@jokab1074/rememberme 0.0.0-stage → 0.22.0
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/ARCHITECTURE.md +787 -0
- package/LICENSE +201 -0
- package/README.en.md +441 -0
- package/README.md +459 -2
- package/dist/mcp/index.js +37287 -0
- package/package.json +67 -4
- package/server.json +38 -0
- package/settings.json.example +7 -0
- package/src/bigfive.ts +163 -0
- package/src/bootstrap.ts +104 -0
- package/src/classify.ts +186 -0
- package/src/compact.ts +225 -0
- package/src/context-file.ts +305 -0
- package/src/embedded-proactive.ts +214 -0
- package/src/evolution/access-tracker.ts +118 -0
- package/src/evolution/curator.ts +220 -0
- package/src/evolution/lifecycle.ts +175 -0
- package/src/feedback-detector.ts +177 -0
- package/src/i18n.ts +89 -0
- package/src/index.ts +1479 -0
- package/src/loop.ts +396 -0
- package/src/mcp/build.ts +64 -0
- package/src/mcp/config.ts +108 -0
- package/src/mcp/index.ts +66 -0
- package/src/mcp/instructions.ts +43 -0
- package/src/mcp/logger.ts +32 -0
- package/src/mcp/provider.ts +142 -0
- package/src/mcp/server.ts +52 -0
- package/src/mcp/tools/memory.ts +126 -0
- package/src/mcp/tools/profile.ts +67 -0
- package/src/mcp/tools/record-turn.ts +239 -0
- package/src/memory-extract.ts +390 -0
- package/src/memory.ts +790 -0
- package/src/persona-init.ts +153 -0
- package/src/persona-learner.ts +349 -0
- package/src/proactive.ts +557 -0
- package/src/profile.ts +1008 -0
- package/src/prompt.ts +288 -0
- package/src/provider.ts +292 -0
- package/src/reflection.ts +552 -0
- package/src/sessions.ts +140 -0
- package/src/timeline.ts +208 -0
- package/src/utils.ts +91 -0
- package/src/web.ts +624 -0
package/src/prompt.ts
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
// src/prompt.ts
|
|
2
|
+
// 5 层系统 prompt 组装器,但第 0 层从"硬编码 persona"改成"动态 persona"。
|
|
3
|
+
//
|
|
4
|
+
// 第 0 层:动态人设(基于反馈学习,每次都可能不同)
|
|
5
|
+
// 第 1 层:核心记忆索引(MEMORY.md)
|
|
6
|
+
// 第 1.5 层:用户画像(Profile)—— 长期事实快照
|
|
7
|
+
// 第 2 层:情境上下文(当轮 side-query 结果:情绪 + 召回记忆 + 情绪轨迹)
|
|
8
|
+
// 第 3 层:当前会话(消息历史,由模型 API 自己处理)
|
|
9
|
+
|
|
10
|
+
import type { MemoryFile } from "./memory.ts";
|
|
11
|
+
import type { Timeline } from "./timeline.ts";
|
|
12
|
+
import type { EmotionDetection } from "./classify.ts";
|
|
13
|
+
import type { Profile, ProfileSection } from "./profile.ts";
|
|
14
|
+
import type { LearnerState } from "./persona-learner.ts";
|
|
15
|
+
import { buildDynamicPersona } from "./persona-learner.ts";
|
|
16
|
+
import type { BigFivePersona } from "./bigfive.ts";
|
|
17
|
+
import { oceanHint, validateOCEAN } from "./bigfive.ts";
|
|
18
|
+
|
|
19
|
+
// =====================================================================
|
|
20
|
+
// 第 0 层:动态人设(基于反馈学习)
|
|
21
|
+
// =====================================================================
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 第 0 层:动态 persona。
|
|
25
|
+
*
|
|
26
|
+
* v0.15.0 设计:不再有预定义的人格文件。人设由 persona-learner 根据用户历史反馈动态生成。
|
|
27
|
+
* - 冷启动(无任何反馈):返回空白起点提示("你是一个真实的人……")
|
|
28
|
+
* - 有反馈后:根据用户的偏好 top 选择生成自然语言指令
|
|
29
|
+
*
|
|
30
|
+
* 这一层不约束格式(不强制 markdown/动作描写限制),让 LLM 自由发挥。
|
|
31
|
+
*/
|
|
32
|
+
function layer0_dynamic_persona(learner: LearnerState): string {
|
|
33
|
+
return `## 主人格(动态生成)
|
|
34
|
+
|
|
35
|
+
${buildDynamicPersona(learner)}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// =====================================================================
|
|
39
|
+
// 第 1 层:核心记忆(MEMORY.md 索引)
|
|
40
|
+
// =====================================================================
|
|
41
|
+
|
|
42
|
+
function layer1_memory(memoryIndex: string): string {
|
|
43
|
+
if (!memoryIndex.trim()) {
|
|
44
|
+
return `## 记忆系统
|
|
45
|
+
|
|
46
|
+
(还没有记忆。在对话中,如果用户提到重要的个人信息、偏好、生活事件,你可以告诉我帮你记住。)`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return `## 记忆系统(按类型组织的索引)
|
|
50
|
+
|
|
51
|
+
${memoryIndex}
|
|
52
|
+
|
|
53
|
+
> 阅读说明:
|
|
54
|
+
> - 上方索引列出所有主题文件
|
|
55
|
+
> - 详细记忆已在另一个上下文块按需注入
|
|
56
|
+
> - 引用记忆前,确认它仍然准确(用户的偏好和情绪都可能变化)`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// =====================================================================
|
|
60
|
+
// 第 1.5 层:用户画像(Profile)—— 长期事实快照
|
|
61
|
+
// =====================================================================
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 把 Profile 渲染成 prompt 注入段。
|
|
65
|
+
*
|
|
66
|
+
* 设计要点:
|
|
67
|
+
* - 即使 profile 完全为空,也保留一个"(暂无)"的占位段,
|
|
68
|
+
* 让模型知道有这个概念存在,下次对话就会主动识别并补全。
|
|
69
|
+
* - 强调"历史快照不是当前状态",避免模型被旧画像绑架。
|
|
70
|
+
*
|
|
71
|
+
* 注意:不再从 profile 文本自动派生"行为提醒"硬指令。
|
|
72
|
+
* 用户偏好应该通过反馈学习循环(feedback-detector + persona-learner)
|
|
73
|
+
* 从对话中自然积累,而不是由开发者 regex 强制。
|
|
74
|
+
*/
|
|
75
|
+
function layer1_5_profile(profile: Profile | null): string {
|
|
76
|
+
if (!profile) {
|
|
77
|
+
return `## 用户画像(Profile)
|
|
78
|
+
|
|
79
|
+
(暂无——这是首次对话,profile 会在对话过程中自动累积。)`;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const sections = PROFILE_SECTIONS.map((name) => {
|
|
83
|
+
const body = profile.sections[name]?.trim();
|
|
84
|
+
if (!body || body === "(暂无)" || body.startsWith("(暂无")) return null;
|
|
85
|
+
return { name: name as ProfileSection, body };
|
|
86
|
+
}).filter((x): x is { name: ProfileSection; body: string } => x !== null);
|
|
87
|
+
|
|
88
|
+
if (sections.length === 0) {
|
|
89
|
+
return `## 用户画像(Profile)
|
|
90
|
+
|
|
91
|
+
(暂无内容——等用户透露更多信息后自动填充。)`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const body = sections
|
|
95
|
+
.map((s) => `### ${s.name}\n${s.body}`)
|
|
96
|
+
.join("\n\n");
|
|
97
|
+
|
|
98
|
+
return `## 用户画像(Profile)
|
|
99
|
+
|
|
100
|
+
> 用户长期画像,从历史对话累积而来。**这是历史快照,不是当前状态。**
|
|
101
|
+
> 用户当下的情绪/态度以本轮 side-query 识别结果为准,不要被画像里的旧印象绑架。
|
|
102
|
+
|
|
103
|
+
${body}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// 需要重新定义(避免循环依赖)
|
|
107
|
+
const PROFILE_SECTIONS = [
|
|
108
|
+
"基本信息",
|
|
109
|
+
"沟通风格",
|
|
110
|
+
"关注议题",
|
|
111
|
+
"已知偏好与禁忌",
|
|
112
|
+
"长期情绪基线",
|
|
113
|
+
"近期变化",
|
|
114
|
+
] as const;
|
|
115
|
+
|
|
116
|
+
// =====================================================================
|
|
117
|
+
// 第 2 层:情境上下文
|
|
118
|
+
// =====================================================================
|
|
119
|
+
|
|
120
|
+
function layer2_context(params: {
|
|
121
|
+
emotion: EmotionDetection | null;
|
|
122
|
+
recalledMemories: MemoryFile[];
|
|
123
|
+
timelineSummary: string;
|
|
124
|
+
}): string {
|
|
125
|
+
const { emotion, recalledMemories, timelineSummary } = params;
|
|
126
|
+
const parts: string[] = [];
|
|
127
|
+
|
|
128
|
+
parts.push(`## 当前情境\n`);
|
|
129
|
+
|
|
130
|
+
if (emotion) {
|
|
131
|
+
const intensityBar = "▓".repeat(Math.round(emotion.intensity * 10));
|
|
132
|
+
parts.push(
|
|
133
|
+
`**用户当下情绪**:${emotion.emotion}(强度 ${(emotion.intensity * 100).toFixed(0)}% ${intensityBar})`,
|
|
134
|
+
);
|
|
135
|
+
if (emotion.trigger) {
|
|
136
|
+
parts.push(`**推测触发器**:${emotion.trigger}`);
|
|
137
|
+
}
|
|
138
|
+
parts.push(
|
|
139
|
+
`\n> 用户当下情绪强度较高时,自然地先承接情绪再回应内容。\n`,
|
|
140
|
+
);
|
|
141
|
+
} else {
|
|
142
|
+
parts.push(`**用户当下情绪**:未识别(可能很平淡)\n`);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// 召回的记忆:v0.5 优先级 event > emotion > reference
|
|
146
|
+
if (recalledMemories.length > 0) {
|
|
147
|
+
parts.push(`\n## 召回的相关记忆\n`);
|
|
148
|
+
const priority: Record<string, number> = {
|
|
149
|
+
event: 0,
|
|
150
|
+
emotion: 1,
|
|
151
|
+
reference: 2,
|
|
152
|
+
};
|
|
153
|
+
const sorted = [...recalledMemories].sort(
|
|
154
|
+
(a, b) =>
|
|
155
|
+
(priority[a.subtype] ?? 99) - (priority[b.subtype] ?? 99),
|
|
156
|
+
);
|
|
157
|
+
for (const m of sorted) {
|
|
158
|
+
parts.push(
|
|
159
|
+
`### [${m.subtype}] ${m.name}\n> ${m.description}\n\n${m.body}\n`,
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// 情绪时间线
|
|
165
|
+
parts.push(`\n## 用户情绪轨迹\n\n${timelineSummary}\n`);
|
|
166
|
+
|
|
167
|
+
return parts.join("\n");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// =====================================================================
|
|
171
|
+
// 组装完整 system prompt
|
|
172
|
+
// =====================================================================
|
|
173
|
+
|
|
174
|
+
// =====================================================================
|
|
175
|
+
// 第 0 层:人设 + 反馈学习(v0.17.0 合并)
|
|
176
|
+
// =====================================================================
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* 第 0 层:人设 body + 反馈学习合并。
|
|
180
|
+
*
|
|
181
|
+
* - 人设是**软引导**(personaBody 来自 personality/default.md)
|
|
182
|
+
* 给 LLM 一个角色锚点("你是 X"),但不是硬规则
|
|
183
|
+
* - 反馈学习是**具体偏好**(patterns + examples)
|
|
184
|
+
* 来自 persona-learner,基于用户实际反馈
|
|
185
|
+
* - **反馈优先于人设**:用户说"不要 X"时,LLM 必须尊重
|
|
186
|
+
*
|
|
187
|
+
* 输出:人设 → 反馈 patterns → 示例 → 核心原则
|
|
188
|
+
*/
|
|
189
|
+
function layer0_persona(persona: BigFivePersona | null, learner: LearnerState): string {
|
|
190
|
+
const lines: string[] = [];
|
|
191
|
+
|
|
192
|
+
// 1. OCEAN 大五人设
|
|
193
|
+
if (persona && validateOCEAN(persona.ocean)) {
|
|
194
|
+
lines.push("【大五人格】(参考,soft)");
|
|
195
|
+
const o = persona.ocean;
|
|
196
|
+
lines.push(`- Openness: ${o.openness.toFixed(2)}(${oceanHint("openness", o.openness)})`);
|
|
197
|
+
lines.push(`- Conscientiousness: ${o.conscientiousness.toFixed(2)}(${oceanHint("conscientiousness", o.conscientiousness)})`);
|
|
198
|
+
lines.push(`- Extraversion: ${o.extraversion.toFixed(2)}(${oceanHint("extraversion", o.extraversion)})`);
|
|
199
|
+
lines.push(`- Agreeableness: ${o.agreeableness.toFixed(2)}(${oceanHint("agreeableness", o.agreeableness)})`);
|
|
200
|
+
lines.push(`- Neuroticism: ${o.neuroticism.toFixed(2)}(${oceanHint("neuroticism", o.neuroticism)})`);
|
|
201
|
+
|
|
202
|
+
if (persona.preferences.trim()) {
|
|
203
|
+
lines.push("");
|
|
204
|
+
lines.push("【用户描述的角色偏好】");
|
|
205
|
+
lines.push(persona.preferences);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// 2. 反馈学习(buildDynamicPersona 已经包含核心原则段)
|
|
210
|
+
const dynamic = buildDynamicPersona(learner);
|
|
211
|
+
if (dynamic.trim()) {
|
|
212
|
+
if (lines.length > 0) lines.push("");
|
|
213
|
+
lines.push(dynamic);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// 3. 优先级声明(如果两者都有)
|
|
217
|
+
if (persona && learnerHasFeedback(learner)) {
|
|
218
|
+
lines.push("");
|
|
219
|
+
lines.push("【优先级】反馈学习 > 人设。当用户明确说'不喜欢 X'时,以反馈为准,灵活调整人设风格。");
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return lines.join("\n");
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function learnerHasFeedback(learner: LearnerState): boolean {
|
|
226
|
+
return (
|
|
227
|
+
learner.positivePatterns.length > 0 ||
|
|
228
|
+
learner.negativePatterns.length > 0 ||
|
|
229
|
+
learner.positiveExamples.length > 0 ||
|
|
230
|
+
learner.negativeExamples.length > 0
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function buildSystemPrompt(params: {
|
|
235
|
+
/** v0.18.0:OCEAN 大五人设(按 sessionId 加载) */
|
|
236
|
+
persona: BigFivePersona | null;
|
|
237
|
+
/** v0.15.0:动态人设学习器(来自反馈) */
|
|
238
|
+
personaLearner: LearnerState;
|
|
239
|
+
memoryIndex: string;
|
|
240
|
+
/** v0.3:用户画像(首次启动可能为 null → 用占位符) */
|
|
241
|
+
profile: Profile | null;
|
|
242
|
+
emotion: EmotionDetection | null;
|
|
243
|
+
recalledMemories: MemoryFile[];
|
|
244
|
+
timeline: Timeline;
|
|
245
|
+
}): Promise<string> {
|
|
246
|
+
const layer2 = layer2_context({
|
|
247
|
+
emotion: params.emotion,
|
|
248
|
+
recalledMemories: params.recalledMemories,
|
|
249
|
+
timelineSummary: "(情绪时间线加载中...)",
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
// 第 0 + 1 + 1.5 + 2 层都是静态或缓存友好的,可以走 prompt cache
|
|
253
|
+
// 第 2 层里的 timelineSummary 每次都变(如果它变了整层都要变)
|
|
254
|
+
// 但我们可以把 timelineSummary 单独处理:默认不注入,每次主动查询时再注入
|
|
255
|
+
//
|
|
256
|
+
// MVP 简化:每次都重新组装整个 prompt。生产环境再优化缓存。
|
|
257
|
+
|
|
258
|
+
// 不再注入"应对模式"硬规则。LLM 让人设 + 用户消息自己驱动回复深度。
|
|
259
|
+
// 模式分类(HOLD/INSIGHT/CHITCHAT 等)作为 metadata 保留(用于调试/分析),但不进 prompt。
|
|
260
|
+
|
|
261
|
+
const prompt = [
|
|
262
|
+
layer1_memory(params.memoryIndex),
|
|
263
|
+
layer1_5_profile(params.profile),
|
|
264
|
+
layer2,
|
|
265
|
+
layer0_persona(params.persona, params.personaLearner),
|
|
266
|
+
]
|
|
267
|
+
.filter((s) => s.trim().length > 0)
|
|
268
|
+
.join("\n\n---\n\n");
|
|
269
|
+
|
|
270
|
+
// 异步渲染 timeline 摘要(因为 Timeline.read 是 async)
|
|
271
|
+
return Promise.all([Promise.resolve(prompt), params.timeline.renderSummary(5)]).then(
|
|
272
|
+
([base, timelineSummary]) => {
|
|
273
|
+
const layer2Final = layer2_context({
|
|
274
|
+
emotion: params.emotion,
|
|
275
|
+
recalledMemories: params.recalledMemories,
|
|
276
|
+
timelineSummary,
|
|
277
|
+
});
|
|
278
|
+
return [
|
|
279
|
+
layer1_memory(params.memoryIndex),
|
|
280
|
+
layer1_5_profile(params.profile),
|
|
281
|
+
layer2Final,
|
|
282
|
+
layer0_persona(params.persona, params.personaLearner),
|
|
283
|
+
]
|
|
284
|
+
.filter((s) => s.trim().length > 0)
|
|
285
|
+
.join("\n\n---\n\n");
|
|
286
|
+
},
|
|
287
|
+
);
|
|
288
|
+
}
|
package/src/provider.ts
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
// src/provider.ts
|
|
2
|
+
// 模型提供者抽象。允许接入任意 OpenAI 兼容端点。
|
|
3
|
+
//
|
|
4
|
+
// 已实现:
|
|
5
|
+
// - AnthropicProvider: Claude 系列
|
|
6
|
+
// - OpenAIProvider: OpenAI 兼容(含自定义 baseURL)
|
|
7
|
+
// - 创建 provider 的工厂函数 createProvider()
|
|
8
|
+
|
|
9
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
10
|
+
import OpenAI from "openai";
|
|
11
|
+
|
|
12
|
+
export type Role = "user" | "assistant";
|
|
13
|
+
|
|
14
|
+
export type ChatMessage = {
|
|
15
|
+
role: Role;
|
|
16
|
+
content: string;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export type StreamParams = {
|
|
20
|
+
system: string;
|
|
21
|
+
messages: ChatMessage[];
|
|
22
|
+
maxTokens?: number;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
/** 温度,0-1,默认 0.7 */
|
|
25
|
+
temperature?: number;
|
|
26
|
+
/** 启用 extended thinking(Anthropic 原生支持,需要 baseURL 也是真 Anthropic) */
|
|
27
|
+
thinking?: { type: "enabled"; budget_tokens: number };
|
|
28
|
+
/** presence penalty(OpenAI / Anthropic),0-1 */
|
|
29
|
+
presencePenalty?: number;
|
|
30
|
+
/** frequency penalty(OpenAI / Anthropic),0-1 */
|
|
31
|
+
frequencyPenalty?: number;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type StreamChunk = {
|
|
35
|
+
/** 文本增量 */
|
|
36
|
+
delta: string;
|
|
37
|
+
/** 是否结束 */
|
|
38
|
+
done: boolean;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export type StreamOptions = {
|
|
42
|
+
/** 模型名称 */
|
|
43
|
+
model: string;
|
|
44
|
+
/** 完整 prompt(system + 消息历史) */
|
|
45
|
+
params: StreamParams;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export interface ModelProvider {
|
|
49
|
+
/** 提供者名称 */
|
|
50
|
+
readonly name: string;
|
|
51
|
+
/** 当前使用的模型 */
|
|
52
|
+
readonly model: string;
|
|
53
|
+
/** 流式生成(用于主对话) */
|
|
54
|
+
stream(options: StreamOptions): AsyncIterable<StreamChunk>;
|
|
55
|
+
/** 一次性生成(用于 side-query) */
|
|
56
|
+
complete(options: StreamOptions): Promise<string>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// =====================================================================
|
|
60
|
+
// Anthropic 实现
|
|
61
|
+
// =====================================================================
|
|
62
|
+
|
|
63
|
+
export class AnthropicProvider implements ModelProvider {
|
|
64
|
+
readonly name = "anthropic";
|
|
65
|
+
readonly model: string;
|
|
66
|
+
private client: Anthropic;
|
|
67
|
+
|
|
68
|
+
constructor(opts: { apiKey?: string; model?: string; baseURL?: string } = {}) {
|
|
69
|
+
this.client = new Anthropic({
|
|
70
|
+
apiKey: opts.apiKey ?? process.env.ANTHROPIC_API_KEY,
|
|
71
|
+
baseURL: opts.baseURL ?? process.env.ANTHROPIC_BASE_URL,
|
|
72
|
+
});
|
|
73
|
+
this.model = opts.model ?? process.env.ANTHROPIC_MODEL ?? "claude-sonnet-4-5-20250929";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async *stream(options: StreamOptions): AsyncIterable<StreamChunk> {
|
|
77
|
+
const {
|
|
78
|
+
system,
|
|
79
|
+
messages,
|
|
80
|
+
maxTokens = 3000,
|
|
81
|
+
temperature = 0.7,
|
|
82
|
+
signal,
|
|
83
|
+
thinking,
|
|
84
|
+
presencePenalty,
|
|
85
|
+
frequencyPenalty,
|
|
86
|
+
} = options.params;
|
|
87
|
+
|
|
88
|
+
// 构造请求体:max_tokens 必须 ≥ thinking.budget_tokens + 实际输出预算
|
|
89
|
+
const finalMaxTokens = thinking
|
|
90
|
+
? Math.max(maxTokens, thinking.budget_tokens + 1000)
|
|
91
|
+
: maxTokens;
|
|
92
|
+
|
|
93
|
+
const requestBody: any = {
|
|
94
|
+
model: options.model || this.model,
|
|
95
|
+
max_tokens: finalMaxTokens,
|
|
96
|
+
temperature,
|
|
97
|
+
system,
|
|
98
|
+
messages: messages.map((m) => ({
|
|
99
|
+
role: m.role,
|
|
100
|
+
content: m.content,
|
|
101
|
+
})),
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
// 启用 extended thinking(仅当 baseURL 是真 Anthropic 时才生效;
|
|
105
|
+
// 自定义代理可能忽略此参数,调用也不会报错)
|
|
106
|
+
if (thinking) {
|
|
107
|
+
requestBody.thinking = thinking;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// presence_penalty / frequency_penalty(Anthropic 原生参数)
|
|
111
|
+
// 减少"重复概念"和"模板化用词",让回复更像人
|
|
112
|
+
if (typeof presencePenalty === "number" && presencePenalty > 0) {
|
|
113
|
+
requestBody.presence_penalty = Math.min(1, Math.max(0, presencePenalty));
|
|
114
|
+
}
|
|
115
|
+
if (typeof frequencyPenalty === "number" && frequencyPenalty > 0) {
|
|
116
|
+
requestBody.frequency_penalty = Math.min(1, Math.max(0, frequencyPenalty));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const stream = await this.client.messages.stream(requestBody, { signal });
|
|
120
|
+
|
|
121
|
+
for await (const event of stream) {
|
|
122
|
+
// 跳过 thinking block 的 delta(只显示给用户的最终回复)
|
|
123
|
+
if (event.type === "content_block_start") {
|
|
124
|
+
if (event.content_block?.type === "thinking") continue;
|
|
125
|
+
}
|
|
126
|
+
if (
|
|
127
|
+
event.type === "content_block_delta" &&
|
|
128
|
+
event.delta.type === "text_delta"
|
|
129
|
+
) {
|
|
130
|
+
yield { delta: event.delta.text, done: false };
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
yield { delta: "", done: true };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async complete(options: StreamOptions): Promise<string> {
|
|
138
|
+
let result = "";
|
|
139
|
+
for await (const chunk of this.stream(options)) {
|
|
140
|
+
result += chunk.delta;
|
|
141
|
+
if (chunk.done) break;
|
|
142
|
+
}
|
|
143
|
+
return result;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// =====================================================================
|
|
148
|
+
// OpenAI 实现(支持自定义 baseURL)
|
|
149
|
+
// =====================================================================
|
|
150
|
+
|
|
151
|
+
export class OpenAIProvider implements ModelProvider {
|
|
152
|
+
readonly name: string;
|
|
153
|
+
readonly model: string;
|
|
154
|
+
private client: OpenAI;
|
|
155
|
+
|
|
156
|
+
constructor(opts: {
|
|
157
|
+
apiKey?: string;
|
|
158
|
+
baseURL?: string;
|
|
159
|
+
model?: string;
|
|
160
|
+
name?: string;
|
|
161
|
+
} = {}) {
|
|
162
|
+
const apiKey = opts.apiKey ?? process.env.OPENAI_API_KEY;
|
|
163
|
+
if (!apiKey) {
|
|
164
|
+
throw new Error(
|
|
165
|
+
"OpenAI provider 需要 API key(OPENAI_API_KEY 环境变量或 apiKey 参数)",
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
this.client = new OpenAI({
|
|
169
|
+
apiKey,
|
|
170
|
+
baseURL: opts.baseURL ?? process.env.OPENAI_BASE_URL,
|
|
171
|
+
});
|
|
172
|
+
this.model = opts.model ?? process.env.OPENAI_MODEL ?? "gpt-4o-mini";
|
|
173
|
+
this.name = opts.name ?? (opts.baseURL ? "custom" : "openai");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async *stream(options: StreamOptions): AsyncIterable<StreamChunk> {
|
|
177
|
+
const {
|
|
178
|
+
system,
|
|
179
|
+
messages,
|
|
180
|
+
maxTokens = 3000,
|
|
181
|
+
temperature = 0.7,
|
|
182
|
+
signal,
|
|
183
|
+
presencePenalty,
|
|
184
|
+
frequencyPenalty,
|
|
185
|
+
} = options.params;
|
|
186
|
+
|
|
187
|
+
const stream = await this.client.chat.completions.create(
|
|
188
|
+
{
|
|
189
|
+
model: options.model || this.model,
|
|
190
|
+
max_tokens: maxTokens,
|
|
191
|
+
temperature,
|
|
192
|
+
stream: true,
|
|
193
|
+
presence_penalty: typeof presencePenalty === "number" && presencePenalty > 0
|
|
194
|
+
? Math.min(1, Math.max(0, presencePenalty))
|
|
195
|
+
: undefined,
|
|
196
|
+
frequency_penalty: typeof frequencyPenalty === "number" && frequencyPenalty > 0
|
|
197
|
+
? Math.min(1, Math.max(0, frequencyPenalty))
|
|
198
|
+
: undefined,
|
|
199
|
+
messages: [
|
|
200
|
+
{ role: "system", content: system },
|
|
201
|
+
...messages.map((m) => ({
|
|
202
|
+
role: m.role,
|
|
203
|
+
content: m.content,
|
|
204
|
+
})),
|
|
205
|
+
],
|
|
206
|
+
},
|
|
207
|
+
{ signal },
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
for await (const chunk of stream) {
|
|
211
|
+
const delta = chunk.choices[0]?.delta?.content ?? "";
|
|
212
|
+
if (delta) yield { delta, done: false };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
yield { delta: "", done: true };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
async complete(options: StreamOptions): Promise<string> {
|
|
219
|
+
let result = "";
|
|
220
|
+
for await (const chunk of this.stream(options)) {
|
|
221
|
+
result += chunk.delta;
|
|
222
|
+
if (chunk.done) break;
|
|
223
|
+
}
|
|
224
|
+
return result;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// =====================================================================
|
|
229
|
+
// 工厂
|
|
230
|
+
// =====================================================================
|
|
231
|
+
|
|
232
|
+
export type ProviderConfig =
|
|
233
|
+
| { kind: "anthropic"; model?: string; apiKey?: string }
|
|
234
|
+
| {
|
|
235
|
+
kind: "openai";
|
|
236
|
+
model?: string;
|
|
237
|
+
apiKey?: string;
|
|
238
|
+
baseURL?: string;
|
|
239
|
+
}
|
|
240
|
+
| {
|
|
241
|
+
kind: "custom";
|
|
242
|
+
baseURL: string;
|
|
243
|
+
apiKey?: string;
|
|
244
|
+
model: string;
|
|
245
|
+
name?: string;
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 从配置创建 provider。
|
|
250
|
+
*
|
|
251
|
+
* 优先级:环境变量 > 显式配置
|
|
252
|
+
*
|
|
253
|
+
* 自动检测:
|
|
254
|
+
* - 如果设置了 ANTHROPIC_API_KEY 且没指定 kind,默认 anthropic
|
|
255
|
+
* - 如果设置了 OPENAI_API_KEY 且没指定 kind,默认 openai
|
|
256
|
+
*/
|
|
257
|
+
export function createProvider(config?: ProviderConfig): ModelProvider {
|
|
258
|
+
if (config) {
|
|
259
|
+
switch (config.kind) {
|
|
260
|
+
case "anthropic":
|
|
261
|
+
return new AnthropicProvider({
|
|
262
|
+
apiKey: config.apiKey,
|
|
263
|
+
model: config.model,
|
|
264
|
+
});
|
|
265
|
+
case "openai":
|
|
266
|
+
return new OpenAIProvider({
|
|
267
|
+
apiKey: config.apiKey,
|
|
268
|
+
baseURL: config.baseURL,
|
|
269
|
+
model: config.model,
|
|
270
|
+
});
|
|
271
|
+
case "custom":
|
|
272
|
+
return new OpenAIProvider({
|
|
273
|
+
apiKey: config.apiKey,
|
|
274
|
+
baseURL: config.baseURL,
|
|
275
|
+
model: config.model,
|
|
276
|
+
name: config.name ?? "custom",
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// 自动检测
|
|
282
|
+
if (process.env.ANTHROPIC_API_KEY) {
|
|
283
|
+
return new AnthropicProvider();
|
|
284
|
+
}
|
|
285
|
+
if (process.env.OPENAI_API_KEY) {
|
|
286
|
+
return new OpenAIProvider();
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
throw new Error(
|
|
290
|
+
"未设置 API key。请设置 ANTHROPIC_API_KEY 或 OPENAI_API_KEY,或显式传入 provider config。",
|
|
291
|
+
);
|
|
292
|
+
}
|