@nestim/koishi-plugin-qq-group-manager 1.4.6 → 1.4.8
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 +72 -0
- package/lib/ai/engine.d.ts +40 -1
- package/lib/ai/engine.js +211 -20
- package/lib/ai/learn.d.ts +19 -0
- package/lib/ai/learn.js +50 -1
- package/lib/ai/provider.d.ts +4 -0
- package/lib/ai/provider.js +7 -5
- package/lib/ai/state.d.ts +4 -0
- package/lib/ai/state.js +4 -0
- package/lib/ai/trigger.d.ts +21 -9
- package/lib/ai/trigger.js +54 -18
- package/lib/index.d.ts +42 -0
- package/lib/index.js +19 -1
- package/lib/service.d.ts +7 -0
- package/lib/service.js +42 -0
- package/package.json +1 -1
- package/src/ai/engine.ts +243 -25
- package/src/ai/learn.ts +56 -0
- package/src/ai/provider.ts +11 -5
- package/src/ai/state.ts +4 -0
- package/src/ai/trigger.ts +72 -22
- package/src/index.ts +20 -2
- package/src/service.js +42 -0
package/src/ai/engine.ts
CHANGED
|
@@ -13,7 +13,16 @@
|
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
15
|
import { AiState, GroupState, ChatRecord, FollowupState } from './state';
|
|
16
|
-
import {
|
|
16
|
+
import {
|
|
17
|
+
LearnBucket,
|
|
18
|
+
LearnStore,
|
|
19
|
+
buildSummaryPrompt,
|
|
20
|
+
buildConsolidatePrompt,
|
|
21
|
+
cleanSummary,
|
|
22
|
+
isDuplicate,
|
|
23
|
+
isAutoMemoryBlock,
|
|
24
|
+
AUTO_MEMORY_LABEL,
|
|
25
|
+
} from './learn';
|
|
17
26
|
import { decideTrigger } from './trigger';
|
|
18
27
|
import { buildJudgePrompt, buildReplyPrompt, buildUserPrompt, PASS_TOKEN } from './prompt';
|
|
19
28
|
import { ChatProvider, ChatResult } from './provider';
|
|
@@ -38,6 +47,14 @@ export interface AiHost {
|
|
|
38
47
|
fetchQuotedImages?(session: any, quote: any): Promise<RenderedImage[]>;
|
|
39
48
|
resolveImage(ref: string, session: any): Promise<string>;
|
|
40
49
|
sendReply(session: any, text: string): Promise<void>;
|
|
50
|
+
/** 发送系统提示(不引用、不进入 AI 上下文),用于冷却提示等 */
|
|
51
|
+
sendNotice?(session: any, text: string): Promise<void>;
|
|
52
|
+
/** 写入自动归纳记忆:add = 新条目;remove = 需要被压缩替换掉的旧条目 */
|
|
53
|
+
commitAutoMemory?(scope: { kind: 'group' | 'private'; id: string } | null, payload: {
|
|
54
|
+
add: string;
|
|
55
|
+
remove?: string[];
|
|
56
|
+
label?: string;
|
|
57
|
+
}): Promise<void>;
|
|
41
58
|
readMemoryFile(scope?: { kind: 'group' | 'private'; id: string } | null): Promise<string>;
|
|
42
59
|
}
|
|
43
60
|
|
|
@@ -72,8 +89,22 @@ function cleanReply(text: string, selfName: string): string {
|
|
|
72
89
|
return out.replace(/\s+/g, ' ').trim();
|
|
73
90
|
}
|
|
74
91
|
|
|
75
|
-
|
|
76
|
-
|
|
92
|
+
/** 把服务端 usage 压成一行日志,便于观察真实 token 消耗与缓存命中 */
|
|
93
|
+
function usageText(usage: any): string {
|
|
94
|
+
if (!usage) return '';
|
|
95
|
+
const input = usage.prompt_tokens ?? usage.input_tokens;
|
|
96
|
+
const output = usage.completion_tokens ?? usage.output_tokens;
|
|
97
|
+
const cacheHit = usage.prompt_cache_hit_tokens
|
|
98
|
+
?? usage.cached_tokens
|
|
99
|
+
?? usage.cache_read_input_tokens;
|
|
100
|
+
const parts: string[] = [];
|
|
101
|
+
if (input != null) parts.push(`in=${input}`);
|
|
102
|
+
if (output != null) parts.push(`out=${output}`);
|
|
103
|
+
if (cacheHit != null) parts.push(`cache=${cacheHit}`);
|
|
104
|
+
return parts.join(',');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function clipReply(text: string, maxChars: number): string { const max = Math.max(20, maxChars || 120);
|
|
77
108
|
if (text.length <= max) return text;
|
|
78
109
|
const slice = text.slice(0, max);
|
|
79
110
|
const boundary = Math.max(
|
|
@@ -143,6 +174,17 @@ export class AiEngine {
|
|
|
143
174
|
return rules.find((item) => String(item?.guildId ?? '').trim() === guildId);
|
|
144
175
|
}
|
|
145
176
|
|
|
177
|
+
/**
|
|
178
|
+
* 读配置:该群 groupRules 里有同名非空值就用它,否则回落到全局。
|
|
179
|
+
* 这样频率限制(阈值/概率/模型调用冷却)可以按群单独设置。
|
|
180
|
+
*/
|
|
181
|
+
private setting(session: any, key: string): any {
|
|
182
|
+
const rule = this.ruleFor(session);
|
|
183
|
+
const value = rule ? rule[key] : undefined;
|
|
184
|
+
if (value === undefined || value === null || value === '') return this.config[key];
|
|
185
|
+
return value;
|
|
186
|
+
}
|
|
187
|
+
|
|
146
188
|
resolveEnabled(session: any): boolean {
|
|
147
189
|
const rule = this.ruleFor(session);
|
|
148
190
|
const requireRule = this.config.aiReplyRequireGroupRule !== false;
|
|
@@ -182,6 +224,38 @@ export class AiEngine {
|
|
|
182
224
|
return !!this.config.aiDebugPrompt;
|
|
183
225
|
}
|
|
184
226
|
|
|
227
|
+
/**
|
|
228
|
+
* 历史上下文按字数裁剪(aiContextMaxChars,0=不限)。
|
|
229
|
+
* 从最新往前累加,至少保留最近 4 条,避免一刀切掉当前对话。
|
|
230
|
+
*/
|
|
231
|
+
private clampContext(records: ChatRecord[]): ChatRecord[] {
|
|
232
|
+
const limit = Math.max(0, Number(this.config.aiContextMaxChars ?? 0));
|
|
233
|
+
if (!limit || !records.length) return records;
|
|
234
|
+
const out: ChatRecord[] = [];
|
|
235
|
+
let total = 0;
|
|
236
|
+
for (let i = records.length - 1; i >= 0; i -= 1) {
|
|
237
|
+
const item = records[i];
|
|
238
|
+
const size = String(item.text || '').length
|
|
239
|
+
+ String(item.forwardText || '').length
|
|
240
|
+
+ 32; // 昵称 / 时间 / 角色等渲染开销
|
|
241
|
+
if (out.length >= 4 && total + size > limit) break;
|
|
242
|
+
total += size;
|
|
243
|
+
out.unshift(item);
|
|
244
|
+
}
|
|
245
|
+
return out;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** 限制外部插件注入的风格段长度(aiStyleMaxChars,0=不限) */
|
|
249
|
+
private clampStyle(sections: string[]): string[] {
|
|
250
|
+
const limit = Math.max(0, Number(this.config.aiStyleMaxChars ?? 0));
|
|
251
|
+
if (!limit || !sections.length) return sections;
|
|
252
|
+
return sections.map((text) => {
|
|
253
|
+
const value = String(text || '');
|
|
254
|
+
if (value.length <= limit) return value;
|
|
255
|
+
return `${value.slice(0, limit)}\n(以上风格说明过长已截断,保持已经给出的语气即可)`;
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
|
|
185
259
|
// ---------------------------------------------------------------- 记录
|
|
186
260
|
|
|
187
261
|
/** 是否像指令(这类消息不进上下文,避免污染) */
|
|
@@ -399,12 +473,12 @@ export class AiEngine {
|
|
|
399
473
|
if (!records.length) return;
|
|
400
474
|
|
|
401
475
|
const scope = { kind, id: scopeId } as any;
|
|
402
|
-
const
|
|
403
|
-
if (!
|
|
476
|
+
const saved = await this.summarizeRecords(records, kind, scope, reason);
|
|
477
|
+
if (!saved || !saved.text) return;
|
|
404
478
|
|
|
405
479
|
if (cfg.memoryLearnPushBack === false) return;
|
|
406
480
|
|
|
407
|
-
const text = `刚记住了:${
|
|
481
|
+
const text = saved.consolidated ? `刚整理了记忆:${saved.text}` : `刚记住了:${saved.text}`;
|
|
408
482
|
try {
|
|
409
483
|
if (kind === "private") {
|
|
410
484
|
const bot = (kind === "private" && session?.bot) || null;
|
|
@@ -419,13 +493,13 @@ export class AiEngine {
|
|
|
419
493
|
}
|
|
420
494
|
}
|
|
421
495
|
|
|
422
|
-
/**
|
|
496
|
+
/** 把一批消息归纳成一条记忆并写入对应作用域;返回写入结果或 null */
|
|
423
497
|
private async summarizeRecords(
|
|
424
498
|
records: any[],
|
|
425
499
|
kind: "group" | "private",
|
|
426
500
|
scope: any,
|
|
427
501
|
reason: string,
|
|
428
|
-
): Promise<string> {
|
|
502
|
+
): Promise<{ text: string; consolidated: boolean; removed: number } | null> {
|
|
429
503
|
const cfg: any = this.config || {};
|
|
430
504
|
|
|
431
505
|
// 每日上限
|
|
@@ -436,7 +510,7 @@ export class AiEngine {
|
|
|
436
510
|
const used = this.learnDaily.get(dailyKey) || 0;
|
|
437
511
|
if (used >= limit) {
|
|
438
512
|
this.host.logger?.info?.(`[memory-learn] 已达每日上限 ${limit}(${kind}:${scope.id})`);
|
|
439
|
-
return
|
|
513
|
+
return null;
|
|
440
514
|
}
|
|
441
515
|
|
|
442
516
|
const prompt = buildSummaryPrompt(records, { kind, selfName: this.selfName });
|
|
@@ -447,20 +521,24 @@ export class AiEngine {
|
|
|
447
521
|
user: prompt.user,
|
|
448
522
|
temperature: 0.3,
|
|
449
523
|
maxTokens: 400,
|
|
524
|
+
model: String(cfg.memoryLearnModel || "").trim() || undefined,
|
|
450
525
|
});
|
|
451
526
|
if (!result || !result.ok) {
|
|
452
527
|
this.host.logger?.warn?.(`[memory-learn] 归纳调用失败: ${result && result.error}`);
|
|
453
|
-
return
|
|
528
|
+
return null;
|
|
454
529
|
}
|
|
455
530
|
raw = String(result.text || "");
|
|
531
|
+
if (usageText(result.usage)) {
|
|
532
|
+
this.host.logger?.info?.(`[memory-learn] 归纳 token ${usageText(result.usage)}(${kind}:${scope.id})`);
|
|
533
|
+
}
|
|
456
534
|
} catch (error: any) {
|
|
457
535
|
this.host.logger?.warn?.(`[memory-learn] 归纳异常: ${String(error)}`);
|
|
458
|
-
return
|
|
536
|
+
return null;
|
|
459
537
|
}
|
|
460
538
|
|
|
461
539
|
const maxChars = Math.max(40, Number(cfg.memoryLearnMaxChars) || 150);
|
|
462
540
|
let text = cleanSummary(raw, maxChars);
|
|
463
|
-
if (!text) return
|
|
541
|
+
if (!text) return null;
|
|
464
542
|
|
|
465
543
|
// 去重
|
|
466
544
|
let existing: string[] = [];
|
|
@@ -477,19 +555,114 @@ export class AiEngine {
|
|
|
477
555
|
const threshold = Number(cfg.memoryLearnDuplicateThreshold) || 0.55;
|
|
478
556
|
if (isDuplicate(text, existing, threshold)) {
|
|
479
557
|
this.host.logger?.info?.(`[memory-learn] 跳过重复记忆(${kind}:${scope.id})`);
|
|
480
|
-
return
|
|
558
|
+
return null;
|
|
481
559
|
}
|
|
482
560
|
|
|
561
|
+
let saved: { text: string; consolidated: boolean; removed: number };
|
|
483
562
|
try {
|
|
484
|
-
await
|
|
563
|
+
saved = await this.saveLearnedMemory(kind, scope, text);
|
|
485
564
|
this.learnDaily.set(dailyKey, used + 1);
|
|
486
565
|
} catch (error: any) {
|
|
487
566
|
this.host.logger?.warn?.(`[memory-learn] 写入失败: ${String(error)}`);
|
|
488
|
-
return
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
this.host.logger?.info?.(
|
|
571
|
+
`[memory-learn] 已记入 ${kind}:${scope.id}(${reason}) ${saved.text.length}字`
|
|
572
|
+
+ (saved.consolidated ? `,压缩 ${saved.removed} 条旧记忆 → 1` : ""),
|
|
573
|
+
);
|
|
574
|
+
return saved;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* 自动归纳写入策略(1.4.7+):
|
|
579
|
+
* - 每累计 N 条(默认 5)就把最早的 N-1 条 + 本次新记忆压缩成 1 条;
|
|
580
|
+
* - 自动记忆总数超过上限(默认 15)时同样触发压缩;
|
|
581
|
+
* - 压缩失败时退回普通追加,不丢数据,下次归纳会再试。
|
|
582
|
+
*/
|
|
583
|
+
private async saveLearnedMemory(
|
|
584
|
+
kind: "group" | "private",
|
|
585
|
+
scope: any,
|
|
586
|
+
text: string,
|
|
587
|
+
): Promise<{ text: string; consolidated: boolean; removed: number }> {
|
|
588
|
+
const cfg: any = this.config || {};
|
|
589
|
+
const host: any = this.host;
|
|
590
|
+
const canConsolidate = cfg.memoryLearnConsolidate !== false
|
|
591
|
+
&& typeof host.commitAutoMemory === "function";
|
|
592
|
+
|
|
593
|
+
if (!canConsolidate) {
|
|
594
|
+
await host.saveMemoryToFile("", text, scope, AUTO_MEMORY_LABEL);
|
|
595
|
+
return { text, consolidated: false, removed: 0 };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const every = Math.max(2, Number(cfg.memoryLearnConsolidateEvery) || 5);
|
|
599
|
+
const maxEntries = Math.max(1, Number(cfg.memoryLearnMaxEntries) || 15);
|
|
600
|
+
const maxChars = Math.max(40, Number(cfg.memoryLearnConsolidateMaxChars) || 90);
|
|
601
|
+
|
|
602
|
+
let autoBlocks: string[] = [];
|
|
603
|
+
try {
|
|
604
|
+
const content = await host.readMemoryFile(scope);
|
|
605
|
+
autoBlocks = splitMemoryBlocks(content)
|
|
606
|
+
.map((item) => item.text)
|
|
607
|
+
.filter((item) => isAutoMemoryBlock(item));
|
|
608
|
+
} catch {
|
|
609
|
+
autoBlocks = [];
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
const projected = autoBlocks.length + 1;
|
|
613
|
+
const reachedBatch = projected >= every;
|
|
614
|
+
const reachedCap = projected > maxEntries && autoBlocks.length > 0;
|
|
615
|
+
if (!reachedBatch && !reachedCap) {
|
|
616
|
+
await host.commitAutoMemory(scope, { add: text, label: AUTO_MEMORY_LABEL });
|
|
617
|
+
return { text, consolidated: false, removed: 0 };
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
// 常规:拿最早的 every-1 条 + 本次,正好 every 条压成 1 条
|
|
621
|
+
const take = Math.max(1, Math.min(every - 1, autoBlocks.length));
|
|
622
|
+
const remove = autoBlocks.slice(0, take);
|
|
623
|
+
|
|
624
|
+
let stored = text;
|
|
625
|
+
let consolidated = false;
|
|
626
|
+
try {
|
|
627
|
+
const merged = await this.consolidateMemories(kind, remove, text, maxChars);
|
|
628
|
+
if (merged) {
|
|
629
|
+
stored = merged;
|
|
630
|
+
consolidated = true;
|
|
631
|
+
}
|
|
632
|
+
} catch (error: any) {
|
|
633
|
+
this.host.logger?.warn?.(`[memory-learn] 压缩异常: ${String(error)}`);
|
|
489
634
|
}
|
|
490
635
|
|
|
491
|
-
|
|
492
|
-
|
|
636
|
+
await host.commitAutoMemory(scope, {
|
|
637
|
+
add: stored,
|
|
638
|
+
remove: consolidated ? remove : [],
|
|
639
|
+
label: AUTO_MEMORY_LABEL,
|
|
640
|
+
});
|
|
641
|
+
return { text: stored, consolidated, removed: consolidated ? remove.length : 0 };
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** 调模型把若干条自动记忆压成一条更短的 */
|
|
645
|
+
private async consolidateMemories(
|
|
646
|
+
kind: "group" | "private",
|
|
647
|
+
blocks: string[],
|
|
648
|
+
fresh: string,
|
|
649
|
+
maxChars: number,
|
|
650
|
+
): Promise<string> {
|
|
651
|
+
const cfg: any = this.config || {};
|
|
652
|
+
const marker = `## · ${AUTO_MEMORY_LABEL}`;
|
|
653
|
+
const prompt = buildConsolidatePrompt([...blocks, `${marker}\n${fresh}`], { maxChars, kind });
|
|
654
|
+
const result = await this.provider.chat({
|
|
655
|
+
system: prompt.system,
|
|
656
|
+
user: prompt.user,
|
|
657
|
+
temperature: 0.2,
|
|
658
|
+
maxTokens: Math.max(200, Math.min(500, maxChars * 5)),
|
|
659
|
+
model: String(cfg.memoryLearnModel || "").trim() || undefined,
|
|
660
|
+
});
|
|
661
|
+
if (!result || !result.ok) {
|
|
662
|
+
this.host.logger?.warn?.(`[memory-learn] 压缩调用失败: ${result?.error || "unknown"}`);
|
|
663
|
+
return "";
|
|
664
|
+
}
|
|
665
|
+
return cleanSummary(String(result.text || ""), maxChars);
|
|
493
666
|
}
|
|
494
667
|
|
|
495
668
|
private findBot(): any {
|
|
@@ -608,6 +781,38 @@ export class AiEngine {
|
|
|
608
781
|
|
|
609
782
|
// ---------------------------------------------------------------- 主流程
|
|
610
783
|
|
|
784
|
+
/**
|
|
785
|
+
* 被 @ 但处于模型调用冷却时,在群里提示还剩多久。
|
|
786
|
+
*
|
|
787
|
+
* 只发本地短句,不调用模型;同一群按 aiCooldownNoticeIntervalSeconds 限流,
|
|
788
|
+
* 避免有人连续 @ 时刷屏。
|
|
789
|
+
*/
|
|
790
|
+
private async sendCooldownNotice(session: any, state: GroupState, remainingMs: number): Promise<void> {
|
|
791
|
+
if (this.setting(session, 'aiCooldownNotice') === false) return;
|
|
792
|
+
const gap = Math.max(0, Number(this.config.aiCooldownNoticeIntervalSeconds ?? 20)) * 1000;
|
|
793
|
+
const now = this.now();
|
|
794
|
+
if (gap > 0 && now - (state.lastCooldownNoticeAt || 0) < gap) return;
|
|
795
|
+
|
|
796
|
+
const seconds = Math.max(1, Math.ceil(Math.max(0, remainingMs) / 1000));
|
|
797
|
+
const template = String(this.config.aiCooldownNoticeText || '还在冷却,{seconds} 秒后再叫我。');
|
|
798
|
+
const text = template
|
|
799
|
+
.replace(/\{seconds\}/g, String(seconds))
|
|
800
|
+
.replace(/\{minutes\}/g, String(Math.ceil(seconds / 60)));
|
|
801
|
+
if (!text.trim()) return;
|
|
802
|
+
|
|
803
|
+
state.lastCooldownNoticeAt = now;
|
|
804
|
+
try {
|
|
805
|
+
if (typeof (this.host as any).sendNotice === 'function') {
|
|
806
|
+
await (this.host as any).sendNotice(session, text);
|
|
807
|
+
} else {
|
|
808
|
+
await this.host.sendReply(session, text);
|
|
809
|
+
}
|
|
810
|
+
this.log('ai-cooldown-notice', { seconds, remainingMs }, session);
|
|
811
|
+
} catch (error: any) {
|
|
812
|
+
this.host.logger?.warn?.(`[ai] 冷却提示发送失败: ${String(error)}`);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
611
816
|
async handle(session: any): Promise<void> {
|
|
612
817
|
const key = this.groupKey(session);
|
|
613
818
|
if (!key) return;
|
|
@@ -631,22 +836,27 @@ export class AiEngine {
|
|
|
631
836
|
// 用户换了话题/说的和上一轮无关时,丢掉待续话题,避免机器人追着自己上一句说
|
|
632
837
|
if (followupState && !followup) state.followup = null;
|
|
633
838
|
|
|
634
|
-
const threshold = Math.max(1, Number(this.
|
|
839
|
+
const threshold = Math.max(1, Number(this.setting(session, 'aiMessageThreshold') ?? 15));
|
|
635
840
|
const decision = decideTrigger({
|
|
636
|
-
mode: (this.
|
|
841
|
+
mode: (this.setting(session, 'aiReplyMode') || 'hybrid') as any,
|
|
637
842
|
counter: state.counter,
|
|
638
843
|
threshold,
|
|
639
|
-
probability: Number(this.
|
|
844
|
+
probability: Number(this.setting(session, 'aiRandomReplyProbability') ?? 0.08),
|
|
640
845
|
now: this.now(),
|
|
641
846
|
lastAttemptAt: state.lastAttemptAt,
|
|
642
|
-
minIntervalMs: Math.max(0, Number(this.
|
|
847
|
+
minIntervalMs: Math.max(0, Number(this.setting(session, 'aiMinReplyIntervalSeconds') ?? 45)) * 1000,
|
|
643
848
|
lastReplyAt: state.lastReplyAt || 0,
|
|
644
849
|
mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
|
|
645
850
|
inFlight: state.inFlight,
|
|
646
851
|
mention,
|
|
647
852
|
followup,
|
|
648
853
|
rng: this.rng,
|
|
854
|
+
pseudoRandom: this.setting(session, 'aiPseudoRandom') !== false,
|
|
855
|
+
randomBoost: state.randomBoost,
|
|
856
|
+
pseudoRandomStep: Math.max(0, Number(this.setting(session, 'aiPseudoRandomStep') ?? 0.01)),
|
|
649
857
|
});
|
|
858
|
+
// 伪随机加成只由「随机掷骰」更新:冷却/阈值跳过时保持不变
|
|
859
|
+
if (typeof decision.nextBoost === 'number') state.randomBoost = decision.nextBoost;
|
|
650
860
|
|
|
651
861
|
this.log('ai-trigger', {
|
|
652
862
|
fire: decision.fire,
|
|
@@ -655,9 +865,16 @@ export class AiEngine {
|
|
|
655
865
|
threshold,
|
|
656
866
|
mention,
|
|
657
867
|
followup,
|
|
868
|
+
prob: decision.effectiveProbability,
|
|
869
|
+
boost: state.randomBoost,
|
|
658
870
|
ctx: state.records.length,
|
|
659
871
|
}, session);
|
|
660
|
-
if (!decision.fire)
|
|
872
|
+
if (!decision.fire) {
|
|
873
|
+
if (decision.reason === 'cooldown-mention') {
|
|
874
|
+
await this.sendCooldownNotice(session, state, decision.remainingMs || 0);
|
|
875
|
+
}
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
661
878
|
|
|
662
879
|
state.inFlight = true;
|
|
663
880
|
state.lastAttemptAt = this.now();
|
|
@@ -671,13 +888,13 @@ export class AiEngine {
|
|
|
671
888
|
groupId: String(session.guildId),
|
|
672
889
|
mode: 'reply',
|
|
673
890
|
};
|
|
674
|
-
const styleSections = await this.hooks.collectSections(hookCtx);
|
|
891
|
+
const styleSections = this.clampStyle(await this.hooks.collectSections(hookCtx));
|
|
675
892
|
const webSearch = await this.webSearch(record, session);
|
|
676
893
|
const promptInput = {
|
|
677
894
|
selfName: this.selfName,
|
|
678
895
|
persona: this.personaPrompt,
|
|
679
896
|
groupId: String(session.guildId),
|
|
680
|
-
records: state.records,
|
|
897
|
+
records: this.clampContext(state.records),
|
|
681
898
|
current: record,
|
|
682
899
|
mention,
|
|
683
900
|
followup,
|
|
@@ -790,6 +1007,7 @@ export class AiEngine {
|
|
|
790
1007
|
images: images.length,
|
|
791
1008
|
degradedToText: !!result.degradedToText,
|
|
792
1009
|
chars: finalText.length,
|
|
1010
|
+
tokens: usageText(result.usage) || undefined,
|
|
793
1011
|
preview: finalText.slice(0, 60),
|
|
794
1012
|
}, session);
|
|
795
1013
|
|
|
@@ -815,7 +1033,7 @@ export class AiEngine {
|
|
|
815
1033
|
const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
|
|
816
1034
|
let sections: string[] = [];
|
|
817
1035
|
try {
|
|
818
|
-
sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
|
|
1036
|
+
sections = this.clampStyle(await this.hooks.collectSections({ session, groupId, mode: 'reply' }));
|
|
819
1037
|
} catch { /* ignore */ }
|
|
820
1038
|
const system = [
|
|
821
1039
|
`你是 QQ 群 ${groupId} 里的一个普通成员。`,
|
package/src/ai/learn.ts
CHANGED
|
@@ -206,3 +206,59 @@ export function isDuplicate(candidate: string, existing: string[], threshold = 0
|
|
|
206
206
|
}
|
|
207
207
|
return false;
|
|
208
208
|
}
|
|
209
|
+
|
|
210
|
+
// ---------------------------------------------------------------- 记忆压缩
|
|
211
|
+
|
|
212
|
+
/** 自动归纳条目的标题标记(写进 Markdown 块首行) */
|
|
213
|
+
export const AUTO_MEMORY_LABEL = '自动归纳';
|
|
214
|
+
|
|
215
|
+
/** 自动归纳块首行形如 `## 2026/10/28 12:00:00 · 自动归纳` */
|
|
216
|
+
export function isAutoMemoryBlock(block: string): boolean {
|
|
217
|
+
const first = String(block || '').split('\n', 1)[0] || '';
|
|
218
|
+
return /·\s*自动归纳/.test(first);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** 取记忆块正文(去掉 `## 时间 · 来源` 标题行) */
|
|
222
|
+
export function memoryBlockBody(block: string): string {
|
|
223
|
+
const lines = String(block || '').split('\n');
|
|
224
|
+
if (lines.length <= 1) return String(block || '').trim();
|
|
225
|
+
return lines.slice(1).join('\n').trim();
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 记忆压缩提示词:把 N 条自动归纳合并成一条更短的。
|
|
230
|
+
*
|
|
231
|
+
* 目的不是“再总结一遍”,而是去掉重复与过时信息——群里连续几天聊同一件事时,
|
|
232
|
+
* 自动归纳会反复产出高度相似的条目,压缩后只保留事实差异。
|
|
233
|
+
*/
|
|
234
|
+
export function buildConsolidatePrompt(
|
|
235
|
+
blocks: string[],
|
|
236
|
+
options: { maxChars?: number; kind?: string } = {},
|
|
237
|
+
): { system: string; user: string } {
|
|
238
|
+
const maxChars = Math.max(40, Number(options.maxChars) || 90);
|
|
239
|
+
const label = options.kind === 'private' ? '私聊' : '群聊';
|
|
240
|
+
const bodies = (blocks || [])
|
|
241
|
+
.map((block) => memoryBlockBody(block).replace(/\s+/g, ' ').trim())
|
|
242
|
+
.filter(Boolean);
|
|
243
|
+
|
|
244
|
+
const system = [
|
|
245
|
+
`你在压缩一段${label}的长期记忆。`,
|
|
246
|
+
`下面有 ${bodies.length} 条已经归纳过的记忆,请合并成一条。`,
|
|
247
|
+
'',
|
|
248
|
+
'要求:',
|
|
249
|
+
'- 只保留互不重复的事实:人物与称呼、关系、稳定偏好、反复出现的话题;',
|
|
250
|
+
'- 删掉重复表述、一次性情绪、已经过时的细节;',
|
|
251
|
+
'- 不要编造,不要写“他们聊到”“讨论了”这类过程描述;',
|
|
252
|
+
`- 只输出一条纯文本,不超过 ${maxChars} 字,不要标题、编号、列表、Markdown;`,
|
|
253
|
+
'- 如果这些记忆里没有任何值得保留的内容,只输出一个词:NONE',
|
|
254
|
+
].join('\n');
|
|
255
|
+
|
|
256
|
+
const user = [
|
|
257
|
+
'【待压缩的记忆】',
|
|
258
|
+
...bodies.map((text, index) => `${index + 1}. ${text}`),
|
|
259
|
+
'',
|
|
260
|
+
'现在输出合并后的那一条记忆,或输出 NONE。',
|
|
261
|
+
].join('\n');
|
|
262
|
+
|
|
263
|
+
return { system, user };
|
|
264
|
+
}
|
package/src/ai/provider.ts
CHANGED
|
@@ -14,6 +14,8 @@ export interface ChatRequest {
|
|
|
14
14
|
temperature?: number;
|
|
15
15
|
maxTokens?: number;
|
|
16
16
|
timeoutMs?: number;
|
|
17
|
+
/** 覆盖默认 aiModel(例如自动归纳用更便宜的模型) */
|
|
18
|
+
model?: string;
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
export interface ChatResult {
|
|
@@ -23,6 +25,8 @@ export interface ChatResult {
|
|
|
23
25
|
status?: number;
|
|
24
26
|
/** 是否因为图片被拒而发生了降级重试 */
|
|
25
27
|
degradedToText?: boolean;
|
|
28
|
+
/** 服务端 token 用量(OpenAI: usage;Gemini: usageMetadata) */
|
|
29
|
+
usage?: any;
|
|
26
30
|
}
|
|
27
31
|
|
|
28
32
|
export interface ProviderConfig {
|
|
@@ -65,7 +69,7 @@ export class ChatProvider {
|
|
|
65
69
|
|
|
66
70
|
async chat(request: ChatRequest): Promise<ChatResult> {
|
|
67
71
|
if (!this.apiKey) return { ok: false, error: 'AI 未配置 apiKey' };
|
|
68
|
-
if (!this.model) return { ok: false, error: 'AI 未配置 model' };
|
|
72
|
+
if (!this.model && !String(request.model || '').trim()) return { ok: false, error: 'AI 未配置 model' };
|
|
69
73
|
|
|
70
74
|
const provider = String(this.config.aiProvider ?? 'openai-compatible');
|
|
71
75
|
const requested = (request.images ?? []).filter((item) => /^data:image\//i.test(item) || /^https?:\/\//i.test(item));
|
|
@@ -113,6 +117,7 @@ export class ChatProvider {
|
|
|
113
117
|
options: { maxTokens?: number; retried?: boolean } = {},
|
|
114
118
|
): Promise<ChatResult> {
|
|
115
119
|
const base = String(this.config.aiBaseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
|
|
120
|
+
const model = String(request.model || this.model).trim();
|
|
116
121
|
const content: any[] = [{ type: 'text', text: request.user }];
|
|
117
122
|
for (const url of images) content.push({ type: 'image_url', image_url: { url } });
|
|
118
123
|
const userContent = images.length ? content : request.user;
|
|
@@ -131,7 +136,7 @@ export class ChatProvider {
|
|
|
131
136
|
'Content-Type': 'application/json',
|
|
132
137
|
},
|
|
133
138
|
body: JSON.stringify({
|
|
134
|
-
model
|
|
139
|
+
model,
|
|
135
140
|
temperature: request.temperature ?? this.config.aiTemperature ?? 0.8,
|
|
136
141
|
max_tokens: maxTokens,
|
|
137
142
|
messages: [
|
|
@@ -180,7 +185,7 @@ export class ChatProvider {
|
|
|
180
185
|
error: `模型返回空内容(finish=${payload?.choices?.[0]?.finish_reason || 'unknown'})`,
|
|
181
186
|
};
|
|
182
187
|
}
|
|
183
|
-
return { ok: true, text, status: response.status };
|
|
188
|
+
return { ok: true, text, status: response.status, usage: payload?.usage };
|
|
184
189
|
} catch (error: any) {
|
|
185
190
|
const aborted = error?.name === 'AbortError';
|
|
186
191
|
return { ok: false, error: aborted ? '请求超时' : `请求失败: ${String(error?.message || error)}` };
|
|
@@ -192,7 +197,8 @@ export class ChatProvider {
|
|
|
192
197
|
private async callGemini(request: ChatRequest, images: string[]): Promise<ChatResult> {
|
|
193
198
|
const rawBase = String(this.config.aiBaseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/+$/, '');
|
|
194
199
|
const base = /\/v\d/i.test(rawBase) ? rawBase : `${rawBase}/v1beta`;
|
|
195
|
-
const
|
|
200
|
+
const model = String(request.model || this.model).trim();
|
|
201
|
+
const endpoint = `${base}/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(this.apiKey)}`;
|
|
196
202
|
const parts: any[] = [{ text: request.user }];
|
|
197
203
|
for (const url of images) {
|
|
198
204
|
const match = /^data:(image\/[^;]+);base64,(.*)$/i.exec(url);
|
|
@@ -228,7 +234,7 @@ export class ChatProvider {
|
|
|
228
234
|
.join('')
|
|
229
235
|
.trim();
|
|
230
236
|
if (!text) return { ok: false, status: response.status, error: 'Gemini 返回空内容' };
|
|
231
|
-
return { ok: true, text, status: response.status };
|
|
237
|
+
return { ok: true, text, status: response.status, usage: payload?.usageMetadata };
|
|
232
238
|
} catch (error: any) {
|
|
233
239
|
const aborted = error?.name === 'AbortError';
|
|
234
240
|
return { ok: false, error: aborted ? '请求超时' : `请求失败: ${String(error?.message || error)}` };
|
package/src/ai/state.ts
CHANGED
|
@@ -43,6 +43,10 @@ export class GroupState {
|
|
|
43
43
|
counter = 0;
|
|
44
44
|
lastReplyAt = 0;
|
|
45
45
|
lastAttemptAt = 0;
|
|
46
|
+
/** 上次发「冷却中」提示的时间,用于避免 @ 刷屏时反复提示 */
|
|
47
|
+
lastCooldownNoticeAt = 0;
|
|
48
|
+
/** 伪随机加成:随机未命中时累加,命中后归零 */
|
|
49
|
+
randomBoost = 0;
|
|
46
50
|
inFlight = false;
|
|
47
51
|
followup: FollowupState | null = null;
|
|
48
52
|
seen = new Map<string, number>();
|