@nestim/koishi-plugin-qq-group-manager 1.4.11 → 1.4.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -0
- package/lib/ai/engine.d.ts +6 -5
- package/lib/ai/engine.js +221 -59
- package/lib/ai/learn.d.ts +14 -2
- package/lib/ai/learn.js +94 -7
- package/lib/index.d.ts +2 -0
- package/lib/index.js +1 -0
- package/lib/service.js +3 -1
- package/package.json +1 -1
- package/readme.md +19 -2
- package/src/ai/engine.ts +225 -60
- package/src/ai/learn.ts +95 -7
- package/src/index.ts +1 -0
- package/src/service.js +3 -1
package/lib/index.d.ts
CHANGED
|
@@ -153,6 +153,7 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
153
153
|
aiIdleTopicMinHour: Schema<number, number>;
|
|
154
154
|
aiIdleTopicMaxHour: Schema<number, number>;
|
|
155
155
|
aiIdleTopicCooldownMinutes: Schema<number, number>;
|
|
156
|
+
aiIdleTopicWebSearch: Schema<boolean, boolean>;
|
|
156
157
|
aiSystemPrompt: Schema<string, string>;
|
|
157
158
|
aiActivePersona: Schema<string, string>;
|
|
158
159
|
aiPersonas: Schema<Schemastery.ObjectS<{
|
|
@@ -324,6 +325,7 @@ export declare const Config: Schema<Schemastery.ObjectS<{
|
|
|
324
325
|
aiIdleTopicMinHour: number;
|
|
325
326
|
aiIdleTopicMaxHour: number;
|
|
326
327
|
aiIdleTopicCooldownMinutes: number;
|
|
328
|
+
aiIdleTopicWebSearch: boolean;
|
|
327
329
|
aiSystemPrompt: string;
|
|
328
330
|
aiActivePersona: string;
|
|
329
331
|
aiPersonas: Schemastery.ObjectT<{
|
package/lib/index.js
CHANGED
|
@@ -136,6 +136,7 @@ exports.Config = koishi_1.Schema.intersect([
|
|
|
136
136
|
aiIdleTopicMinHour: koishi_1.Schema.natural().min(0).max(23).default(9).description('主动话题允许的最早小时(0-23)。'),
|
|
137
137
|
aiIdleTopicMaxHour: koishi_1.Schema.natural().min(0).max(24).default(23).description('主动话题允许的最晚小时(不含)。'),
|
|
138
138
|
aiIdleTopicCooldownMinutes: koishi_1.Schema.natural().min(1).max(1440).default(60).description('两次主动话题之间的最小间隔(分钟)。'),
|
|
139
|
+
aiIdleTopicWebSearch: koishi_1.Schema.boolean().default(true).description('主动话题前先搜一次(优先用最近聊天内容做 query,没有上下文就搜当天热点);搜不到或无关会自动忽略。'),
|
|
139
140
|
aiSystemPrompt: koishi_1.Schema.string().role('textarea').default('你是群聊中的友好机器人,请简洁、自然、符合中文互联网语境地回复。').description('默认系统提示词。'),
|
|
140
141
|
aiActivePersona: koishi_1.Schema.string().default('').description('启用的人格 ID(为空时使用默认自称与默认提示词)。'),
|
|
141
142
|
aiPersonas: koishi_1.Schema.array(koishi_1.Schema.object({
|
package/lib/service.js
CHANGED
|
@@ -900,10 +900,12 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
900
900
|
.map((item) => String(item || '').trim())
|
|
901
901
|
.filter(Boolean));
|
|
902
902
|
const label = String(payload && payload.label || '自动归纳');
|
|
903
|
+
const category = String(payload && payload.category || '').trim();
|
|
904
|
+
const fullLabel = category ? `${label} · ${category}` : label;
|
|
903
905
|
return this.runMemoryWriteLocked(async () => {
|
|
904
906
|
const now = new Date();
|
|
905
907
|
const stamp = now.toLocaleString('zh-CN', { hour12: false });
|
|
906
|
-
const block = `## ${stamp} · ${
|
|
908
|
+
const block = `## ${stamp} · ${fullLabel}\n${add}`;
|
|
907
909
|
const existing = (await this.readMemoryFile(scope)).trim();
|
|
908
910
|
const blocks = this.extractMemoryBlocks(existing);
|
|
909
911
|
const kept = [];
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nestim/koishi-plugin-qq-group-manager",
|
|
3
3
|
"description": "Koishi QQ群管理插件(OneBot/LLOneBot):群管命令、权限校验、图片菜单、状态卡片、复读、AI群聊回复、记忆库、识图与自动管控(禁言/踢人)。",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.13",
|
|
5
5
|
"main": "lib/index.js",
|
|
6
6
|
"typings": "lib/index.d.ts",
|
|
7
7
|
"files": [
|
package/readme.md
CHANGED
|
@@ -190,11 +190,11 @@ npm i @nestim/koishi-plugin-qq-group-manager
|
|
|
190
190
|
累计到阈值(aiContextWindow × memoryLearnThresholdScale)
|
|
191
191
|
或空闲满 memoryLearnIdleHours(且期间有新消息)
|
|
192
192
|
↓
|
|
193
|
-
|
|
193
|
+
模型归纳成 1~3 条分类记忆(每条 ≤ memoryLearnMaxChars)
|
|
194
194
|
↓ 与已有记忆去重
|
|
195
195
|
写入 Memory_<群号>_群聊.md / Memory_<QQ号>_私聊.md
|
|
196
196
|
↓ 回推原会话
|
|
197
|
-
|
|
197
|
+
「刚记住了:人物关系:……;偏好立场:……」
|
|
198
198
|
```
|
|
199
199
|
|
|
200
200
|
要点:
|
|
@@ -203,12 +203,29 @@ npm i @nestim/koishi-plugin-qq-group-manager
|
|
|
203
203
|
- **不会串台**:私聊发私聊,群聊发对应群。
|
|
204
204
|
- **不会记废话**:提示词只允许人物关系、稳定偏好、群内黑话、反复出现的话题;
|
|
205
205
|
寒暄、一次性情绪、已结束的接梗、纯表情全部丢弃。
|
|
206
|
+
- **按类分开存**:人物关系 / 偏好立场 / 群内黑话 / 长期话题 / 约定事件 / 其他;
|
|
207
|
+
一条记忆只写一类,标题形如 `## 2026/11/18 18:51:00 · 自动归纳 · 人物关系`。
|
|
208
|
+
同类每 `memoryLearnConsolidateEvery` 条压缩成 1 条,自动记忆总数上限 `memoryLearnMaxEntries`。
|
|
206
209
|
- **不会重复记**:写入前做相似度比对,超过 `memoryLearnDuplicateThreshold` 就跳过。
|
|
207
210
|
- **不会刷爆额度**:每作用域每天最多 `memoryLearnDailyLimit` 次。
|
|
208
211
|
- **系统备注与指令消息不参与归纳**(复读、命令结果等)。
|
|
209
212
|
|
|
210
213
|
自动写入了什么,可以直接在 Koishi 控制台「探索器」打开对应的 `Memory_*.md` 查看。
|
|
211
214
|
条目带的时间戳与来源标记能让你区分手动 `[memory]` 与 AI 自动归纳。
|
|
215
|
+
|
|
216
|
+
## 主动话题
|
|
217
|
+
|
|
218
|
+
群内超过 `aiIdleTopicMinutes` 没有新消息,且处于 `aiIdleTopicMinHour`~`aiIdleTopicMaxHour`
|
|
219
|
+
之间时,AI 会主动发一条话题(两次之间至少隔 `aiIdleTopicCooldownMinutes`)。
|
|
220
|
+
|
|
221
|
+
提示词会带上:
|
|
222
|
+
|
|
223
|
+
- 当前日期、星期、时间与季节(例如“2026年11月18日星期三 18:51(冬)”),并明确要求不要提与季节/时间不符的内容;
|
|
224
|
+
- 该群最近 12 条聊天,要求优先接着最近的话题或梗往下说,而不是凭空抛一个无关话题;
|
|
225
|
+
- 按最近聊天检索到的相关记忆;
|
|
226
|
+
- `aiIdleTopicWebSearch` 开启时(默认开),用最近一句做 query 搜一次;没有上下文就搜当天热点,
|
|
227
|
+
结果不相关会自动忽略,搜不到也不影响发话题。
|
|
228
|
+
|
|
212
229
|
## 外部插件接口(1.2.2+)
|
|
213
230
|
|
|
214
231
|
主插件暴露一个很小的扩展点,第三方插件可以给 AI 追加“说话风格”,或在发送前过滤输出,
|
package/src/ai/engine.ts
CHANGED
|
@@ -24,9 +24,13 @@ import {
|
|
|
24
24
|
isDuplicate,
|
|
25
25
|
isAutoMemoryBlock,
|
|
26
26
|
AUTO_MEMORY_LABEL,
|
|
27
|
+
parseSummaryEntries,
|
|
28
|
+
memoryBlockBody,
|
|
29
|
+
memoryBlockCategory,
|
|
30
|
+
normalizeMemoryCategory,
|
|
27
31
|
} from './learn';
|
|
28
32
|
import { decideTrigger } from './trigger';
|
|
29
|
-
import { buildReplyPrompt, buildUserPrompt } from './prompt';
|
|
33
|
+
import { buildReplyPrompt, buildUserPrompt, renderRecordLine } from './prompt';
|
|
30
34
|
import { ChatProvider } from './provider';
|
|
31
35
|
import { pickImages, resolveImages } from './vision';
|
|
32
36
|
import { selectMemoryBlocks, splitMemoryBlocks, tokenizeForMatch } from './memory';
|
|
@@ -124,6 +128,32 @@ function clipReply(text: string, maxChars: number): string { const max = Math.m
|
|
|
124
128
|
return `${slice}…`;
|
|
125
129
|
}
|
|
126
130
|
|
|
131
|
+
function seasonOfMonth(month: number): string {
|
|
132
|
+
if (month >= 3 && month <= 5) return '春';
|
|
133
|
+
if (month >= 6 && month <= 8) return '夏';
|
|
134
|
+
if (month >= 9 && month <= 11) return '秋';
|
|
135
|
+
return '冬';
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 主动话题用:把当前时间渲染成“2026年1月15日星期四 10:00(冬)” */
|
|
139
|
+
function formatNowText(date: Date): string {
|
|
140
|
+
const formatted = new Intl.DateTimeFormat('zh-CN', {
|
|
141
|
+
timeZone: 'Asia/Shanghai',
|
|
142
|
+
year: 'numeric',
|
|
143
|
+
month: 'long',
|
|
144
|
+
day: 'numeric',
|
|
145
|
+
weekday: 'long',
|
|
146
|
+
hour: '2-digit',
|
|
147
|
+
minute: '2-digit',
|
|
148
|
+
hour12: false,
|
|
149
|
+
}).format(date);
|
|
150
|
+
const month = Number(new Intl.DateTimeFormat('en-US', {
|
|
151
|
+
timeZone: 'Asia/Shanghai',
|
|
152
|
+
month: 'numeric',
|
|
153
|
+
}).format(date));
|
|
154
|
+
return `${formatted}(${seasonOfMonth(month)})`;
|
|
155
|
+
}
|
|
156
|
+
|
|
127
157
|
export class AiEngine {
|
|
128
158
|
readonly state: AiState;
|
|
129
159
|
/** 外部插件扩展点:提示词风格段 + 输出过滤 */
|
|
@@ -697,7 +727,7 @@ export class AiEngine {
|
|
|
697
727
|
|
|
698
728
|
if (cfg.memoryLearnPushBack === false) return;
|
|
699
729
|
|
|
700
|
-
const text = saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}
|
|
730
|
+
const text = (saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}`).slice(0, 300);
|
|
701
731
|
try {
|
|
702
732
|
if (kind === "private") {
|
|
703
733
|
const bot = (kind === "private" && session?.bot) || null;
|
|
@@ -718,7 +748,7 @@ export class AiEngine {
|
|
|
718
748
|
kind: "group" | "private",
|
|
719
749
|
scope: any,
|
|
720
750
|
reason: string,
|
|
721
|
-
): Promise<{ text: string; consolidated: boolean; removed: number } | null> {
|
|
751
|
+
): Promise<{ text: string; consolidated: boolean; removed: number; entries: number } | null> {
|
|
722
752
|
const cfg: any = this.config || {};
|
|
723
753
|
|
|
724
754
|
// 每日上限
|
|
@@ -739,7 +769,7 @@ export class AiEngine {
|
|
|
739
769
|
system: prompt.system,
|
|
740
770
|
user: prompt.user,
|
|
741
771
|
temperature: 0.3,
|
|
742
|
-
maxTokens:
|
|
772
|
+
maxTokens: 800,
|
|
743
773
|
model: String(cfg.memoryLearnModel || "").trim() || undefined,
|
|
744
774
|
});
|
|
745
775
|
if (!result || !result.ok) {
|
|
@@ -756,62 +786,74 @@ export class AiEngine {
|
|
|
756
786
|
}
|
|
757
787
|
|
|
758
788
|
const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
|
|
759
|
-
|
|
760
|
-
if (!
|
|
789
|
+
const entries = parseSummaryEntries(raw, maxChars);
|
|
790
|
+
if (!entries.length) return null;
|
|
761
791
|
|
|
762
|
-
//
|
|
792
|
+
// 去重:分别和已有正文比较
|
|
763
793
|
let existing: string[] = [];
|
|
764
794
|
try {
|
|
765
795
|
const content = await (this.host as any).readMemoryFile(scope);
|
|
766
|
-
existing = String(content || "")
|
|
767
|
-
.
|
|
768
|
-
.
|
|
769
|
-
.filter(Boolean)
|
|
770
|
-
.map((b: string) => b.split("\n").slice(1).join("\n").trim() || b);
|
|
796
|
+
existing = splitMemoryBlocks(String(content || ""))
|
|
797
|
+
.map((item: any) => memoryBlockBody(item.text))
|
|
798
|
+
.filter(Boolean);
|
|
771
799
|
} catch {
|
|
772
800
|
existing = [];
|
|
773
801
|
}
|
|
774
802
|
const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
|
|
775
|
-
|
|
803
|
+
const accepted = entries.filter((entry) => !isDuplicate(entry.text, existing, threshold));
|
|
804
|
+
if (!accepted.length) {
|
|
776
805
|
this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
|
|
777
806
|
return null;
|
|
778
807
|
}
|
|
779
808
|
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
809
|
+
const savedList: Array<{ text: string; consolidated: boolean; removed: number; category: string }> = [];
|
|
810
|
+
for (const entry of accepted) {
|
|
811
|
+
try {
|
|
812
|
+
savedList.push(await this.saveLearnedMemory(kind, scope, entry.text, entry.category));
|
|
813
|
+
} catch (error: any) {
|
|
814
|
+
this.host.logger?.warn?.(`[memory-learn] 写入失败(${entry.category}): ${String(error)}`);
|
|
815
|
+
}
|
|
787
816
|
}
|
|
817
|
+
if (!savedList.length) return null;
|
|
818
|
+
this.learnDaily.set(dailyKey, used + 1);
|
|
788
819
|
|
|
820
|
+
const consolidated = savedList.some((item) => item.consolidated);
|
|
821
|
+
const removed = savedList.reduce((sum, item) => sum + item.removed, 0);
|
|
822
|
+
const categories = savedList.map((item) => item.category).join("、");
|
|
789
823
|
this.host.logger?.info?.(
|
|
790
|
-
`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${
|
|
791
|
-
+ (
|
|
824
|
+
`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${savedList.length} 条,分类:${categories}`
|
|
825
|
+
+ (consolidated ? `,压缩 ${removed} 条旧记忆` : ""),
|
|
792
826
|
);
|
|
793
|
-
return
|
|
827
|
+
return {
|
|
828
|
+
text: savedList.map((item) => `${item.category}:${item.text}`).join(";"),
|
|
829
|
+
consolidated,
|
|
830
|
+
removed,
|
|
831
|
+
entries: savedList.length,
|
|
832
|
+
};
|
|
794
833
|
}
|
|
795
834
|
|
|
796
835
|
/**
|
|
797
|
-
*
|
|
798
|
-
* -
|
|
799
|
-
* -
|
|
836
|
+
* 自动归纳写入策略(分类版):
|
|
837
|
+
* - 记忆按分类存,一条只属于一类;
|
|
838
|
+
* - 同一分类累计 N 条(默认 5)时,把最早的 N-1 条 + 本次压成 1 条;
|
|
839
|
+
* - 自动记忆总数超过上限(默认 15)时,压缩条数最多的分类里最老的一组;
|
|
800
840
|
* - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
|
|
801
841
|
*/
|
|
802
842
|
private async saveLearnedMemory(
|
|
803
843
|
kind: "group" | "private",
|
|
804
844
|
scope: any,
|
|
805
845
|
text: string,
|
|
806
|
-
|
|
846
|
+
category = "其他",
|
|
847
|
+
): Promise<{ text: string; consolidated: boolean; removed: number; category: string }> {
|
|
807
848
|
const cfg: any = this.config || {};
|
|
808
849
|
const host: any = this.host;
|
|
850
|
+
const cat = normalizeMemoryCategory(category);
|
|
809
851
|
const canConsolidate = cfg.memoryLearnConsolidate !== false
|
|
810
852
|
&& typeof host.commitAutoMemory === "function";
|
|
811
853
|
|
|
812
854
|
if (!canConsolidate) {
|
|
813
|
-
await host.saveMemoryToFile("", text, scope, AUTO_MEMORY_LABEL);
|
|
814
|
-
return { text, consolidated: false, removed: 0 };
|
|
855
|
+
await host.saveMemoryToFile("", text, scope, `${AUTO_MEMORY_LABEL} · ${cat}`);
|
|
856
|
+
return { text, consolidated: false, removed: 0, category: cat };
|
|
815
857
|
}
|
|
816
858
|
|
|
817
859
|
const every = Math.max(2, Number(cfg.memoryLearnConsolidateEvery) || 5);
|
|
@@ -828,48 +870,107 @@ export class AiEngine {
|
|
|
828
870
|
autoBlocks = [];
|
|
829
871
|
}
|
|
830
872
|
|
|
831
|
-
const
|
|
832
|
-
const
|
|
833
|
-
const
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
873
|
+
const sameCategory = autoBlocks.filter((block) => memoryBlockCategory(block) === cat);
|
|
874
|
+
const projectedSame = sameCategory.length + 1;
|
|
875
|
+
const reachedBatch = projectedSame >= every;
|
|
876
|
+
const reachedCap = autoBlocks.length + 1 > maxEntries && autoBlocks.length > 0;
|
|
877
|
+
|
|
878
|
+
// 常规批量:同分类最早的 N-1 条 + 本次,正好 N 条压成 1 条
|
|
879
|
+
if (reachedBatch) {
|
|
880
|
+
const take = Math.max(1, Math.min(every - 1, sameCategory.length));
|
|
881
|
+
const remove = sameCategory.slice(0, take);
|
|
882
|
+
let stored = text;
|
|
883
|
+
let consolidated = false;
|
|
884
|
+
try {
|
|
885
|
+
const merged = await this.consolidateMemories(kind, remove, text, maxChars, cat);
|
|
886
|
+
if (merged) {
|
|
887
|
+
stored = merged;
|
|
888
|
+
consolidated = true;
|
|
889
|
+
}
|
|
890
|
+
} catch (error: any) {
|
|
891
|
+
this.host.logger?.warn?.(`[memory-learn] 压缩异常: ${String(error)}`);
|
|
892
|
+
}
|
|
893
|
+
await host.commitAutoMemory(scope, {
|
|
894
|
+
add: stored,
|
|
895
|
+
remove: consolidated ? remove : [],
|
|
896
|
+
label: AUTO_MEMORY_LABEL,
|
|
897
|
+
category: cat,
|
|
898
|
+
});
|
|
899
|
+
return { text: stored, consolidated, removed: consolidated ? remove.length : 0, category: cat };
|
|
837
900
|
}
|
|
838
901
|
|
|
839
|
-
//
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
902
|
+
// 超过总上限:先压缩“条数最多”的分类里最老的一组(不带本次新记忆),再追加本次
|
|
903
|
+
if (reachedCap) {
|
|
904
|
+
const byCategory = new Map<string, string[]>();
|
|
905
|
+
for (const block of autoBlocks) {
|
|
906
|
+
const key = memoryBlockCategory(block);
|
|
907
|
+
const list = byCategory.get(key) || [];
|
|
908
|
+
list.push(block);
|
|
909
|
+
byCategory.set(key, list);
|
|
910
|
+
}
|
|
911
|
+
let targetCategory = "";
|
|
912
|
+
let targetBlocks: string[] = [];
|
|
913
|
+
for (const [key, list] of byCategory) {
|
|
914
|
+
if (list.length >= 2 && list.length > targetBlocks.length) {
|
|
915
|
+
targetCategory = key;
|
|
916
|
+
targetBlocks = list;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
if (targetBlocks.length) {
|
|
920
|
+
const take = Math.max(1, Math.min(every - 1, targetBlocks.length));
|
|
921
|
+
const remove = targetBlocks.slice(0, take);
|
|
922
|
+
if (targetCategory === cat) {
|
|
923
|
+
// 同一分类:把本次新记忆一起并进去
|
|
924
|
+
let merged = "";
|
|
925
|
+
try {
|
|
926
|
+
merged = await this.consolidateMemories(kind, remove, text, maxChars, cat);
|
|
927
|
+
} catch (error: any) {
|
|
928
|
+
this.host.logger?.warn?.(`[memory-learn] 上限压缩异常: ${String(error)}`);
|
|
929
|
+
}
|
|
930
|
+
if (merged) {
|
|
931
|
+
await host.commitAutoMemory(scope, {
|
|
932
|
+
add: merged,
|
|
933
|
+
remove,
|
|
934
|
+
label: AUTO_MEMORY_LABEL,
|
|
935
|
+
category: cat,
|
|
936
|
+
});
|
|
937
|
+
return { text: merged, consolidated: true, removed: remove.length, category: cat };
|
|
938
|
+
}
|
|
939
|
+
} else {
|
|
940
|
+
// 不同分类:只压缩旧的一组,本次仍然单独追加
|
|
941
|
+
try {
|
|
942
|
+
const merged = await this.consolidateMemories(kind, remove, "", maxChars, targetCategory);
|
|
943
|
+
if (merged) {
|
|
944
|
+
await host.commitAutoMemory(scope, {
|
|
945
|
+
add: merged,
|
|
946
|
+
remove,
|
|
947
|
+
label: AUTO_MEMORY_LABEL,
|
|
948
|
+
category: targetCategory,
|
|
949
|
+
});
|
|
950
|
+
}
|
|
951
|
+
} catch (error: any) {
|
|
952
|
+
this.host.logger?.warn?.(`[memory-learn] 上限压缩异常: ${String(error)}`);
|
|
953
|
+
}
|
|
954
|
+
}
|
|
850
955
|
}
|
|
851
|
-
} catch (error: any) {
|
|
852
|
-
this.host.logger?.warn?.(`[memory-learn] 压缩异常: ${String(error)}`);
|
|
853
956
|
}
|
|
854
957
|
|
|
855
|
-
await host.commitAutoMemory(scope, {
|
|
856
|
-
|
|
857
|
-
remove: consolidated ? remove : [],
|
|
858
|
-
label: AUTO_MEMORY_LABEL,
|
|
859
|
-
});
|
|
860
|
-
return { text: stored, consolidated, removed: consolidated ? remove.length : 0 };
|
|
958
|
+
await host.commitAutoMemory(scope, { add: text, label: AUTO_MEMORY_LABEL, category: cat });
|
|
959
|
+
return { text, consolidated: false, removed: 0, category: cat };
|
|
861
960
|
}
|
|
862
961
|
|
|
863
|
-
/**
|
|
962
|
+
/** 调模型把若干条同分类自动记忆压成一条更短的 */
|
|
864
963
|
private async consolidateMemories(
|
|
865
964
|
kind: "group" | "private",
|
|
866
965
|
blocks: string[],
|
|
867
966
|
fresh: string,
|
|
868
967
|
maxChars: number,
|
|
968
|
+
category = "其他",
|
|
869
969
|
): Promise<string> {
|
|
870
970
|
const cfg: any = this.config || {};
|
|
871
971
|
const marker = `## · ${AUTO_MEMORY_LABEL}`;
|
|
872
|
-
const
|
|
972
|
+
const input = fresh ? [...blocks, `${marker}\n${fresh}`] : blocks;
|
|
973
|
+
const prompt = buildConsolidatePrompt(input, { maxChars, kind, category });
|
|
873
974
|
const result = await this.provider.chat({
|
|
874
975
|
system: prompt.system,
|
|
875
976
|
user: prompt.user,
|
|
@@ -987,7 +1088,9 @@ export class AiEngine {
|
|
|
987
1088
|
} catch {
|
|
988
1089
|
return [];
|
|
989
1090
|
}
|
|
990
|
-
const blocks = splitMemoryBlocks(content)
|
|
1091
|
+
const blocks = splitMemoryBlocks(content)
|
|
1092
|
+
.map((item) => ({ ...item, text: memoryBlockBody(item.text) }))
|
|
1093
|
+
.filter((item) => item.text);
|
|
991
1094
|
if (!blocks.length) return [];
|
|
992
1095
|
const recent = state.records.slice(-3).map((item) => item.text);
|
|
993
1096
|
const selected = selectMemoryBlocks(blocks, [record.text, ...recent], {
|
|
@@ -1245,21 +1348,83 @@ export class AiEngine {
|
|
|
1245
1348
|
return this.provider.chat(request);
|
|
1246
1349
|
}
|
|
1247
1350
|
|
|
1248
|
-
/**
|
|
1351
|
+
/** 群内长时间没人说话时,生成一条主动话题:带时间/季节、最近上下文、相关记忆和联网结果。 */
|
|
1249
1352
|
async idleTopic(groupId: string): Promise<string> {
|
|
1250
1353
|
const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
|
|
1354
|
+
const hookCtx = { session, groupId, mode: 'reply' as const };
|
|
1251
1355
|
let sections: string[] = [];
|
|
1252
1356
|
let personaOverride: string | null = null;
|
|
1253
1357
|
try {
|
|
1254
|
-
const hookCtx = { session, groupId, mode: 'reply' as const };
|
|
1255
1358
|
sections = this.clampStyle(await this.hooks.collectSections(hookCtx));
|
|
1256
1359
|
personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
|
|
1257
1360
|
} catch { /* ignore */ }
|
|
1361
|
+
|
|
1362
|
+
// 最近上下文:优先 onebot:<群号>,兼容其它 platform
|
|
1363
|
+
let state = this.state.peek(`onebot:${groupId}`);
|
|
1364
|
+
if (!state) {
|
|
1365
|
+
for (const [key, value] of this.state.entries()) {
|
|
1366
|
+
if (key.endsWith(`:${groupId}`)) {
|
|
1367
|
+
state = value;
|
|
1368
|
+
break;
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
const records = state ? state.records.slice(-12) : [];
|
|
1373
|
+
const contextText = records
|
|
1374
|
+
.map((record) => renderRecordLine(record, this.selfName))
|
|
1375
|
+
.join('\n');
|
|
1376
|
+
const lastAt = records.length ? Number(records[records.length - 1].at) || 0 : 0;
|
|
1377
|
+
const gapMinutes = lastAt ? Math.max(0, Math.round((this.now() - lastAt) / 60000)) : 0;
|
|
1378
|
+
const contextLabel = gapMinutes
|
|
1379
|
+
? `【最近聊天】(最后一条 ${gapMinutes} 分钟前)`
|
|
1380
|
+
: '【最近聊天】';
|
|
1381
|
+
|
|
1382
|
+
// 相关记忆:用最近几句话做查询;没有上下文就取最近两条
|
|
1383
|
+
let memories: string[] = [];
|
|
1384
|
+
try {
|
|
1385
|
+
const scope = typeof (this.host as any).memoryScopeOf === 'function'
|
|
1386
|
+
? (this.host as any).memoryScopeOf(session)
|
|
1387
|
+
: { kind: 'group', id: groupId };
|
|
1388
|
+
const content = await this.host.readMemoryFile(scope);
|
|
1389
|
+
const blocks = splitMemoryBlocks(content)
|
|
1390
|
+
.map((item) => ({ ...item, text: memoryBlockBody(item.text) }))
|
|
1391
|
+
.filter((item) => item.text);
|
|
1392
|
+
const queryTexts = records.slice(-4).map((record) => record.text).filter(Boolean);
|
|
1393
|
+
const selected = queryTexts.length
|
|
1394
|
+
? selectMemoryBlocks(blocks, queryTexts, { limit: 3, minScore: 0.12, maxChars: 140 })
|
|
1395
|
+
: blocks.slice(-2);
|
|
1396
|
+
memories = selected.map((item) => item.text);
|
|
1397
|
+
} catch { /* ignore */ }
|
|
1398
|
+
|
|
1399
|
+
// 联网:用最近一句做 query;没有上下文就问今天的热点
|
|
1400
|
+
let searchSection = '';
|
|
1401
|
+
if (this.config.aiIdleTopicWebSearch !== false) {
|
|
1402
|
+
const lastText = records.length ? String(records[records.length - 1].text || '') : '';
|
|
1403
|
+
const cleanLast = lastText
|
|
1404
|
+
.replace(/\[[^\]]{1,16}\]/g, ' ')
|
|
1405
|
+
.replace(/[图片表情视频语音文件]/g, ' ')
|
|
1406
|
+
.replace(/\s+/g, ' ')
|
|
1407
|
+
.trim();
|
|
1408
|
+
const seed = cleanLast.length >= 4 ? cleanLast : '今天有什么热点话题';
|
|
1409
|
+
try {
|
|
1410
|
+
searchSection = await this.webSearch({ text: seed } as ChatRecord, session, true);
|
|
1411
|
+
} catch { /* ignore */ }
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
const nowText = formatNowText(new Date(this.now()));
|
|
1258
1415
|
const system = [
|
|
1259
1416
|
`你是 QQ 群 ${groupId} 里的一个普通成员。`,
|
|
1260
1417
|
personaOverride || this.personaPrompt,
|
|
1418
|
+
`现在是 ${nowText}。`,
|
|
1261
1419
|
'群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
|
|
1262
|
-
'
|
|
1420
|
+
contextText ? `${contextLabel}\n${contextText}` : '',
|
|
1421
|
+
memories.length ? `【相关记忆】\n${memories.map((item) => `- ${item}`).join('\n')}` : '',
|
|
1422
|
+
searchSection,
|
|
1423
|
+
'要求:',
|
|
1424
|
+
'- 优先接着最近聊天里的话题或梗往下说;没有可接的,再结合当前时间、季节和记忆找话题;',
|
|
1425
|
+
'- 不要提与现在时间、季节不符的内容(按上面给出的日期判断,不要凭印象说夏天/冬天);',
|
|
1426
|
+
'- 联网结果只在确实相关时参考,不相关就忽略,不要编造新闻;',
|
|
1427
|
+
'- 不要问“在吗”,不要提“很久没人说话”,不要自我介绍;',
|
|
1263
1428
|
...sections,
|
|
1264
1429
|
].filter(Boolean).join('\n');
|
|
1265
1430
|
const result = await this.provider.chat({
|
package/src/ai/learn.ts
CHANGED
|
@@ -12,6 +12,44 @@ import { truncate } from '../core/text';
|
|
|
12
12
|
|
|
13
13
|
export const MAX_SUMMARY_CHARS = 150;
|
|
14
14
|
|
|
15
|
+
/** 记忆分类:一条记忆只属于一类,便于存储与检索 */
|
|
16
|
+
export const MEMORY_CATEGORIES = ['人物关系', '偏好立场', '群内黑话', '长期话题', '约定事件', '其他'] as const;
|
|
17
|
+
|
|
18
|
+
const CATEGORY_ALIASES: Record<string, string> = {
|
|
19
|
+
人物: '人物关系',
|
|
20
|
+
关系: '人物关系',
|
|
21
|
+
称呼: '人物关系',
|
|
22
|
+
身份: '人物关系',
|
|
23
|
+
偏好: '偏好立场',
|
|
24
|
+
立场: '偏好立场',
|
|
25
|
+
喜好: '偏好立场',
|
|
26
|
+
观点: '偏好立场',
|
|
27
|
+
黑话: '群内黑话',
|
|
28
|
+
梗: '群内黑话',
|
|
29
|
+
术语: '群内黑话',
|
|
30
|
+
缩写: '群内黑话',
|
|
31
|
+
话题: '长期话题',
|
|
32
|
+
约定: '约定事件',
|
|
33
|
+
事件: '约定事件',
|
|
34
|
+
计划: '约定事件',
|
|
35
|
+
其他: '其他',
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export function normalizeMemoryCategory(raw: string): string {
|
|
39
|
+
const value = String(raw || '').trim().replace(/[\s*_`「」【】\[\]]/g, '');
|
|
40
|
+
if (!value) return '其他';
|
|
41
|
+
if ((MEMORY_CATEGORIES as readonly string[]).includes(value)) return value;
|
|
42
|
+
for (const key of Object.keys(CATEGORY_ALIASES)) {
|
|
43
|
+
if (value.includes(key)) return CATEGORY_ALIASES[key];
|
|
44
|
+
}
|
|
45
|
+
return '其他';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface SummaryEntry {
|
|
49
|
+
category: string;
|
|
50
|
+
text: string;
|
|
51
|
+
}
|
|
52
|
+
|
|
15
53
|
export interface EvictedLike {
|
|
16
54
|
id?: string;
|
|
17
55
|
userId?: string;
|
|
@@ -116,7 +154,7 @@ export function renderForSummary(records: EvictedLike[], selfName = 'bot'): stri
|
|
|
116
154
|
return lines.join('\n');
|
|
117
155
|
}
|
|
118
156
|
|
|
119
|
-
/**
|
|
157
|
+
/** 归纳提示词:按类别输出多条,一条只写一类 */
|
|
120
158
|
export function buildSummaryPrompt(
|
|
121
159
|
records: EvictedLike[],
|
|
122
160
|
options: { kind?: string; selfName?: string } = {},
|
|
@@ -131,20 +169,61 @@ export function buildSummaryPrompt(
|
|
|
131
169
|
'2. 稳定的偏好、立场、习惯(不是一时的情绪)',
|
|
132
170
|
'3. 群内或两人之间约定俗成的说法、黑话',
|
|
133
171
|
'4. 反复出现、以后还会聊到的话题',
|
|
172
|
+
'5. 明确的约定、时间、计划',
|
|
134
173
|
'',
|
|
135
174
|
'必须丢掉:寒暄、打招呼、一次性的抱怨或玩笑、已经结束的接梗、纯表情。',
|
|
136
175
|
'',
|
|
137
176
|
'输出要求:',
|
|
138
|
-
'-
|
|
139
|
-
`-
|
|
177
|
+
'- 按类别拆开,每条一行,格式必须是「类别:内容」;',
|
|
178
|
+
`- 类别只能是:${MEMORY_CATEGORIES.join('、')};`,
|
|
179
|
+
'- 一条记忆只写一个类别,不要在一句里混入另一个类别的内容;',
|
|
180
|
+
'- 最多输出 3 条;同类最多 2 条;',
|
|
181
|
+
'- 不要标题、列表符号、编号、Markdown、引号;',
|
|
182
|
+
`- 每条不超过 ${MAX_SUMMARY_CHARS} 字;`,
|
|
140
183
|
'- 用陈述句写事实,不要写「他们聊到」「讨论了」这类过程描述;',
|
|
141
184
|
'- 如果没有任何值得长期记住的内容,只输出一个词:NONE',
|
|
142
185
|
].join('\n');
|
|
143
186
|
|
|
144
|
-
const user = ['【记录】', body || '(空)', '', '
|
|
187
|
+
const user = ['【记录】', body || '(空)', '', '现在输出分类后的记忆(类别:内容),或输出 NONE。'].join('\n');
|
|
145
188
|
return { system, user };
|
|
146
189
|
}
|
|
147
190
|
|
|
191
|
+
/** 解析模型输出的多分类记忆 */
|
|
192
|
+
export function parseSummaryEntries(raw: string, maxChars = MAX_SUMMARY_CHARS): SummaryEntry[] {
|
|
193
|
+
let text = String(raw || '').trim();
|
|
194
|
+
if (!text) return [];
|
|
195
|
+
text = text
|
|
196
|
+
.replace(/^```[a-zA-Z0-9_-]*\s*\n?/, '')
|
|
197
|
+
.replace(/\n?\s*```\s*$/, '')
|
|
198
|
+
.trim();
|
|
199
|
+
if (/^(?:none|无|没有|n\/a)$/i.test(text)) return [];
|
|
200
|
+
|
|
201
|
+
const lines = text
|
|
202
|
+
.split(/\r?\n/)
|
|
203
|
+
.map((line) => line.replace(/^\s*(?:[-*+·]|\d+[.)、])\s*/, '').trim())
|
|
204
|
+
.filter(Boolean);
|
|
205
|
+
|
|
206
|
+
const out: SummaryEntry[] = [];
|
|
207
|
+
const seen = new Set<string>();
|
|
208
|
+
for (const line of lines) {
|
|
209
|
+
let category = '其他';
|
|
210
|
+
let body = line;
|
|
211
|
+
const match = /^([^::]{1,12})[::]\s*(.+)$/.exec(line);
|
|
212
|
+
if (match) {
|
|
213
|
+
category = normalizeMemoryCategory(match[1]);
|
|
214
|
+
body = match[2];
|
|
215
|
+
}
|
|
216
|
+
const cleaned = cleanSummary(body.replace(/\*\*/g, ''), maxChars);
|
|
217
|
+
if (!cleaned) continue;
|
|
218
|
+
const key = `${category}|${cleaned}`;
|
|
219
|
+
if (seen.has(key)) continue;
|
|
220
|
+
seen.add(key);
|
|
221
|
+
out.push({ category, text: cleaned });
|
|
222
|
+
if (out.length >= 3) break;
|
|
223
|
+
}
|
|
224
|
+
return out;
|
|
225
|
+
}
|
|
226
|
+
|
|
148
227
|
/** 清洗模型输出 */
|
|
149
228
|
export function cleanSummary(raw: string, maxChars = MAX_SUMMARY_CHARS): string {
|
|
150
229
|
let text = String(raw || '').trim();
|
|
@@ -241,27 +320,36 @@ export function memoryBlockBody(block: string): string {
|
|
|
241
320
|
return lines.slice(1).join('\n').trim();
|
|
242
321
|
}
|
|
243
322
|
|
|
323
|
+
/** 取记忆块的分类;旧格式没有分类时归入「其他」 */
|
|
324
|
+
export function memoryBlockCategory(block: string): string {
|
|
325
|
+
const first = String(block || '').split('\n', 1)[0] || '';
|
|
326
|
+
const match = /·\s*自动归纳\s*·\s*([^·\n]+)/.exec(first);
|
|
327
|
+
return normalizeMemoryCategory(match ? match[1] : '其他');
|
|
328
|
+
}
|
|
329
|
+
|
|
244
330
|
/**
|
|
245
|
-
* 记忆压缩提示词:把 N
|
|
331
|
+
* 记忆压缩提示词:把 N 条同分类的自动归纳合并成一条更短的。
|
|
246
332
|
*
|
|
247
333
|
* 目的不是“再总结一遍”,而是去掉重复与过时信息——群里连续几天聊同一件事时,
|
|
248
334
|
* 自动归纳会反复产出高度相似的条目,压缩后只保留事实差异。
|
|
249
335
|
*/
|
|
250
336
|
export function buildConsolidatePrompt(
|
|
251
337
|
blocks: string[],
|
|
252
|
-
options: { maxChars?: number; kind?: string } = {},
|
|
338
|
+
options: { maxChars?: number; kind?: string; category?: string } = {},
|
|
253
339
|
): { system: string; user: string } {
|
|
254
340
|
const maxChars = Math.max(40, Number(options.maxChars) || 90);
|
|
255
341
|
const label = options.kind === 'private' ? '私聊' : '群聊';
|
|
342
|
+
const category = normalizeMemoryCategory(options.category || '其他');
|
|
256
343
|
const bodies = (blocks || [])
|
|
257
344
|
.map((block) => memoryBlockBody(block).replace(/\s+/g, ' ').trim())
|
|
258
345
|
.filter(Boolean);
|
|
259
346
|
|
|
260
347
|
const system = [
|
|
261
|
-
`你在压缩一段${label}
|
|
348
|
+
`你在压缩一段${label}里「${category}」类的长期记忆。`,
|
|
262
349
|
`下面有 ${bodies.length} 条已经归纳过的记忆,请合并成一条。`,
|
|
263
350
|
'',
|
|
264
351
|
'要求:',
|
|
352
|
+
`- 只合并「${category}」这一类的信息,不要混入其他类别;`,
|
|
265
353
|
'- 只保留互不重复的事实:人物与称呼、关系、稳定偏好、反复出现的话题;',
|
|
266
354
|
'- 删掉重复表述、一次性情绪、已经过时的细节;',
|
|
267
355
|
'- 不要编造,不要写“他们聊到”“讨论了”这类过程描述;',
|