@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/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,37 @@
|
|
|
2
2
|
|
|
3
3
|
本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
|
|
4
4
|
|
|
5
|
+
## 1.4.13
|
|
6
|
+
|
|
7
|
+
### 修复
|
|
8
|
+
|
|
9
|
+
- 主动话题的最近聊天标注「最后一条 X 分钟前」,避免把很久以前的消息当成当前话题;
|
|
10
|
+
- 主动话题的联网搜索会先去掉 `[图片]`、`[表情]` 等占位符,避免拿占位符当搜索词;
|
|
11
|
+
- 归纳解析会去掉 `**` 等 Markdown 残留,分类名更干净。
|
|
12
|
+
|
|
13
|
+
## 1.4.12
|
|
14
|
+
|
|
15
|
+
### 改进
|
|
16
|
+
|
|
17
|
+
- **主动话题结合上下文、记忆与联网搜索**:
|
|
18
|
+
- 提示词带当前日期、星期、时间与季节(如“2026年11月18日星期三 18:51(冬)”),
|
|
19
|
+
并明确要求不要提与当前季节/时间不符的内容;
|
|
20
|
+
- 带上该群最近 12 条聊天,要求优先接着最近的话题或梗往下说,而不是凭空抛一个无关话题;
|
|
21
|
+
- 按最近聊天检索相关记忆,一起放进提示词;
|
|
22
|
+
- 新增 `aiIdleTopicWebSearch`(默认开):用最近一句做 query;没有上下文就搜当天热点。
|
|
23
|
+
结果不相关会自动忽略,搜不到也不影响发话题。
|
|
24
|
+
|
|
25
|
+
### 记忆分类
|
|
26
|
+
|
|
27
|
+
- **自动归纳按类别分开存**:一条记忆只属于一类,标题格式为
|
|
28
|
+
`## 2026/11/18 18:51:00 · 自动归纳 · 人物关系`。
|
|
29
|
+
- 类别:人物关系 / 偏好立场 / 群内黑话 / 长期话题 / 约定事件 / 其他;
|
|
30
|
+
- 一次归纳最多产出 3 条,同类最多 2 条,不再把不同类的事实塞进一句;
|
|
31
|
+
- 压缩只在**同分类**内进行(每 `memoryLearnConsolidateEvery` 条同类压 1 条);
|
|
32
|
+
总数超过 `memoryLearnMaxEntries` 时优先压缩条数最多的分类;
|
|
33
|
+
- 旧记忆没有分类,自动按「其他」处理,不丢数据;
|
|
34
|
+
- 记忆注入时只带正文,不再把 `## 时间 · 自动归纳` 标题塞进提示词。
|
|
35
|
+
|
|
5
36
|
## 1.4.11
|
|
6
37
|
|
|
7
38
|
### 修复
|
package/lib/ai/engine.d.ts
CHANGED
|
@@ -143,13 +143,14 @@ export declare class AiEngine {
|
|
|
143
143
|
/** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
|
|
144
144
|
private summarizeRecords;
|
|
145
145
|
/**
|
|
146
|
-
*
|
|
147
|
-
* -
|
|
148
|
-
* -
|
|
146
|
+
* 自动归纳写入策略(分类版):
|
|
147
|
+
* - 记忆按分类存,一条只属于一类;
|
|
148
|
+
* - 同一分类累计 N 条(默认 5)时,把最早的 N-1 条 + 本次压成 1 条;
|
|
149
|
+
* - 自动记忆总数超过上限(默认 15)时,压缩条数最多的分类里最老的一组;
|
|
149
150
|
* - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
|
|
150
151
|
*/
|
|
151
152
|
private saveLearnedMemory;
|
|
152
|
-
/**
|
|
153
|
+
/** 调模型把若干条同分类自动记忆压成一条更短的 */
|
|
153
154
|
private consolidateMemories;
|
|
154
155
|
private findBot;
|
|
155
156
|
private isMention;
|
|
@@ -169,7 +170,7 @@ export declare class AiEngine {
|
|
|
169
170
|
handle(session: any): Promise<void>;
|
|
170
171
|
/** 供外部插件(如私聊插件)复用同一个模型 provider。 */
|
|
171
172
|
chat(request: any): Promise<import("./provider").ChatResult>;
|
|
172
|
-
/**
|
|
173
|
+
/** 群内长时间没人说话时,生成一条主动话题:带时间/季节、最近上下文、相关记忆和联网结果。 */
|
|
173
174
|
idleTopic(groupId: string): Promise<string>;
|
|
174
175
|
/** 需要时调用 DeepSeek Search API;失败/不支持/没结果都返回空串,继续普通回复。 */
|
|
175
176
|
private webSearch;
|
package/lib/ai/engine.js
CHANGED
|
@@ -99,6 +99,33 @@ function clipReply(text, maxChars) {
|
|
|
99
99
|
return slice.slice(0, boundary + 1);
|
|
100
100
|
return `${slice}…`;
|
|
101
101
|
}
|
|
102
|
+
function seasonOfMonth(month) {
|
|
103
|
+
if (month >= 3 && month <= 5)
|
|
104
|
+
return '春';
|
|
105
|
+
if (month >= 6 && month <= 8)
|
|
106
|
+
return '夏';
|
|
107
|
+
if (month >= 9 && month <= 11)
|
|
108
|
+
return '秋';
|
|
109
|
+
return '冬';
|
|
110
|
+
}
|
|
111
|
+
/** 主动话题用:把当前时间渲染成“2026年1月15日星期四 10:00(冬)” */
|
|
112
|
+
function formatNowText(date) {
|
|
113
|
+
const formatted = new Intl.DateTimeFormat('zh-CN', {
|
|
114
|
+
timeZone: 'Asia/Shanghai',
|
|
115
|
+
year: 'numeric',
|
|
116
|
+
month: 'long',
|
|
117
|
+
day: 'numeric',
|
|
118
|
+
weekday: 'long',
|
|
119
|
+
hour: '2-digit',
|
|
120
|
+
minute: '2-digit',
|
|
121
|
+
hour12: false,
|
|
122
|
+
}).format(date);
|
|
123
|
+
const month = Number(new Intl.DateTimeFormat('en-US', {
|
|
124
|
+
timeZone: 'Asia/Shanghai',
|
|
125
|
+
month: 'numeric',
|
|
126
|
+
}).format(date));
|
|
127
|
+
return `${formatted}(${seasonOfMonth(month)})`;
|
|
128
|
+
}
|
|
102
129
|
class AiEngine {
|
|
103
130
|
state;
|
|
104
131
|
/** 外部插件扩展点:提示词风格段 + 输出过滤 */
|
|
@@ -648,7 +675,7 @@ class AiEngine {
|
|
|
648
675
|
return;
|
|
649
676
|
if (cfg.memoryLearnPushBack === false)
|
|
650
677
|
return;
|
|
651
|
-
const text = saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}
|
|
678
|
+
const text = (saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}`).slice(0, 300);
|
|
652
679
|
try {
|
|
653
680
|
if (kind === "private") {
|
|
654
681
|
const bot = (kind === "private" && session?.bot) || null;
|
|
@@ -686,7 +713,7 @@ class AiEngine {
|
|
|
686
713
|
system: prompt.system,
|
|
687
714
|
user: prompt.user,
|
|
688
715
|
temperature: 0.3,
|
|
689
|
-
maxTokens:
|
|
716
|
+
maxTokens: 800,
|
|
690
717
|
model: String(cfg.memoryLearnModel || "").trim() || undefined,
|
|
691
718
|
});
|
|
692
719
|
if (!result || !result.ok) {
|
|
@@ -703,54 +730,66 @@ class AiEngine {
|
|
|
703
730
|
return null;
|
|
704
731
|
}
|
|
705
732
|
const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
|
|
706
|
-
|
|
707
|
-
if (!
|
|
733
|
+
const entries = (0, learn_1.parseSummaryEntries)(raw, maxChars);
|
|
734
|
+
if (!entries.length)
|
|
708
735
|
return null;
|
|
709
|
-
//
|
|
736
|
+
// 去重:分别和已有正文比较
|
|
710
737
|
let existing = [];
|
|
711
738
|
try {
|
|
712
739
|
const content = await this.host.readMemoryFile(scope);
|
|
713
|
-
existing = String(content || "")
|
|
714
|
-
.
|
|
715
|
-
.
|
|
716
|
-
.filter(Boolean)
|
|
717
|
-
.map((b) => b.split("\n").slice(1).join("\n").trim() || b);
|
|
740
|
+
existing = (0, memory_1.splitMemoryBlocks)(String(content || ""))
|
|
741
|
+
.map((item) => (0, learn_1.memoryBlockBody)(item.text))
|
|
742
|
+
.filter(Boolean);
|
|
718
743
|
}
|
|
719
744
|
catch {
|
|
720
745
|
existing = [];
|
|
721
746
|
}
|
|
722
747
|
const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
|
|
723
|
-
|
|
748
|
+
const accepted = entries.filter((entry) => !(0, learn_1.isDuplicate)(entry.text, existing, threshold));
|
|
749
|
+
if (!accepted.length) {
|
|
724
750
|
this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
|
|
725
751
|
return null;
|
|
726
752
|
}
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
753
|
+
const savedList = [];
|
|
754
|
+
for (const entry of accepted) {
|
|
755
|
+
try {
|
|
756
|
+
savedList.push(await this.saveLearnedMemory(kind, scope, entry.text, entry.category));
|
|
757
|
+
}
|
|
758
|
+
catch (error) {
|
|
759
|
+
this.host.logger?.warn?.(`[memory-learn] 写入失败(${entry.category}): ${String(error)}`);
|
|
760
|
+
}
|
|
731
761
|
}
|
|
732
|
-
|
|
733
|
-
this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
|
|
762
|
+
if (!savedList.length)
|
|
734
763
|
return null;
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
764
|
+
this.learnDaily.set(dailyKey, used + 1);
|
|
765
|
+
const consolidated = savedList.some((item) => item.consolidated);
|
|
766
|
+
const removed = savedList.reduce((sum, item) => sum + item.removed, 0);
|
|
767
|
+
const categories = savedList.map((item) => item.category).join("、");
|
|
768
|
+
this.host.logger?.info?.(`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${savedList.length} 条,分类:${categories}`
|
|
769
|
+
+ (consolidated ? `,压缩 ${removed} 条旧记忆` : ""));
|
|
770
|
+
return {
|
|
771
|
+
text: savedList.map((item) => `${item.category}:${item.text}`).join(";"),
|
|
772
|
+
consolidated,
|
|
773
|
+
removed,
|
|
774
|
+
entries: savedList.length,
|
|
775
|
+
};
|
|
739
776
|
}
|
|
740
777
|
/**
|
|
741
|
-
*
|
|
742
|
-
* -
|
|
743
|
-
* -
|
|
778
|
+
* 自动归纳写入策略(分类版):
|
|
779
|
+
* - 记忆按分类存,一条只属于一类;
|
|
780
|
+
* - 同一分类累计 N 条(默认 5)时,把最早的 N-1 条 + 本次压成 1 条;
|
|
781
|
+
* - 自动记忆总数超过上限(默认 15)时,压缩条数最多的分类里最老的一组;
|
|
744
782
|
* - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
|
|
745
783
|
*/
|
|
746
|
-
async saveLearnedMemory(kind, scope, text) {
|
|
784
|
+
async saveLearnedMemory(kind, scope, text, category = "其他") {
|
|
747
785
|
const cfg = this.config || {};
|
|
748
786
|
const host = this.host;
|
|
787
|
+
const cat = (0, learn_1.normalizeMemoryCategory)(category);
|
|
749
788
|
const canConsolidate = cfg.memoryLearnConsolidate !== false
|
|
750
789
|
&& typeof host.commitAutoMemory === "function";
|
|
751
790
|
if (!canConsolidate) {
|
|
752
|
-
await host.saveMemoryToFile("", text, scope, learn_1.AUTO_MEMORY_LABEL);
|
|
753
|
-
return { text, consolidated: false, removed: 0 };
|
|
791
|
+
await host.saveMemoryToFile("", text, scope, `${learn_1.AUTO_MEMORY_LABEL} · ${cat}`);
|
|
792
|
+
return { text, consolidated: false, removed: 0, category: cat };
|
|
754
793
|
}
|
|
755
794
|
const every = Math.max(2, Number(cfg.memoryLearnConsolidateEvery) || 5);
|
|
756
795
|
const maxEntries = Math.max(1, Number(cfg.memoryLearnMaxEntries) || 15);
|
|
@@ -765,40 +804,101 @@ class AiEngine {
|
|
|
765
804
|
catch {
|
|
766
805
|
autoBlocks = [];
|
|
767
806
|
}
|
|
768
|
-
const
|
|
769
|
-
const
|
|
770
|
-
const
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
consolidated = true;
|
|
807
|
+
const sameCategory = autoBlocks.filter((block) => (0, learn_1.memoryBlockCategory)(block) === cat);
|
|
808
|
+
const projectedSame = sameCategory.length + 1;
|
|
809
|
+
const reachedBatch = projectedSame >= every;
|
|
810
|
+
const reachedCap = autoBlocks.length + 1 > maxEntries && autoBlocks.length > 0;
|
|
811
|
+
// 常规批量:同分类最早的 N-1 条 + 本次,正好 N 条压成 1 条
|
|
812
|
+
if (reachedBatch) {
|
|
813
|
+
const take = Math.max(1, Math.min(every - 1, sameCategory.length));
|
|
814
|
+
const remove = sameCategory.slice(0, take);
|
|
815
|
+
let stored = text;
|
|
816
|
+
let consolidated = false;
|
|
817
|
+
try {
|
|
818
|
+
const merged = await this.consolidateMemories(kind, remove, text, maxChars, cat);
|
|
819
|
+
if (merged) {
|
|
820
|
+
stored = merged;
|
|
821
|
+
consolidated = true;
|
|
822
|
+
}
|
|
785
823
|
}
|
|
824
|
+
catch (error) {
|
|
825
|
+
this.host.logger?.warn?.(`[memory-learn] 压缩异常: ${String(error)}`);
|
|
826
|
+
}
|
|
827
|
+
await host.commitAutoMemory(scope, {
|
|
828
|
+
add: stored,
|
|
829
|
+
remove: consolidated ? remove : [],
|
|
830
|
+
label: learn_1.AUTO_MEMORY_LABEL,
|
|
831
|
+
category: cat,
|
|
832
|
+
});
|
|
833
|
+
return { text: stored, consolidated, removed: consolidated ? remove.length : 0, category: cat };
|
|
786
834
|
}
|
|
787
|
-
|
|
788
|
-
|
|
835
|
+
// 超过总上限:先压缩“条数最多”的分类里最老的一组(不带本次新记忆),再追加本次
|
|
836
|
+
if (reachedCap) {
|
|
837
|
+
const byCategory = new Map();
|
|
838
|
+
for (const block of autoBlocks) {
|
|
839
|
+
const key = (0, learn_1.memoryBlockCategory)(block);
|
|
840
|
+
const list = byCategory.get(key) || [];
|
|
841
|
+
list.push(block);
|
|
842
|
+
byCategory.set(key, list);
|
|
843
|
+
}
|
|
844
|
+
let targetCategory = "";
|
|
845
|
+
let targetBlocks = [];
|
|
846
|
+
for (const [key, list] of byCategory) {
|
|
847
|
+
if (list.length >= 2 && list.length > targetBlocks.length) {
|
|
848
|
+
targetCategory = key;
|
|
849
|
+
targetBlocks = list;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
if (targetBlocks.length) {
|
|
853
|
+
const take = Math.max(1, Math.min(every - 1, targetBlocks.length));
|
|
854
|
+
const remove = targetBlocks.slice(0, take);
|
|
855
|
+
if (targetCategory === cat) {
|
|
856
|
+
// 同一分类:把本次新记忆一起并进去
|
|
857
|
+
let merged = "";
|
|
858
|
+
try {
|
|
859
|
+
merged = await this.consolidateMemories(kind, remove, text, maxChars, cat);
|
|
860
|
+
}
|
|
861
|
+
catch (error) {
|
|
862
|
+
this.host.logger?.warn?.(`[memory-learn] 上限压缩异常: ${String(error)}`);
|
|
863
|
+
}
|
|
864
|
+
if (merged) {
|
|
865
|
+
await host.commitAutoMemory(scope, {
|
|
866
|
+
add: merged,
|
|
867
|
+
remove,
|
|
868
|
+
label: learn_1.AUTO_MEMORY_LABEL,
|
|
869
|
+
category: cat,
|
|
870
|
+
});
|
|
871
|
+
return { text: merged, consolidated: true, removed: remove.length, category: cat };
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
else {
|
|
875
|
+
// 不同分类:只压缩旧的一组,本次仍然单独追加
|
|
876
|
+
try {
|
|
877
|
+
const merged = await this.consolidateMemories(kind, remove, "", maxChars, targetCategory);
|
|
878
|
+
if (merged) {
|
|
879
|
+
await host.commitAutoMemory(scope, {
|
|
880
|
+
add: merged,
|
|
881
|
+
remove,
|
|
882
|
+
label: learn_1.AUTO_MEMORY_LABEL,
|
|
883
|
+
category: targetCategory,
|
|
884
|
+
});
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
catch (error) {
|
|
888
|
+
this.host.logger?.warn?.(`[memory-learn] 上限压缩异常: ${String(error)}`);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
}
|
|
789
892
|
}
|
|
790
|
-
await host.commitAutoMemory(scope, {
|
|
791
|
-
|
|
792
|
-
remove: consolidated ? remove : [],
|
|
793
|
-
label: learn_1.AUTO_MEMORY_LABEL,
|
|
794
|
-
});
|
|
795
|
-
return { text: stored, consolidated, removed: consolidated ? remove.length : 0 };
|
|
893
|
+
await host.commitAutoMemory(scope, { add: text, label: learn_1.AUTO_MEMORY_LABEL, category: cat });
|
|
894
|
+
return { text, consolidated: false, removed: 0, category: cat };
|
|
796
895
|
}
|
|
797
|
-
/**
|
|
798
|
-
async consolidateMemories(kind, blocks, fresh, maxChars) {
|
|
896
|
+
/** 调模型把若干条同分类自动记忆压成一条更短的 */
|
|
897
|
+
async consolidateMemories(kind, blocks, fresh, maxChars, category = "其他") {
|
|
799
898
|
const cfg = this.config || {};
|
|
800
899
|
const marker = `## · ${learn_1.AUTO_MEMORY_LABEL}`;
|
|
801
|
-
const
|
|
900
|
+
const input = fresh ? [...blocks, `${marker}\n${fresh}`] : blocks;
|
|
901
|
+
const prompt = (0, learn_1.buildConsolidatePrompt)(input, { maxChars, kind, category });
|
|
802
902
|
const result = await this.provider.chat({
|
|
803
903
|
system: prompt.system,
|
|
804
904
|
user: prompt.user,
|
|
@@ -927,7 +1027,9 @@ class AiEngine {
|
|
|
927
1027
|
catch {
|
|
928
1028
|
return [];
|
|
929
1029
|
}
|
|
930
|
-
const blocks = (0, memory_1.splitMemoryBlocks)(content)
|
|
1030
|
+
const blocks = (0, memory_1.splitMemoryBlocks)(content)
|
|
1031
|
+
.map((item) => ({ ...item, text: (0, learn_1.memoryBlockBody)(item.text) }))
|
|
1032
|
+
.filter((item) => item.text);
|
|
931
1033
|
if (!blocks.length)
|
|
932
1034
|
return [];
|
|
933
1035
|
const recent = state.records.slice(-3).map((item) => item.text);
|
|
@@ -1175,22 +1277,82 @@ class AiEngine {
|
|
|
1175
1277
|
chat(request) {
|
|
1176
1278
|
return this.provider.chat(request);
|
|
1177
1279
|
}
|
|
1178
|
-
/**
|
|
1280
|
+
/** 群内长时间没人说话时,生成一条主动话题:带时间/季节、最近上下文、相关记忆和联网结果。 */
|
|
1179
1281
|
async idleTopic(groupId) {
|
|
1180
1282
|
const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
|
|
1283
|
+
const hookCtx = { session, groupId, mode: 'reply' };
|
|
1181
1284
|
let sections = [];
|
|
1182
1285
|
let personaOverride = null;
|
|
1183
1286
|
try {
|
|
1184
|
-
const hookCtx = { session, groupId, mode: 'reply' };
|
|
1185
1287
|
sections = this.clampStyle(await this.hooks.collectSections(hookCtx));
|
|
1186
1288
|
personaOverride = await this.hooks.collectPersonaOverride(hookCtx);
|
|
1187
1289
|
}
|
|
1188
1290
|
catch { /* ignore */ }
|
|
1291
|
+
// 最近上下文:优先 onebot:<群号>,兼容其它 platform
|
|
1292
|
+
let state = this.state.peek(`onebot:${groupId}`);
|
|
1293
|
+
if (!state) {
|
|
1294
|
+
for (const [key, value] of this.state.entries()) {
|
|
1295
|
+
if (key.endsWith(`:${groupId}`)) {
|
|
1296
|
+
state = value;
|
|
1297
|
+
break;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
const records = state ? state.records.slice(-12) : [];
|
|
1302
|
+
const contextText = records
|
|
1303
|
+
.map((record) => (0, prompt_1.renderRecordLine)(record, this.selfName))
|
|
1304
|
+
.join('\n');
|
|
1305
|
+
const lastAt = records.length ? Number(records[records.length - 1].at) || 0 : 0;
|
|
1306
|
+
const gapMinutes = lastAt ? Math.max(0, Math.round((this.now() - lastAt) / 60000)) : 0;
|
|
1307
|
+
const contextLabel = gapMinutes
|
|
1308
|
+
? `【最近聊天】(最后一条 ${gapMinutes} 分钟前)`
|
|
1309
|
+
: '【最近聊天】';
|
|
1310
|
+
// 相关记忆:用最近几句话做查询;没有上下文就取最近两条
|
|
1311
|
+
let memories = [];
|
|
1312
|
+
try {
|
|
1313
|
+
const scope = typeof this.host.memoryScopeOf === 'function'
|
|
1314
|
+
? this.host.memoryScopeOf(session)
|
|
1315
|
+
: { kind: 'group', id: groupId };
|
|
1316
|
+
const content = await this.host.readMemoryFile(scope);
|
|
1317
|
+
const blocks = (0, memory_1.splitMemoryBlocks)(content)
|
|
1318
|
+
.map((item) => ({ ...item, text: (0, learn_1.memoryBlockBody)(item.text) }))
|
|
1319
|
+
.filter((item) => item.text);
|
|
1320
|
+
const queryTexts = records.slice(-4).map((record) => record.text).filter(Boolean);
|
|
1321
|
+
const selected = queryTexts.length
|
|
1322
|
+
? (0, memory_1.selectMemoryBlocks)(blocks, queryTexts, { limit: 3, minScore: 0.12, maxChars: 140 })
|
|
1323
|
+
: blocks.slice(-2);
|
|
1324
|
+
memories = selected.map((item) => item.text);
|
|
1325
|
+
}
|
|
1326
|
+
catch { /* ignore */ }
|
|
1327
|
+
// 联网:用最近一句做 query;没有上下文就问今天的热点
|
|
1328
|
+
let searchSection = '';
|
|
1329
|
+
if (this.config.aiIdleTopicWebSearch !== false) {
|
|
1330
|
+
const lastText = records.length ? String(records[records.length - 1].text || '') : '';
|
|
1331
|
+
const cleanLast = lastText
|
|
1332
|
+
.replace(/\[[^\]]{1,16}\]/g, ' ')
|
|
1333
|
+
.replace(/[图片表情视频语音文件]/g, ' ')
|
|
1334
|
+
.replace(/\s+/g, ' ')
|
|
1335
|
+
.trim();
|
|
1336
|
+
const seed = cleanLast.length >= 4 ? cleanLast : '今天有什么热点话题';
|
|
1337
|
+
try {
|
|
1338
|
+
searchSection = await this.webSearch({ text: seed }, session, true);
|
|
1339
|
+
}
|
|
1340
|
+
catch { /* ignore */ }
|
|
1341
|
+
}
|
|
1342
|
+
const nowText = formatNowText(new Date(this.now()));
|
|
1189
1343
|
const system = [
|
|
1190
1344
|
`你是 QQ 群 ${groupId} 里的一个普通成员。`,
|
|
1191
1345
|
personaOverride || this.personaPrompt,
|
|
1346
|
+
`现在是 ${nowText}。`,
|
|
1192
1347
|
'群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
|
|
1193
|
-
'
|
|
1348
|
+
contextText ? `${contextLabel}\n${contextText}` : '',
|
|
1349
|
+
memories.length ? `【相关记忆】\n${memories.map((item) => `- ${item}`).join('\n')}` : '',
|
|
1350
|
+
searchSection,
|
|
1351
|
+
'要求:',
|
|
1352
|
+
'- 优先接着最近聊天里的话题或梗往下说;没有可接的,再结合当前时间、季节和记忆找话题;',
|
|
1353
|
+
'- 不要提与现在时间、季节不符的内容(按上面给出的日期判断,不要凭印象说夏天/冬天);',
|
|
1354
|
+
'- 联网结果只在确实相关时参考,不相关就忽略,不要编造新闻;',
|
|
1355
|
+
'- 不要问“在吗”,不要提“很久没人说话”,不要自我介绍;',
|
|
1194
1356
|
...sections,
|
|
1195
1357
|
].filter(Boolean).join('\n');
|
|
1196
1358
|
const result = await this.provider.chat({
|
package/lib/ai/learn.d.ts
CHANGED
|
@@ -8,6 +8,13 @@
|
|
|
8
8
|
* 归纳出来的内容是一次性的一长串,150 字以内,写入对应作用域的记忆文件。
|
|
9
9
|
*/
|
|
10
10
|
export declare const MAX_SUMMARY_CHARS = 150;
|
|
11
|
+
/** 记忆分类:一条记忆只属于一类,便于存储与检索 */
|
|
12
|
+
export declare const MEMORY_CATEGORIES: readonly ["人物关系", "偏好立场", "群内黑话", "长期话题", "约定事件", "其他"];
|
|
13
|
+
export declare function normalizeMemoryCategory(raw: string): string;
|
|
14
|
+
export interface SummaryEntry {
|
|
15
|
+
category: string;
|
|
16
|
+
text: string;
|
|
17
|
+
}
|
|
11
18
|
export interface EvictedLike {
|
|
12
19
|
id?: string;
|
|
13
20
|
userId?: string;
|
|
@@ -50,7 +57,7 @@ export declare class LearnStore {
|
|
|
50
57
|
}
|
|
51
58
|
/** 把一批消息渲染成模型可读的文本 */
|
|
52
59
|
export declare function renderForSummary(records: EvictedLike[], selfName?: string): string;
|
|
53
|
-
/**
|
|
60
|
+
/** 归纳提示词:按类别输出多条,一条只写一类 */
|
|
54
61
|
export declare function buildSummaryPrompt(records: EvictedLike[], options?: {
|
|
55
62
|
kind?: string;
|
|
56
63
|
selfName?: string;
|
|
@@ -58,6 +65,8 @@ export declare function buildSummaryPrompt(records: EvictedLike[], options?: {
|
|
|
58
65
|
system: string;
|
|
59
66
|
user: string;
|
|
60
67
|
};
|
|
68
|
+
/** 解析模型输出的多分类记忆 */
|
|
69
|
+
export declare function parseSummaryEntries(raw: string, maxChars?: number): SummaryEntry[];
|
|
61
70
|
/** 清洗模型输出 */
|
|
62
71
|
export declare function cleanSummary(raw: string, maxChars?: number): string;
|
|
63
72
|
/** Jaccard 相似度,用于挡住重复记忆 */
|
|
@@ -70,8 +79,10 @@ export declare const AUTO_MEMORY_LABEL = "\u81EA\u52A8\u5F52\u7EB3";
|
|
|
70
79
|
export declare function isAutoMemoryBlock(block: string): boolean;
|
|
71
80
|
/** 取记忆块正文(去掉 `## 时间 · 来源` 标题行) */
|
|
72
81
|
export declare function memoryBlockBody(block: string): string;
|
|
82
|
+
/** 取记忆块的分类;旧格式没有分类时归入「其他」 */
|
|
83
|
+
export declare function memoryBlockCategory(block: string): string;
|
|
73
84
|
/**
|
|
74
|
-
* 记忆压缩提示词:把 N
|
|
85
|
+
* 记忆压缩提示词:把 N 条同分类的自动归纳合并成一条更短的。
|
|
75
86
|
*
|
|
76
87
|
* 目的不是“再总结一遍”,而是去掉重复与过时信息——群里连续几天聊同一件事时,
|
|
77
88
|
* 自动归纳会反复产出高度相似的条目,压缩后只保留事实差异。
|
|
@@ -79,6 +90,7 @@ export declare function memoryBlockBody(block: string): string;
|
|
|
79
90
|
export declare function buildConsolidatePrompt(blocks: string[], options?: {
|
|
80
91
|
maxChars?: number;
|
|
81
92
|
kind?: string;
|
|
93
|
+
category?: string;
|
|
82
94
|
}): {
|
|
83
95
|
system: string;
|
|
84
96
|
user: string;
|
package/lib/ai/learn.js
CHANGED
|
@@ -9,17 +9,53 @@
|
|
|
9
9
|
* 归纳出来的内容是一次性的一长串,150 字以内,写入对应作用域的记忆文件。
|
|
10
10
|
*/
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.AUTO_MEMORY_LABEL = exports.LearnStore = exports.LearnBucket = exports.MAX_SUMMARY_CHARS = void 0;
|
|
12
|
+
exports.AUTO_MEMORY_LABEL = exports.LearnStore = exports.LearnBucket = exports.MEMORY_CATEGORIES = exports.MAX_SUMMARY_CHARS = void 0;
|
|
13
|
+
exports.normalizeMemoryCategory = normalizeMemoryCategory;
|
|
13
14
|
exports.renderForSummary = renderForSummary;
|
|
14
15
|
exports.buildSummaryPrompt = buildSummaryPrompt;
|
|
16
|
+
exports.parseSummaryEntries = parseSummaryEntries;
|
|
15
17
|
exports.cleanSummary = cleanSummary;
|
|
16
18
|
exports.similarityOf = similarityOf;
|
|
17
19
|
exports.isDuplicate = isDuplicate;
|
|
18
20
|
exports.isAutoMemoryBlock = isAutoMemoryBlock;
|
|
19
21
|
exports.memoryBlockBody = memoryBlockBody;
|
|
22
|
+
exports.memoryBlockCategory = memoryBlockCategory;
|
|
20
23
|
exports.buildConsolidatePrompt = buildConsolidatePrompt;
|
|
21
24
|
const text_1 = require("../core/text");
|
|
22
25
|
exports.MAX_SUMMARY_CHARS = 150;
|
|
26
|
+
/** 记忆分类:一条记忆只属于一类,便于存储与检索 */
|
|
27
|
+
exports.MEMORY_CATEGORIES = ['人物关系', '偏好立场', '群内黑话', '长期话题', '约定事件', '其他'];
|
|
28
|
+
const CATEGORY_ALIASES = {
|
|
29
|
+
人物: '人物关系',
|
|
30
|
+
关系: '人物关系',
|
|
31
|
+
称呼: '人物关系',
|
|
32
|
+
身份: '人物关系',
|
|
33
|
+
偏好: '偏好立场',
|
|
34
|
+
立场: '偏好立场',
|
|
35
|
+
喜好: '偏好立场',
|
|
36
|
+
观点: '偏好立场',
|
|
37
|
+
黑话: '群内黑话',
|
|
38
|
+
梗: '群内黑话',
|
|
39
|
+
术语: '群内黑话',
|
|
40
|
+
缩写: '群内黑话',
|
|
41
|
+
话题: '长期话题',
|
|
42
|
+
约定: '约定事件',
|
|
43
|
+
事件: '约定事件',
|
|
44
|
+
计划: '约定事件',
|
|
45
|
+
其他: '其他',
|
|
46
|
+
};
|
|
47
|
+
function normalizeMemoryCategory(raw) {
|
|
48
|
+
const value = String(raw || '').trim().replace(/[\s*_`「」【】\[\]]/g, '');
|
|
49
|
+
if (!value)
|
|
50
|
+
return '其他';
|
|
51
|
+
if (exports.MEMORY_CATEGORIES.includes(value))
|
|
52
|
+
return value;
|
|
53
|
+
for (const key of Object.keys(CATEGORY_ALIASES)) {
|
|
54
|
+
if (value.includes(key))
|
|
55
|
+
return CATEGORY_ALIASES[key];
|
|
56
|
+
}
|
|
57
|
+
return '其他';
|
|
58
|
+
}
|
|
23
59
|
/** 正在累计的一批消息 */
|
|
24
60
|
class LearnBucket {
|
|
25
61
|
records = [];
|
|
@@ -111,7 +147,7 @@ function renderForSummary(records, selfName = 'bot') {
|
|
|
111
147
|
}
|
|
112
148
|
return lines.join('\n');
|
|
113
149
|
}
|
|
114
|
-
/**
|
|
150
|
+
/** 归纳提示词:按类别输出多条,一条只写一类 */
|
|
115
151
|
function buildSummaryPrompt(records, options = {}) {
|
|
116
152
|
const label = options.kind === 'private' ? '私聊' : '群聊';
|
|
117
153
|
const body = renderForSummary(records, options.selfName || 'bot');
|
|
@@ -123,18 +159,61 @@ function buildSummaryPrompt(records, options = {}) {
|
|
|
123
159
|
'2. 稳定的偏好、立场、习惯(不是一时的情绪)',
|
|
124
160
|
'3. 群内或两人之间约定俗成的说法、黑话',
|
|
125
161
|
'4. 反复出现、以后还会聊到的话题',
|
|
162
|
+
'5. 明确的约定、时间、计划',
|
|
126
163
|
'',
|
|
127
164
|
'必须丢掉:寒暄、打招呼、一次性的抱怨或玩笑、已经结束的接梗、纯表情。',
|
|
128
165
|
'',
|
|
129
166
|
'输出要求:',
|
|
130
|
-
'-
|
|
131
|
-
`-
|
|
167
|
+
'- 按类别拆开,每条一行,格式必须是「类别:内容」;',
|
|
168
|
+
`- 类别只能是:${exports.MEMORY_CATEGORIES.join('、')};`,
|
|
169
|
+
'- 一条记忆只写一个类别,不要在一句里混入另一个类别的内容;',
|
|
170
|
+
'- 最多输出 3 条;同类最多 2 条;',
|
|
171
|
+
'- 不要标题、列表符号、编号、Markdown、引号;',
|
|
172
|
+
`- 每条不超过 ${exports.MAX_SUMMARY_CHARS} 字;`,
|
|
132
173
|
'- 用陈述句写事实,不要写「他们聊到」「讨论了」这类过程描述;',
|
|
133
174
|
'- 如果没有任何值得长期记住的内容,只输出一个词:NONE',
|
|
134
175
|
].join('\n');
|
|
135
|
-
const user = ['【记录】', body || '(空)', '', '
|
|
176
|
+
const user = ['【记录】', body || '(空)', '', '现在输出分类后的记忆(类别:内容),或输出 NONE。'].join('\n');
|
|
136
177
|
return { system, user };
|
|
137
178
|
}
|
|
179
|
+
/** 解析模型输出的多分类记忆 */
|
|
180
|
+
function parseSummaryEntries(raw, maxChars = exports.MAX_SUMMARY_CHARS) {
|
|
181
|
+
let text = String(raw || '').trim();
|
|
182
|
+
if (!text)
|
|
183
|
+
return [];
|
|
184
|
+
text = text
|
|
185
|
+
.replace(/^```[a-zA-Z0-9_-]*\s*\n?/, '')
|
|
186
|
+
.replace(/\n?\s*```\s*$/, '')
|
|
187
|
+
.trim();
|
|
188
|
+
if (/^(?:none|无|没有|n\/a)$/i.test(text))
|
|
189
|
+
return [];
|
|
190
|
+
const lines = text
|
|
191
|
+
.split(/\r?\n/)
|
|
192
|
+
.map((line) => line.replace(/^\s*(?:[-*+·]|\d+[.)、])\s*/, '').trim())
|
|
193
|
+
.filter(Boolean);
|
|
194
|
+
const out = [];
|
|
195
|
+
const seen = new Set();
|
|
196
|
+
for (const line of lines) {
|
|
197
|
+
let category = '其他';
|
|
198
|
+
let body = line;
|
|
199
|
+
const match = /^([^::]{1,12})[::]\s*(.+)$/.exec(line);
|
|
200
|
+
if (match) {
|
|
201
|
+
category = normalizeMemoryCategory(match[1]);
|
|
202
|
+
body = match[2];
|
|
203
|
+
}
|
|
204
|
+
const cleaned = cleanSummary(body.replace(/\*\*/g, ''), maxChars);
|
|
205
|
+
if (!cleaned)
|
|
206
|
+
continue;
|
|
207
|
+
const key = `${category}|${cleaned}`;
|
|
208
|
+
if (seen.has(key))
|
|
209
|
+
continue;
|
|
210
|
+
seen.add(key);
|
|
211
|
+
out.push({ category, text: cleaned });
|
|
212
|
+
if (out.length >= 3)
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
return out;
|
|
216
|
+
}
|
|
138
217
|
/** 清洗模型输出 */
|
|
139
218
|
function cleanSummary(raw, maxChars = exports.MAX_SUMMARY_CHARS) {
|
|
140
219
|
let text = String(raw || '').trim();
|
|
@@ -231,8 +310,14 @@ function memoryBlockBody(block) {
|
|
|
231
310
|
return String(block || '').trim();
|
|
232
311
|
return lines.slice(1).join('\n').trim();
|
|
233
312
|
}
|
|
313
|
+
/** 取记忆块的分类;旧格式没有分类时归入「其他」 */
|
|
314
|
+
function memoryBlockCategory(block) {
|
|
315
|
+
const first = String(block || '').split('\n', 1)[0] || '';
|
|
316
|
+
const match = /·\s*自动归纳\s*·\s*([^·\n]+)/.exec(first);
|
|
317
|
+
return normalizeMemoryCategory(match ? match[1] : '其他');
|
|
318
|
+
}
|
|
234
319
|
/**
|
|
235
|
-
* 记忆压缩提示词:把 N
|
|
320
|
+
* 记忆压缩提示词:把 N 条同分类的自动归纳合并成一条更短的。
|
|
236
321
|
*
|
|
237
322
|
* 目的不是“再总结一遍”,而是去掉重复与过时信息——群里连续几天聊同一件事时,
|
|
238
323
|
* 自动归纳会反复产出高度相似的条目,压缩后只保留事实差异。
|
|
@@ -240,14 +325,16 @@ function memoryBlockBody(block) {
|
|
|
240
325
|
function buildConsolidatePrompt(blocks, options = {}) {
|
|
241
326
|
const maxChars = Math.max(40, Number(options.maxChars) || 90);
|
|
242
327
|
const label = options.kind === 'private' ? '私聊' : '群聊';
|
|
328
|
+
const category = normalizeMemoryCategory(options.category || '其他');
|
|
243
329
|
const bodies = (blocks || [])
|
|
244
330
|
.map((block) => memoryBlockBody(block).replace(/\s+/g, ' ').trim())
|
|
245
331
|
.filter(Boolean);
|
|
246
332
|
const system = [
|
|
247
|
-
`你在压缩一段${label}
|
|
333
|
+
`你在压缩一段${label}里「${category}」类的长期记忆。`,
|
|
248
334
|
`下面有 ${bodies.length} 条已经归纳过的记忆,请合并成一条。`,
|
|
249
335
|
'',
|
|
250
336
|
'要求:',
|
|
337
|
+
`- 只合并「${category}」这一类的信息,不要混入其他类别;`,
|
|
251
338
|
'- 只保留互不重复的事实:人物与称呼、关系、稳定偏好、反复出现的话题;',
|
|
252
339
|
'- 删掉重复表述、一次性情绪、已经过时的细节;',
|
|
253
340
|
'- 不要编造,不要写“他们聊到”“讨论了”这类过程描述;',
|