my-ai-chat-framework 2.0.0 → 2.7.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/README.md +242 -45
- package/dist/my-ai-chat-framework.browser.es.js +1048 -184
- package/dist/my-ai-chat-framework.browser.es.js.map +1 -1
- package/dist/my-ai-chat-framework.browser.umd.js +1056 -188
- package/dist/my-ai-chat-framework.browser.umd.js.map +1 -1
- package/dist/my-ai-chat-framework.node.cjs.js +1056 -188
- package/dist/my-ai-chat-framework.node.cjs.js.map +1 -1
- package/package.json +7 -7
- package/src/adapters/openai.js +214 -64
- package/src/core/ChatService.js +298 -110
- package/src/core/Errors.js +60 -0
- package/src/core/EventEmitter.js +19 -0
- package/src/core/MessageStore.js +39 -0
- package/src/core/SystemPromptStore.js +118 -0
- package/src/index.js +10 -14
- package/src/plugins/model-registry.js +187 -0
- package/src/plugins/tool-calling.js +172 -78
- package/src/utils/MessageFormatter.js +204 -0
- package/src/utils/typeCheck.js +12 -0
- package/src/utils/url.js +18 -0
- package/.env +0 -15
- package/test.js +0 -107
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
//#region src/core/EventEmitter.js
|
|
2
2
|
/**
|
|
3
3
|
* 极简事件发射器
|
|
4
|
+
* 支持同步/异步事件,handler 返回 Promise 时自动 await
|
|
4
5
|
*/
|
|
5
6
|
var EventEmitter = class {
|
|
6
7
|
constructor() {
|
|
@@ -17,6 +18,9 @@ var EventEmitter = class {
|
|
|
17
18
|
if (handlers.length) this._events.set(event, handlers);
|
|
18
19
|
else this._events.delete(event);
|
|
19
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* 同步触发事件
|
|
23
|
+
*/
|
|
20
24
|
emit(event, data) {
|
|
21
25
|
if (!this._events.has(event)) return;
|
|
22
26
|
for (const handler of this._events.get(event)) try {
|
|
@@ -25,6 +29,18 @@ var EventEmitter = class {
|
|
|
25
29
|
console.error(`事件 ${event} 处理出错:`, err);
|
|
26
30
|
}
|
|
27
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* 异步触发事件,逐个 await handler
|
|
34
|
+
* handler 返回 Promise 时自动等待
|
|
35
|
+
*/
|
|
36
|
+
async emitAsync(event, data) {
|
|
37
|
+
if (!this._events.has(event)) return;
|
|
38
|
+
for (const handler of this._events.get(event)) try {
|
|
39
|
+
await handler(data);
|
|
40
|
+
} catch (err) {
|
|
41
|
+
console.error(`事件 ${event} 处理出错:`, err);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
28
44
|
};
|
|
29
45
|
//#endregion
|
|
30
46
|
//#region src/core/MessageStore.js
|
|
@@ -35,6 +51,10 @@ var EventEmitter = class {
|
|
|
35
51
|
* id?: string,
|
|
36
52
|
* role: 'user'|'assistant'|'system'|'tool',
|
|
37
53
|
* content: string,
|
|
54
|
+
* images?: Array<string>, // 图片引用(URL / id),框架不存储图片数据
|
|
55
|
+
* _ephemeral?: boolean, // 临时消息:仅底部连续时参与请求,续写后转正
|
|
56
|
+
* _complete?: boolean, // 流式是否完成(false=未完成/中断)
|
|
57
|
+
* prefix?: boolean, // 前缀续写标记
|
|
38
58
|
* toolCalls?: Array,
|
|
39
59
|
* toolCallId?: string,
|
|
40
60
|
* timestamp?: number,
|
|
@@ -84,6 +104,22 @@ var MessageStore = class {
|
|
|
84
104
|
metadata
|
|
85
105
|
});
|
|
86
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* 快速添加一次性的、带续写标记的 assistant 消息
|
|
109
|
+
* 适用于思维链引导、临时注入等场景
|
|
110
|
+
* @param {string} content — 引导内容
|
|
111
|
+
* @param {Object} [options] — { reasoningContent, prefix }
|
|
112
|
+
* @returns {Object} 添加的消息
|
|
113
|
+
*/
|
|
114
|
+
addOnceAssistant(content, options = {}) {
|
|
115
|
+
return this.add({
|
|
116
|
+
role: "assistant",
|
|
117
|
+
content,
|
|
118
|
+
reasoningContent: options.reasoningContent,
|
|
119
|
+
prefix: options.prefix !== false,
|
|
120
|
+
_ephemeral: true
|
|
121
|
+
});
|
|
122
|
+
}
|
|
87
123
|
getLast() {
|
|
88
124
|
return this._messages[this._messages.length - 1] || null;
|
|
89
125
|
}
|
|
@@ -102,106 +138,667 @@ var MessageStore = class {
|
|
|
102
138
|
if (lastAssistantIndex >= 0) return this._messages.splice(lastAssistantIndex + 1);
|
|
103
139
|
return [];
|
|
104
140
|
}
|
|
141
|
+
/**
|
|
142
|
+
* 更新消息:按 id 查找并合并 changes,不新增消息
|
|
143
|
+
* @param {string} id — 消息 id
|
|
144
|
+
* @param {Object} changes — 要合并的字段
|
|
145
|
+
* @returns {Object|null} 更新后的消息,未找到返回 null
|
|
146
|
+
*/
|
|
147
|
+
update(id, changes) {
|
|
148
|
+
for (const msg of this._messages) if (msg.id === id) {
|
|
149
|
+
Object.assign(msg, changes);
|
|
150
|
+
msg.timestamp = changes.timestamp || Date.now();
|
|
151
|
+
return msg;
|
|
152
|
+
}
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
105
155
|
};
|
|
106
156
|
//#endregion
|
|
107
|
-
//#region src/core/
|
|
157
|
+
//#region src/core/SystemPromptStore.js
|
|
108
158
|
/**
|
|
109
|
-
*
|
|
110
|
-
*
|
|
159
|
+
* SystemPromptStore — 系统提示词存储
|
|
160
|
+
*
|
|
161
|
+
* 职责:管理多条 system prompt 的增删改查与开关
|
|
162
|
+
* 与 MessageStore 分离,因为 system prompt 是"AI 行为准则",不是对话事件
|
|
163
|
+
*
|
|
164
|
+
* 每条记录格式:
|
|
165
|
+
* {
|
|
166
|
+
* id: string,
|
|
167
|
+
* content: string,
|
|
168
|
+
* enabled: boolean,
|
|
169
|
+
* timestamp: number
|
|
170
|
+
* }
|
|
111
171
|
*/
|
|
172
|
+
var SystemPromptStore = class {
|
|
173
|
+
constructor() {
|
|
174
|
+
this._prompts = [];
|
|
175
|
+
this._idCounter = 0;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* 添加一条 system prompt
|
|
179
|
+
* @param {string} content — 提示词内容
|
|
180
|
+
* @param {boolean} [enabled=true] — 是否启用
|
|
181
|
+
* @returns {Object} 添加的记录
|
|
182
|
+
*/
|
|
183
|
+
add(content, enabled = true) {
|
|
184
|
+
if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
|
|
185
|
+
const record = {
|
|
186
|
+
id: `sys_${Date.now()}_${++this._idCounter}`,
|
|
187
|
+
content: content.trim(),
|
|
188
|
+
enabled: Boolean(enabled),
|
|
189
|
+
timestamp: Date.now()
|
|
190
|
+
};
|
|
191
|
+
this._prompts.push(record);
|
|
192
|
+
return record;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* 删除指定索引的 system prompt
|
|
196
|
+
* @param {number} index
|
|
197
|
+
* @returns {Object} 被删除的记录
|
|
198
|
+
*/
|
|
199
|
+
remove(index) {
|
|
200
|
+
if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
|
|
201
|
+
return this._prompts.splice(index, 1)[0];
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* 切换指定索引的启用/禁用状态
|
|
205
|
+
* @param {number} index
|
|
206
|
+
* @returns {boolean} 切换后的状态
|
|
207
|
+
*/
|
|
208
|
+
toggle(index) {
|
|
209
|
+
if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
|
|
210
|
+
this._prompts[index].enabled = !this._prompts[index].enabled;
|
|
211
|
+
return this._prompts[index].enabled;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* 更新指定索引的 content
|
|
215
|
+
* @param {number} index
|
|
216
|
+
* @param {string} content
|
|
217
|
+
*/
|
|
218
|
+
update(index, content) {
|
|
219
|
+
if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
|
|
220
|
+
if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
|
|
221
|
+
this._prompts[index].content = content.trim();
|
|
222
|
+
this._prompts[index].timestamp = Date.now();
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* 清空并用一条 content 替换(便捷方法,常用于 config.system = '...')
|
|
226
|
+
* @param {string} content
|
|
227
|
+
*/
|
|
228
|
+
set(content) {
|
|
229
|
+
this._prompts = [];
|
|
230
|
+
if (content && typeof content === "string" && content.trim()) this.add(content, true);
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* 按 enabled 筛选后,转为适配器可用的格式
|
|
234
|
+
* @returns {Array<{role:'system', content:string}>}
|
|
235
|
+
*/
|
|
236
|
+
getEnabled() {
|
|
237
|
+
return this._prompts.filter((p) => p.enabled).map((p) => ({
|
|
238
|
+
role: "system",
|
|
239
|
+
content: p.content
|
|
240
|
+
}));
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* 返回所有记录(含 enabled 状态,用于 UI 展示)
|
|
244
|
+
* @returns {Array}
|
|
245
|
+
*/
|
|
246
|
+
getAll() {
|
|
247
|
+
return [...this._prompts];
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* 清空所有 system prompt
|
|
251
|
+
*/
|
|
252
|
+
clear() {
|
|
253
|
+
this._prompts = [];
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
//#endregion
|
|
257
|
+
//#region src/core/Errors.js
|
|
258
|
+
/**
|
|
259
|
+
* 自定义错误类
|
|
260
|
+
* 用于区分不同类型的错误,方便用户通过 `error.name` 或 `instanceof` 处理
|
|
261
|
+
*/
|
|
262
|
+
var APIError = class extends Error {
|
|
263
|
+
/**
|
|
264
|
+
* @param {string} message - 错误消息(通常来自 API 响应)
|
|
265
|
+
* @param {number} statusCode - HTTP 状态码
|
|
266
|
+
* @param {any} originalError - 原始错误对象或相关信息
|
|
267
|
+
* @param {string} responseText - 原始响应文本(如果有)
|
|
268
|
+
*/
|
|
269
|
+
constructor(message, statusCode, originalError, responseText) {
|
|
270
|
+
super(message);
|
|
271
|
+
this.name = "APIError";
|
|
272
|
+
this.statusCode = statusCode;
|
|
273
|
+
this.originalError = originalError;
|
|
274
|
+
this.responseText = responseText;
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
var NetworkError = class extends Error {
|
|
278
|
+
/**
|
|
279
|
+
* @param {string} message - 错误消息
|
|
280
|
+
* @param {any} originalError - 原始错误对象或相关信息
|
|
281
|
+
*/
|
|
282
|
+
constructor(message, originalError) {
|
|
283
|
+
super(message);
|
|
284
|
+
this.name = "NetworkError";
|
|
285
|
+
this.originalError = originalError;
|
|
286
|
+
}
|
|
287
|
+
};
|
|
288
|
+
var ConfigurationError = class extends Error {
|
|
289
|
+
/**
|
|
290
|
+
* @param {string} message - 错误消息
|
|
291
|
+
*/
|
|
292
|
+
constructor(message) {
|
|
293
|
+
super(message);
|
|
294
|
+
this.name = "ConfigurationError";
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
var ParsingError = class extends Error {
|
|
298
|
+
/**
|
|
299
|
+
* @param {string} message - 错误消息
|
|
300
|
+
* @param {any} originalError - 原始错误对象或相关信息
|
|
301
|
+
* @param {string} responseText - 原始响应文本(如果有)
|
|
302
|
+
**/
|
|
303
|
+
constructor(message, originalError, responseText) {
|
|
304
|
+
super(message);
|
|
305
|
+
this.name = "ParsingError";
|
|
306
|
+
this.originalError = originalError;
|
|
307
|
+
this.responseText = responseText;
|
|
308
|
+
}
|
|
309
|
+
};
|
|
310
|
+
//#endregion
|
|
311
|
+
//#region src/core/ChatService.js
|
|
112
312
|
var ChatService = class extends EventEmitter {
|
|
113
313
|
constructor(config = {}) {
|
|
114
314
|
super();
|
|
115
|
-
this.config = {
|
|
116
|
-
apiKey: config.apiKey || "",
|
|
117
|
-
model: config.model || "gpt-3.5-turbo",
|
|
118
|
-
...config
|
|
119
|
-
};
|
|
315
|
+
this.config = { ...config };
|
|
120
316
|
this.messages = new MessageStore();
|
|
121
|
-
this.
|
|
317
|
+
this.systemPrompts = new SystemPromptStore();
|
|
122
318
|
this._adapter = null;
|
|
123
|
-
this.
|
|
319
|
+
this._abortController = null;
|
|
320
|
+
this._isGenerating = false;
|
|
321
|
+
this._hooks = new EventEmitter();
|
|
322
|
+
this._processResponse = null;
|
|
323
|
+
const model = this.config.model || this.config.modelParams?.model;
|
|
324
|
+
if (!model || typeof model !== "string" || !model.trim()) throw new ConfigurationError("缺少 model 配置");
|
|
325
|
+
const temperature = this.config.modelParams?.temperature ?? this.config.temperature;
|
|
326
|
+
if (temperature !== void 0 && (typeof temperature !== "number" || temperature < 0 || temperature > 2)) throw new ConfigurationError(`temperature 必须在 0-2 之间,当前值: ${temperature}`);
|
|
327
|
+
const maxTokens = this.config.modelParams?.maxTokens ?? this.config.maxTokens;
|
|
328
|
+
if (maxTokens !== void 0 && (typeof maxTokens !== "number" || maxTokens < 1 || !Number.isInteger(maxTokens))) throw new ConfigurationError(`maxTokens 必须为正整数,当前值: ${maxTokens}`);
|
|
329
|
+
if (typeof config.system === "string" && config.system.trim()) this.systemPrompts.set(config.system);
|
|
124
330
|
}
|
|
125
|
-
/**
|
|
126
|
-
* 加载插件
|
|
127
|
-
* @param {object} plugin - 必须包含 install 方法
|
|
128
|
-
*/
|
|
129
331
|
use(plugin) {
|
|
130
|
-
|
|
131
|
-
plugin.install(this);
|
|
132
|
-
this._plugins.push(plugin);
|
|
133
|
-
} else throw new Error("插件必须提供 install 方法");
|
|
332
|
+
plugin.install(this);
|
|
134
333
|
return this;
|
|
135
334
|
}
|
|
136
|
-
/**
|
|
137
|
-
* 设置 API 适配器
|
|
138
|
-
*/
|
|
139
335
|
setAdapter(adapter) {
|
|
140
336
|
this._adapter = adapter;
|
|
141
|
-
return this;
|
|
142
337
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
338
|
+
abort() {
|
|
339
|
+
if (this._abortController) this._abortController.abort();
|
|
340
|
+
}
|
|
341
|
+
get isGenerating() {
|
|
342
|
+
return this._isGenerating;
|
|
343
|
+
}
|
|
344
|
+
async continueLast() {
|
|
345
|
+
const target = this._prepareContinue();
|
|
346
|
+
this.messages.update(target.id, { prefix: true });
|
|
347
|
+
try {
|
|
348
|
+
await this._request({
|
|
349
|
+
addUser: false,
|
|
350
|
+
isStream: false,
|
|
351
|
+
mergeToEntry: target.id
|
|
352
|
+
});
|
|
353
|
+
this.messages.update(target.id, {
|
|
354
|
+
_complete: true,
|
|
355
|
+
prefix: void 0,
|
|
356
|
+
_ephemeral: void 0
|
|
357
|
+
});
|
|
358
|
+
return target;
|
|
359
|
+
} catch (err) {
|
|
360
|
+
this.messages.update(target.id, { prefix: void 0 });
|
|
361
|
+
throw err;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
async continueLastStream(onProgress, onDone) {
|
|
365
|
+
const target = this._prepareContinue();
|
|
366
|
+
console.log("[DEBUG] continueLastStream target.id:", target.id);
|
|
367
|
+
this.messages.update(target.id, { prefix: true });
|
|
368
|
+
const baseLen = (target.content || "").length;
|
|
369
|
+
try {
|
|
370
|
+
await this._request({
|
|
371
|
+
addUser: false,
|
|
372
|
+
isStream: true,
|
|
373
|
+
mergeToEntry: target.id,
|
|
374
|
+
onProgress: (chunk) => {
|
|
375
|
+
if (onProgress) onProgress({
|
|
376
|
+
...chunk,
|
|
377
|
+
content: (chunk.content || "").slice(baseLen)
|
|
378
|
+
});
|
|
379
|
+
},
|
|
380
|
+
onDone: (final) => {
|
|
381
|
+
if (onDone) onDone(final);
|
|
382
|
+
}
|
|
383
|
+
});
|
|
384
|
+
this.messages.update(target.id, {
|
|
385
|
+
_complete: true,
|
|
386
|
+
prefix: void 0,
|
|
387
|
+
_ephemeral: void 0
|
|
388
|
+
});
|
|
389
|
+
return target;
|
|
390
|
+
} catch (err) {
|
|
391
|
+
this.messages.update(target.id, { prefix: void 0 });
|
|
392
|
+
throw err;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
_prepareContinue() {
|
|
396
|
+
const msgs = this.messages.getAll();
|
|
397
|
+
const last = msgs[msgs.length - 1];
|
|
398
|
+
if (last && (last.role === "assistant" || last._ephemeral)) return last;
|
|
399
|
+
throw new Error("最后一条消息不是 assistant,无法续写");
|
|
400
|
+
}
|
|
401
|
+
updateConfig(partial) {
|
|
402
|
+
Object.assign(this.config, partial);
|
|
403
|
+
if (typeof partial.system === "string") this.systemPrompts.set(partial.system);
|
|
404
|
+
this.emit("config-updated", {
|
|
405
|
+
changes: partial,
|
|
406
|
+
timestamp: Date.now()
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
async _request(options) {
|
|
410
|
+
let { userInput, addUser = true, isStream = false, onProgress, onDone, mergeToEntry } = options;
|
|
411
|
+
this.emit("sending", {
|
|
412
|
+
addUser,
|
|
413
|
+
userInput,
|
|
414
|
+
timestamp: Date.now()
|
|
415
|
+
});
|
|
416
|
+
this._addUserMessage(userInput, addUser);
|
|
417
|
+
await this._hooks.emitAsync("beforeRequest", {
|
|
418
|
+
messages: this.messages,
|
|
419
|
+
config: this.config,
|
|
420
|
+
options
|
|
421
|
+
});
|
|
422
|
+
if (this.config.ephemeralContinue && !mergeToEntry) {
|
|
423
|
+
const msgs = this.messages.getAll();
|
|
424
|
+
const last = msgs[msgs.length - 1];
|
|
425
|
+
if (last && last.prefix && (last.role === "assistant" || last._ephemeral)) mergeToEntry = last.id;
|
|
426
|
+
}
|
|
427
|
+
const body = this._adapter.buildRequest(this.messages.getAll(), this.config, this.systemPrompts.getEnabled());
|
|
428
|
+
const retryCfg = this.config.retry || {};
|
|
429
|
+
try {
|
|
430
|
+
return await this._withRetry(body, {
|
|
431
|
+
isStream,
|
|
432
|
+
onProgress,
|
|
433
|
+
onDone,
|
|
434
|
+
mergeToEntry,
|
|
435
|
+
maxRetries: retryCfg.maxRetries ?? 0,
|
|
436
|
+
retryDelay: retryCfg.retryDelay ?? 1e3
|
|
437
|
+
});
|
|
438
|
+
} catch (error) {
|
|
439
|
+
this.emit("error", {
|
|
440
|
+
error,
|
|
441
|
+
timestamp: Date.now()
|
|
442
|
+
});
|
|
443
|
+
throw error;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
_addUserMessage(userInput, addUser) {
|
|
447
|
+
if (addUser && userInput !== void 0) {
|
|
448
|
+
const msg = typeof userInput === "string" ? {
|
|
449
|
+
role: "user",
|
|
450
|
+
content: userInput
|
|
451
|
+
} : {
|
|
452
|
+
role: "user",
|
|
453
|
+
...userInput
|
|
454
|
+
};
|
|
455
|
+
this.messages.add(msg);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
/** retry 循环,占位消息只 push 一次 */
|
|
459
|
+
async _withRetry(body, { isStream, onProgress, onDone, mergeToEntry, maxRetries, retryDelay }) {
|
|
460
|
+
let lastError = null;
|
|
461
|
+
const adapterOptions = { signal: this._abortController?.signal };
|
|
462
|
+
let placeholder = null;
|
|
463
|
+
let base = null;
|
|
464
|
+
if (isStream) {
|
|
465
|
+
if (mergeToEntry) {
|
|
466
|
+
placeholder = this.messages.getAll().find((m) => m.id === mergeToEntry);
|
|
467
|
+
if (placeholder) base = {
|
|
468
|
+
content: placeholder.content || "",
|
|
469
|
+
reasoning: placeholder.reasoningContent || ""
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
if (!placeholder) placeholder = this.messages.add({
|
|
473
|
+
role: "assistant",
|
|
474
|
+
content: "",
|
|
475
|
+
_complete: false
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
479
|
+
if (attempt > 0) {
|
|
480
|
+
this.emit("retry", {
|
|
481
|
+
attempt,
|
|
482
|
+
maxRetries,
|
|
483
|
+
lastError,
|
|
484
|
+
timestamp: Date.now()
|
|
485
|
+
});
|
|
486
|
+
await new Promise((r) => setTimeout(r, retryDelay));
|
|
487
|
+
}
|
|
488
|
+
try {
|
|
489
|
+
this._isGenerating = true;
|
|
490
|
+
if (isStream) return await this._stream(body, adapterOptions, {
|
|
491
|
+
placeholder,
|
|
492
|
+
base,
|
|
493
|
+
mergeToEntry,
|
|
494
|
+
onProgress,
|
|
495
|
+
onDone
|
|
496
|
+
});
|
|
497
|
+
else {
|
|
498
|
+
const resp = await this._adapter.send(body, this.config, adapterOptions);
|
|
499
|
+
let result = this._handleResult(this._adapter.parseResponse(resp), mergeToEntry);
|
|
500
|
+
if (this._processResponse && !mergeToEntry) result = await this._processResponse(result, { isStream: false });
|
|
501
|
+
return result;
|
|
502
|
+
}
|
|
503
|
+
} catch (error) {
|
|
504
|
+
lastError = error;
|
|
505
|
+
if (error.name === "AbortError" || this._abortController?.signal.aborted) {
|
|
506
|
+
this._isGenerating = false;
|
|
507
|
+
throw error;
|
|
508
|
+
}
|
|
509
|
+
if (error instanceof NetworkError && attempt < maxRetries) continue;
|
|
510
|
+
this._isGenerating = false;
|
|
511
|
+
throw error;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
this._isGenerating = false;
|
|
515
|
+
throw lastError;
|
|
516
|
+
}
|
|
517
|
+
/** 流式:ChatService 维护占位,adapter 只管解析 */
|
|
518
|
+
async _stream(body, adapterOptions, { placeholder, base, mergeToEntry, onProgress, onDone }) {
|
|
519
|
+
let finalMsg = null;
|
|
520
|
+
await this._adapter.stream(body, this.config, (snap) => {
|
|
521
|
+
placeholder.content = snap.content || "";
|
|
522
|
+
if (snap.reasoningContent) placeholder.reasoningContent = snap.reasoningContent;
|
|
523
|
+
if (snap.toolCalls) placeholder.toolCalls = [...snap.toolCalls];
|
|
524
|
+
this.emit("stream-progress", snap);
|
|
525
|
+
if (onProgress) onProgress(snap);
|
|
526
|
+
}, async (final) => {
|
|
527
|
+
finalMsg = final;
|
|
528
|
+
if (this._processResponse && !mergeToEntry) finalMsg = await this._processResponse(finalMsg, {
|
|
529
|
+
isStream: true,
|
|
530
|
+
onProgress,
|
|
531
|
+
onDone
|
|
532
|
+
});
|
|
533
|
+
if (mergeToEntry && base) {
|
|
534
|
+
const changes = {
|
|
535
|
+
content: base.content + (final.content || ""),
|
|
536
|
+
_complete: true
|
|
537
|
+
};
|
|
538
|
+
if (final.reasoningContent) changes.reasoningContent = base.reasoning + final.reasoningContent;
|
|
539
|
+
if (final.toolCalls) changes.toolCalls = final.toolCalls;
|
|
540
|
+
this.messages.update(mergeToEntry, changes);
|
|
541
|
+
const updated = this.messages.getAll().find((m) => m.id === mergeToEntry);
|
|
542
|
+
this.emit("message", updated);
|
|
543
|
+
if (onDone) onDone(updated);
|
|
544
|
+
} else {
|
|
545
|
+
placeholder._complete = true;
|
|
546
|
+
this.emit("message", finalMsg);
|
|
547
|
+
if (onDone) onDone(finalMsg);
|
|
548
|
+
}
|
|
549
|
+
}, adapterOptions);
|
|
550
|
+
return mergeToEntry || finalMsg;
|
|
551
|
+
}
|
|
552
|
+
/** 非流式结果落位 */
|
|
553
|
+
_handleResult(assistantMsg, mergeToEntry) {
|
|
554
|
+
if (mergeToEntry) {
|
|
555
|
+
const entry = this.messages.getAll().find((m) => m.id === mergeToEntry);
|
|
556
|
+
if (!entry) {
|
|
557
|
+
this.messages.add(assistantMsg);
|
|
558
|
+
this.emit("message", assistantMsg);
|
|
559
|
+
return assistantMsg;
|
|
560
|
+
}
|
|
561
|
+
const changes = {
|
|
562
|
+
content: (entry.content || "") + (assistantMsg.content || ""),
|
|
563
|
+
_complete: true
|
|
564
|
+
};
|
|
565
|
+
if (assistantMsg.reasoningContent) changes.reasoningContent = (entry.reasoningContent || "") + assistantMsg.reasoningContent;
|
|
566
|
+
if (assistantMsg.toolCalls) changes.toolCalls = assistantMsg.toolCalls;
|
|
567
|
+
this.messages.update(mergeToEntry, changes);
|
|
568
|
+
const updated = this.messages.getAll().find((m) => m.id === mergeToEntry);
|
|
569
|
+
this.emit("message", updated);
|
|
570
|
+
return updated;
|
|
571
|
+
}
|
|
160
572
|
this.messages.add(assistantMsg);
|
|
161
573
|
this.emit("message", assistantMsg);
|
|
162
574
|
return assistantMsg;
|
|
163
575
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
this.
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
this.
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
576
|
+
async send(userInput) {
|
|
577
|
+
this._abortController = new AbortController();
|
|
578
|
+
try {
|
|
579
|
+
return await this._request({
|
|
580
|
+
userInput,
|
|
581
|
+
addUser: true,
|
|
582
|
+
isStream: false
|
|
583
|
+
});
|
|
584
|
+
} finally {
|
|
585
|
+
this._abortController = null;
|
|
586
|
+
this._isGenerating = false;
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
async stream(userInput, onProgress, onDone) {
|
|
590
|
+
this._abortController = new AbortController();
|
|
591
|
+
try {
|
|
592
|
+
return await this._request({
|
|
593
|
+
userInput,
|
|
594
|
+
addUser: true,
|
|
595
|
+
isStream: true,
|
|
596
|
+
onProgress,
|
|
597
|
+
onDone
|
|
598
|
+
});
|
|
599
|
+
} finally {
|
|
600
|
+
this._abortController = null;
|
|
601
|
+
this._isGenerating = false;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
async sendExisting() {
|
|
605
|
+
this._abortController = new AbortController();
|
|
606
|
+
try {
|
|
607
|
+
return await this._request({
|
|
608
|
+
addUser: false,
|
|
609
|
+
isStream: false
|
|
610
|
+
});
|
|
611
|
+
} finally {
|
|
612
|
+
this._abortController = null;
|
|
613
|
+
this._isGenerating = false;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
async sendExistingStream(onProgress, onDone) {
|
|
617
|
+
this._abortController = new AbortController();
|
|
618
|
+
try {
|
|
619
|
+
return await this._request({
|
|
620
|
+
addUser: false,
|
|
621
|
+
isStream: true,
|
|
622
|
+
onProgress,
|
|
623
|
+
onDone
|
|
624
|
+
});
|
|
625
|
+
} finally {
|
|
626
|
+
this._abortController = null;
|
|
627
|
+
this._isGenerating = false;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
//#endregion
|
|
632
|
+
//#region src/utils/url.js
|
|
633
|
+
/**
|
|
634
|
+
* URL 工具函数
|
|
635
|
+
*/
|
|
636
|
+
/**
|
|
637
|
+
* 拼接 baseUrl 和 path
|
|
638
|
+
* 注意:path 应以 '/' 开头,否则会替换 baseUrl 的最后一段
|
|
639
|
+
* @param {string} baseUrl - 基础 URL(如 https://api.deepseek.com)
|
|
640
|
+
* @param {string} path - 路径(如 /v1/chat/completions)
|
|
641
|
+
* @returns {string} 完整的 URL
|
|
642
|
+
*/
|
|
643
|
+
function joinUrl(baseUrl, path) {
|
|
644
|
+
return baseUrl.replace(/\/$/, "") + (path.startsWith("/") ? path : "/" + path);
|
|
645
|
+
}
|
|
646
|
+
//#endregion
|
|
647
|
+
//#region src/utils/typeCheck.js
|
|
648
|
+
/**
|
|
649
|
+
* 类型判断工具
|
|
650
|
+
*/
|
|
651
|
+
/**
|
|
652
|
+
* 判断一个值是否为字符串
|
|
653
|
+
* @param {any} value - 要检查的值
|
|
654
|
+
* @returns {boolean} 如果是字符串则返回 true
|
|
655
|
+
*/
|
|
656
|
+
function isString(value) {
|
|
657
|
+
return typeof value === "string";
|
|
658
|
+
}
|
|
659
|
+
//#endregion
|
|
660
|
+
//#region src/utils/MessageFormatter.js
|
|
661
|
+
/**
|
|
662
|
+
* MessageFormatter — 可注册的消息格式转换器
|
|
663
|
+
*
|
|
664
|
+
* 职责:
|
|
665
|
+
* 1. 内置 OpenA I兼容格式的转换逻辑
|
|
666
|
+
* 2. 支持 register(name, fn) 注册自定义格式(如 Anthropic、Gemini 等)
|
|
667
|
+
* 3. 统一处理 capabilities 过滤(reasoning、vision 等)
|
|
668
|
+
* 4. 所有适配器通过此工具获取 API 消息数组,消除重复代码
|
|
669
|
+
*
|
|
670
|
+
* 用法:
|
|
671
|
+
* import { MessageFormatter } from 'my-ai-chat-framework';
|
|
672
|
+
*
|
|
673
|
+
* // 使用内置格式
|
|
674
|
+
* const msgs = MessageFormatter.format({
|
|
675
|
+
* messages, systemPrompts, capabilities, resolveImage
|
|
676
|
+
* }); // 默认 'openai'
|
|
677
|
+
*
|
|
678
|
+
* // 注册自定义格式
|
|
679
|
+
* MessageFormatter.register('anthropic', ({ messages, systemPrompts, capabilities }) => {
|
|
680
|
+
* // 返回 Anthropic 格式的消息数组
|
|
681
|
+
* });
|
|
682
|
+
*/
|
|
683
|
+
var IS_URL = /^https?:\/\//i;
|
|
684
|
+
function defaultResolveImage(imageId) {
|
|
685
|
+
if (IS_URL.test(imageId)) return { url: imageId };
|
|
686
|
+
return null;
|
|
687
|
+
}
|
|
688
|
+
function buildMultimodalContent(textContent, images, resolveImage) {
|
|
689
|
+
const content = [{
|
|
690
|
+
type: "text",
|
|
691
|
+
text: textContent
|
|
692
|
+
}];
|
|
693
|
+
for (const ref of images) {
|
|
694
|
+
const resolved = resolveImage(ref);
|
|
695
|
+
if (!resolved) continue;
|
|
696
|
+
if (resolved.url) content.push({
|
|
697
|
+
type: "image_url",
|
|
698
|
+
image_url: { url: resolved.url }
|
|
195
699
|
});
|
|
700
|
+
else if (resolved.data) {
|
|
701
|
+
const mime = resolved.mimeType || "image/png";
|
|
702
|
+
content.push({
|
|
703
|
+
type: "image_url",
|
|
704
|
+
image_url: { url: `data:${mime};base64,${resolved.data}` }
|
|
705
|
+
});
|
|
706
|
+
}
|
|
196
707
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
708
|
+
return content;
|
|
709
|
+
}
|
|
710
|
+
/** OpenAI 兼容格式 */
|
|
711
|
+
function toOpenAI({ messages, systemPrompts, capabilities, resolveImage }) {
|
|
712
|
+
const rImg = typeof resolveImage === "function" ? resolveImage : defaultResolveImage;
|
|
713
|
+
const result = [];
|
|
714
|
+
for (const sp of systemPrompts) if (sp?.content && isString(sp.content) && sp.content.trim()) result.push({
|
|
715
|
+
role: "system",
|
|
716
|
+
content: sp.content.trim()
|
|
717
|
+
});
|
|
718
|
+
let ephemEnd = messages.length;
|
|
719
|
+
for (let i = messages.length - 1; i >= 0; i--) if (messages[i]._ephemeral) ephemEnd = i;
|
|
720
|
+
else break;
|
|
721
|
+
for (let i = 0; i < messages.length; i++) {
|
|
722
|
+
const msg = messages[i];
|
|
723
|
+
if (msg._ephemeral) {
|
|
724
|
+
if (i < ephemEnd) continue;
|
|
725
|
+
}
|
|
726
|
+
if (msg.role === "system" && !msg._ephemeral) continue;
|
|
727
|
+
if (msg.role === "tool") {
|
|
728
|
+
result.push({
|
|
729
|
+
role: "tool",
|
|
730
|
+
content: msg.content || "",
|
|
731
|
+
tool_call_id: msg.toolCallId
|
|
732
|
+
});
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (msg.role === "assistant" && msg.toolCalls?.length) {
|
|
736
|
+
const entry = {
|
|
737
|
+
role: "assistant",
|
|
738
|
+
content: msg.content || "",
|
|
739
|
+
tool_calls: msg.toolCalls
|
|
740
|
+
};
|
|
741
|
+
if (msg.prefix) entry.prefix = true;
|
|
742
|
+
if (capabilities?.reasoning && msg.reasoningContent) entry.reasoning_content = msg.reasoningContent;
|
|
743
|
+
result.push(entry);
|
|
744
|
+
continue;
|
|
745
|
+
}
|
|
746
|
+
const hasText = msg.content && isString(msg.content) && msg.content.trim();
|
|
747
|
+
const hasImages = msg.images && Array.isArray(msg.images) && msg.images.length > 0;
|
|
748
|
+
if (!hasText && !hasImages) {
|
|
749
|
+
if (msg.role === "assistant" && msg.prefix) {
|
|
750
|
+
const prefixEntry = {
|
|
751
|
+
role: "assistant",
|
|
752
|
+
content: "",
|
|
753
|
+
prefix: true
|
|
754
|
+
};
|
|
755
|
+
if (capabilities?.reasoning && msg.reasoningContent) prefixEntry.reasoning_content = msg.reasoningContent;
|
|
756
|
+
result.push(prefixEntry);
|
|
757
|
+
}
|
|
758
|
+
continue;
|
|
759
|
+
}
|
|
760
|
+
const entry = { role: msg.role };
|
|
761
|
+
if (hasImages) {
|
|
762
|
+
if (!capabilities?.vision) throw new Error("[MessageFormatter] 消息包含图片但模型不支持视觉(capabilities.vision=false)。请切换模型或移除图片。");
|
|
763
|
+
entry.content = buildMultimodalContent(msg.content || "", msg.images, rImg);
|
|
764
|
+
} else entry.content = msg.content;
|
|
765
|
+
if (msg.prefix) entry.prefix = true;
|
|
766
|
+
result.push(entry);
|
|
767
|
+
}
|
|
768
|
+
return result;
|
|
769
|
+
}
|
|
770
|
+
var MessageFormatter = {
|
|
771
|
+
_formats: new Map([["openai", toOpenAI]]),
|
|
772
|
+
register(name, fn) {
|
|
773
|
+
if (!name || typeof name !== "string" || !name.trim()) throw new Error("[MessageFormatter] 格式名称必须是非空字符串");
|
|
774
|
+
if (typeof fn !== "function") throw new Error("[MessageFormatter] 转换函数必须是 function");
|
|
775
|
+
this._formats.set(name.trim(), fn);
|
|
776
|
+
},
|
|
777
|
+
unregister(name) {
|
|
778
|
+
if (name === "openai") throw new Error("[MessageFormatter] 内置格式 \"openai\" 不可移除");
|
|
779
|
+
this._formats.delete(name);
|
|
780
|
+
},
|
|
781
|
+
listFormats() {
|
|
782
|
+
return [...this._formats.keys()];
|
|
783
|
+
},
|
|
784
|
+
format(options = {}) {
|
|
785
|
+
const formatName = options.format || "openai";
|
|
786
|
+
const fn = this._formats.get(formatName);
|
|
787
|
+
if (!fn) throw new Error(`[MessageFormatter] 未知格式 "${formatName}"。可用格式: ${[...this._formats.keys()].join(", ")}`);
|
|
788
|
+
return fn({
|
|
789
|
+
messages: options.messages || [],
|
|
790
|
+
systemPrompts: options.systemPrompts || [],
|
|
791
|
+
capabilities: options.capabilities || {},
|
|
792
|
+
resolveImage: options.resolveImage
|
|
793
|
+
});
|
|
203
794
|
}
|
|
204
795
|
};
|
|
796
|
+
function assembleMessages(options = {}) {
|
|
797
|
+
return MessageFormatter.format({
|
|
798
|
+
...options,
|
|
799
|
+
format: "openai"
|
|
800
|
+
});
|
|
801
|
+
}
|
|
205
802
|
//#endregion
|
|
206
803
|
//#region src/adapters/openai.js
|
|
207
804
|
/**
|
|
@@ -213,40 +810,66 @@ var openaiAdapter = {
|
|
|
213
810
|
install(chatService) {
|
|
214
811
|
chatService.setAdapter(this);
|
|
215
812
|
},
|
|
216
|
-
buildRequest(messages, config) {
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
813
|
+
buildRequest(messages, config, systemPrompts = []) {
|
|
814
|
+
const model = config.model || config.modelParams?.model;
|
|
815
|
+
if (!model) throw new Error("Missing required config: model (either at top level or in modelParams)");
|
|
816
|
+
const temperature = config.modelParams?.temperature ?? config.temperature ?? .7;
|
|
817
|
+
const maxTokens = config.modelParams?.maxTokens ?? config.maxTokens ?? 2e3;
|
|
818
|
+
const reasoningEffort = config.modelParams?.reasoningEffort ?? config.reasoningEffort;
|
|
819
|
+
const requestBody = {
|
|
820
|
+
model,
|
|
821
|
+
messages: MessageFormatter.format({
|
|
822
|
+
messages,
|
|
823
|
+
systemPrompts,
|
|
824
|
+
capabilities: config.capabilities || {},
|
|
825
|
+
resolveImage: config.resolveImage,
|
|
826
|
+
format: config.messageFormat
|
|
827
|
+
}),
|
|
828
|
+
temperature,
|
|
829
|
+
max_tokens: maxTokens,
|
|
231
830
|
stream: false
|
|
232
831
|
};
|
|
832
|
+
if (config.tools && Array.isArray(config.tools) && config.tools.length > 0) {
|
|
833
|
+
requestBody.tools = config.tools;
|
|
834
|
+
requestBody.tool_choice = "auto";
|
|
835
|
+
}
|
|
836
|
+
if (reasoningEffort && model === "deepseek-reasoner") requestBody.reasoning_effort = reasoningEffort;
|
|
837
|
+
return requestBody;
|
|
838
|
+
},
|
|
839
|
+
_getUrl(config) {
|
|
840
|
+
config = config || {};
|
|
841
|
+
const { apiUrl, baseUrl, path } = config;
|
|
842
|
+
const defaultPath = "/chat/completions";
|
|
843
|
+
if (apiUrl && isString(apiUrl)) return apiUrl;
|
|
844
|
+
if (baseUrl && isString(baseUrl)) return joinUrl(baseUrl, path && isString(path) ? path : defaultPath);
|
|
845
|
+
return "https://api.openai.com/v1/chat/completions";
|
|
233
846
|
},
|
|
234
|
-
async send(requestBody, config) {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
headers
|
|
847
|
+
async send(requestBody, config, options = {}) {
|
|
848
|
+
try {
|
|
849
|
+
const url = this._getUrl(config);
|
|
850
|
+
const headers = {
|
|
238
851
|
"Content-Type": "application/json",
|
|
239
|
-
"Authorization": `Bearer ${config.apiKey}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
852
|
+
"Authorization": `Bearer ${config.apiKey}`,
|
|
853
|
+
...config.headers || {},
|
|
854
|
+
...options.headers || {}
|
|
855
|
+
};
|
|
856
|
+
const response = await fetch(url, {
|
|
857
|
+
method: "POST",
|
|
858
|
+
headers,
|
|
859
|
+
body: JSON.stringify(requestBody),
|
|
860
|
+
signal: options.signal
|
|
861
|
+
});
|
|
862
|
+
if (!response.ok) await this.handleErrorResponse(response);
|
|
863
|
+
return await response.json();
|
|
864
|
+
} catch (error) {
|
|
865
|
+
if (error instanceof APIError) throw error;
|
|
866
|
+
if (error.name === "AbortError") throw error;
|
|
867
|
+
if (error.name === "TypeError" && error.message.includes("fetch")) throw new NetworkError(`Request failed: ${error.message}`, error);
|
|
868
|
+
throw error;
|
|
246
869
|
}
|
|
247
|
-
return await response.json();
|
|
248
870
|
},
|
|
249
871
|
parseResponse(apiResponse) {
|
|
872
|
+
if (!apiResponse || !apiResponse.choices || !apiResponse.choices[0] || !apiResponse.choices[0].message) throw new ParsingError("Invalid API response: missing choices or message", apiResponse, JSON.stringify(apiResponse));
|
|
250
873
|
const msg = apiResponse.choices[0].message;
|
|
251
874
|
const internal = {
|
|
252
875
|
role: msg.role,
|
|
@@ -256,32 +879,43 @@ var openaiAdapter = {
|
|
|
256
879
|
if (msg.reasoning_content) internal.reasoningContent = msg.reasoning_content;
|
|
257
880
|
return internal;
|
|
258
881
|
},
|
|
259
|
-
async stream(requestBody, config, onProgress, onDone) {
|
|
882
|
+
async stream(requestBody, config, onProgress, onDone, options = {}) {
|
|
260
883
|
const streamBody = {
|
|
261
884
|
...requestBody,
|
|
262
885
|
stream: true
|
|
263
886
|
};
|
|
264
|
-
const
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
},
|
|
271
|
-
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
887
|
+
const url = this._getUrl(config);
|
|
888
|
+
let response;
|
|
889
|
+
const headers = {
|
|
890
|
+
"Content-Type": "application/json",
|
|
891
|
+
"Authorization": `Bearer ${config.apiKey}`,
|
|
892
|
+
"Accept": "text/event-stream",
|
|
893
|
+
...config.headers || {},
|
|
894
|
+
...options.headers || {}
|
|
895
|
+
};
|
|
896
|
+
try {
|
|
897
|
+
response = await fetch(url, {
|
|
898
|
+
method: "POST",
|
|
899
|
+
headers,
|
|
900
|
+
body: JSON.stringify(streamBody),
|
|
901
|
+
signal: options.signal
|
|
902
|
+
});
|
|
903
|
+
} catch (error) {
|
|
904
|
+
if (error.name === "AbortError") throw error;
|
|
905
|
+
if (error.name === "TypeError" && error.message.includes("fetch")) throw new NetworkError(`Stream request failed: ${error.message}`, error);
|
|
906
|
+
throw error;
|
|
276
907
|
}
|
|
908
|
+
if (!response.ok) await this.handleErrorResponse(response);
|
|
277
909
|
const reader = response.body.getReader();
|
|
278
910
|
const decoder = new TextDecoder();
|
|
279
911
|
let buffer = "";
|
|
280
912
|
let accumulated = {
|
|
281
913
|
role: "assistant",
|
|
282
|
-
content: ""
|
|
914
|
+
content: "",
|
|
915
|
+
reasoningContent: ""
|
|
283
916
|
};
|
|
284
917
|
while (true) {
|
|
918
|
+
if (options.signal?.aborted) break;
|
|
285
919
|
const { done, value } = await reader.read();
|
|
286
920
|
if (done) break;
|
|
287
921
|
buffer += decoder.decode(value, { stream: true });
|
|
@@ -289,22 +923,34 @@ var openaiAdapter = {
|
|
|
289
923
|
buffer = lines.pop();
|
|
290
924
|
for (const line of lines) {
|
|
291
925
|
const dataLine = line.replace(/^data: /, "").trim();
|
|
292
|
-
if (!dataLine
|
|
926
|
+
if (!dataLine) continue;
|
|
927
|
+
if (dataLine === "[DONE]") break;
|
|
293
928
|
try {
|
|
294
929
|
const delta = JSON.parse(dataLine).choices?.[0]?.delta;
|
|
295
930
|
if (!delta) continue;
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
931
|
+
if (delta.content) accumulated.content += delta.content;
|
|
932
|
+
if (delta.tool_calls) {
|
|
933
|
+
if (!accumulated.toolCalls) accumulated.toolCalls = [];
|
|
934
|
+
for (const toolCallDelta of delta.tool_calls) {
|
|
935
|
+
const index = toolCallDelta.index;
|
|
936
|
+
if (!accumulated.toolCalls[index]) accumulated.toolCalls[index] = {
|
|
937
|
+
id: "",
|
|
938
|
+
type: "function",
|
|
939
|
+
function: {
|
|
940
|
+
name: "",
|
|
941
|
+
arguments: ""
|
|
942
|
+
}
|
|
943
|
+
};
|
|
944
|
+
if (toolCallDelta.id) accumulated.toolCalls[index].id = toolCallDelta.id;
|
|
945
|
+
if (toolCallDelta.type) accumulated.toolCalls[index].type = toolCallDelta.type;
|
|
946
|
+
if (toolCallDelta.function?.name) accumulated.toolCalls[index].function.name += toolCallDelta.function.name;
|
|
947
|
+
if (toolCallDelta.function?.arguments) accumulated.toolCalls[index].function.arguments += toolCallDelta.function.arguments;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (delta.reasoning_content) accumulated.reasoningContent += delta.reasoning_content;
|
|
305
951
|
onProgress({ ...accumulated });
|
|
306
952
|
} catch (e) {
|
|
307
|
-
console.warn("
|
|
953
|
+
console.warn("stream parsing failed :", e, dataLine);
|
|
308
954
|
}
|
|
309
955
|
}
|
|
310
956
|
}
|
|
@@ -314,13 +960,32 @@ var openaiAdapter = {
|
|
|
314
960
|
toolCalls: accumulated.toolCalls,
|
|
315
961
|
reasoningContent: accumulated.reasoningContent
|
|
316
962
|
});
|
|
963
|
+
},
|
|
964
|
+
async handleErrorResponse(response) {
|
|
965
|
+
let errorText = await response.text();
|
|
966
|
+
let errorMessage = `HTTP ${response.status}`;
|
|
967
|
+
try {
|
|
968
|
+
const errorJson = JSON.parse(errorText);
|
|
969
|
+
errorMessage = errorJson.error?.message || errorJson.message || errorText.slice(0, 200);
|
|
970
|
+
} catch (e) {
|
|
971
|
+
errorMessage = errorText.length > 200 ? errorText.slice(0, 200) + "..." : errorText;
|
|
972
|
+
}
|
|
973
|
+
throw new APIError(errorMessage, response.status, null, errorText);
|
|
317
974
|
}
|
|
318
975
|
};
|
|
319
976
|
//#endregion
|
|
320
977
|
//#region src/plugins/tool-calling.js
|
|
321
978
|
/**
|
|
322
979
|
* 工具调用插件
|
|
323
|
-
*
|
|
980
|
+
* 功能:拦截助手消息中的 tool_calls,执行对应的工具,将结果作为 tool 消息加入对话,
|
|
981
|
+
* 然后自动继续对话(通过 sendExisting / sendExistingStream),直到没有新的工具调用。
|
|
982
|
+
*
|
|
983
|
+
* 设计要点:
|
|
984
|
+
* - 支持普通请求和流式请求(通过 isStream 标志区分)
|
|
985
|
+
* - 支持多次工具调用循环(maxIterations 防止无限循环)
|
|
986
|
+
* - 串行执行工具(可后续升级为并行)
|
|
987
|
+
* - 工具执行失败时,仍然返回错误信息给 AI,而不是中断整个流程
|
|
988
|
+
* - 触发 tool-error 事件,方便用户监听工具执行异常
|
|
324
989
|
*/
|
|
325
990
|
var toolCallingPlugin = {
|
|
326
991
|
name: "tool-calling",
|
|
@@ -328,103 +993,302 @@ var toolCallingPlugin = {
|
|
|
328
993
|
install(chatService) {
|
|
329
994
|
this.chatService = chatService;
|
|
330
995
|
this._tools = /* @__PURE__ */ new Map();
|
|
331
|
-
chatService.
|
|
996
|
+
if (!chatService.config.tools) chatService.config.tools = [];
|
|
997
|
+
/**
|
|
998
|
+
* 注册工具
|
|
999
|
+
* @param {string} name - 工具名称(唯一标识)
|
|
1000
|
+
* @param {string} description - 工具描述(告诉 AI 何时调用)
|
|
1001
|
+
* @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
|
|
1002
|
+
* @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
|
|
1003
|
+
* @returns {ChatService} 返回 chatService 实例,支持链式调用
|
|
1004
|
+
*/
|
|
1005
|
+
chatService.registerTool = (name, description, executor, parameters = {}) => {
|
|
332
1006
|
this._tools.set(name, {
|
|
333
1007
|
executor,
|
|
334
1008
|
description
|
|
335
1009
|
});
|
|
1010
|
+
const toolDefinition = {
|
|
1011
|
+
type: "function",
|
|
1012
|
+
function: {
|
|
1013
|
+
name,
|
|
1014
|
+
description,
|
|
1015
|
+
parameters: {
|
|
1016
|
+
type: "object",
|
|
1017
|
+
properties: parameters,
|
|
1018
|
+
required: Object.keys(parameters).filter((key) => parameters[key]?.required)
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
if (!chatService.config.tools.find((t) => t.function.name === name)) chatService.config.tools.push(toolDefinition);
|
|
336
1023
|
return chatService;
|
|
337
1024
|
};
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
return this._handleWithTools(originalSend, input, false);
|
|
341
|
-
};
|
|
342
|
-
const originalStream = chatService.stream;
|
|
343
|
-
chatService.stream = async (input, onProgress, onDone) => {
|
|
344
|
-
return this._handleWithTools(originalStream, input, true, onProgress, onDone);
|
|
1025
|
+
chatService._processResponse = async (response, { isStream, onProgress, onDone }) => {
|
|
1026
|
+
return this._handleWithTools(response, isStream, onProgress, onDone);
|
|
345
1027
|
};
|
|
346
1028
|
},
|
|
347
|
-
async _handleWithTools(
|
|
1029
|
+
async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
|
|
348
1030
|
const self = this;
|
|
349
1031
|
const chat = this.chatService;
|
|
350
1032
|
let iteration = 0;
|
|
1033
|
+
/**
|
|
1034
|
+
* 递归处理工具调用
|
|
1035
|
+
* @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
|
|
1036
|
+
* @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
|
|
1037
|
+
*/
|
|
351
1038
|
async function processResponse(initialResponse) {
|
|
352
1039
|
let lastResponse = initialResponse;
|
|
353
1040
|
while (iteration < self.maxIterations) {
|
|
354
1041
|
const toolCalls = lastResponse?.toolCalls;
|
|
355
1042
|
if (!toolCalls || toolCalls.length === 0) break;
|
|
356
1043
|
iteration++;
|
|
357
|
-
const toolResults =
|
|
358
|
-
for (const call of toolCalls) {
|
|
1044
|
+
const toolResults = await Promise.all(toolCalls.map(async (call) => {
|
|
359
1045
|
const toolName = call.function?.name;
|
|
360
|
-
|
|
1046
|
+
let args;
|
|
1047
|
+
try {
|
|
1048
|
+
args = JSON.parse(call.function?.arguments || "{}");
|
|
1049
|
+
} catch (parseErr) {
|
|
1050
|
+
chat.emit("tool-error", {
|
|
1051
|
+
toolName: toolName || "unknown",
|
|
1052
|
+
error: parseErr,
|
|
1053
|
+
toolCallId: call.id,
|
|
1054
|
+
stage: "parse",
|
|
1055
|
+
timestamp: Date.now()
|
|
1056
|
+
});
|
|
1057
|
+
return {
|
|
1058
|
+
tool_call_id: call.id,
|
|
1059
|
+
error: `参数解析失败: ${parseErr.message}`,
|
|
1060
|
+
success: false
|
|
1061
|
+
};
|
|
1062
|
+
}
|
|
361
1063
|
const tool = self._tools.get(toolName);
|
|
362
1064
|
if (!tool) {
|
|
363
|
-
|
|
364
|
-
|
|
1065
|
+
chat.emit("tool-error", {
|
|
1066
|
+
toolName,
|
|
1067
|
+
error: /* @__PURE__ */ new Error(`Tool not registered: ${toolName}`),
|
|
1068
|
+
toolCallId: call.id,
|
|
1069
|
+
stage: "lookup",
|
|
1070
|
+
timestamp: Date.now()
|
|
1071
|
+
});
|
|
1072
|
+
return {
|
|
365
1073
|
tool_call_id: call.id,
|
|
366
1074
|
error: `工具 ${toolName} 未注册`,
|
|
367
1075
|
success: false
|
|
368
|
-
}
|
|
369
|
-
continue;
|
|
1076
|
+
};
|
|
370
1077
|
}
|
|
371
1078
|
try {
|
|
372
|
-
const
|
|
373
|
-
|
|
1079
|
+
const toolTimeout = chat.config.toolTimeout;
|
|
1080
|
+
let execPromise = tool.executor(args);
|
|
1081
|
+
if (toolTimeout && typeof toolTimeout === "number" && toolTimeout > 0) {
|
|
1082
|
+
const timeoutErr = /* @__PURE__ */ new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
|
|
1083
|
+
timeoutErr.name = "ToolTimeoutError";
|
|
1084
|
+
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(timeoutErr), toolTimeout));
|
|
1085
|
+
execPromise = Promise.race([execPromise, timeoutPromise]);
|
|
1086
|
+
}
|
|
1087
|
+
const result = await execPromise;
|
|
1088
|
+
chat.emit("tool-success", {
|
|
1089
|
+
toolName,
|
|
1090
|
+
result,
|
|
1091
|
+
toolCallId: call.id,
|
|
1092
|
+
timestamp: Date.now()
|
|
1093
|
+
});
|
|
1094
|
+
return {
|
|
374
1095
|
tool_call_id: call.id,
|
|
375
1096
|
content: typeof result === "string" ? result : JSON.stringify(result),
|
|
376
1097
|
success: true
|
|
377
|
-
}
|
|
1098
|
+
};
|
|
378
1099
|
} catch (err) {
|
|
379
|
-
|
|
380
|
-
|
|
1100
|
+
const stage = err.name === "ToolTimeoutError" ? "timeout" : "execute";
|
|
1101
|
+
chat.emit("tool-error", {
|
|
1102
|
+
toolName,
|
|
1103
|
+
error: err,
|
|
1104
|
+
toolCallId: call.id,
|
|
1105
|
+
stage,
|
|
1106
|
+
timestamp: Date.now()
|
|
1107
|
+
});
|
|
1108
|
+
return {
|
|
381
1109
|
tool_call_id: call.id,
|
|
382
1110
|
error: err.message,
|
|
383
1111
|
success: false
|
|
384
|
-
}
|
|
1112
|
+
};
|
|
385
1113
|
}
|
|
1114
|
+
}));
|
|
1115
|
+
for (const tr of toolResults) {
|
|
1116
|
+
const content = tr.success ? tr.content : tr.error || "工具执行失败";
|
|
1117
|
+
chat.messages.addTool(content, tr.tool_call_id);
|
|
386
1118
|
}
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
}, (final) => {
|
|
395
|
-
lastResponse = final;
|
|
396
|
-
resolve();
|
|
397
|
-
});
|
|
1119
|
+
if (isStream) await new Promise((resolve) => {
|
|
1120
|
+
chat.sendExistingStream((chunk) => {
|
|
1121
|
+
if (onProgress) onProgress(chunk);
|
|
1122
|
+
lastResponse = chunk;
|
|
1123
|
+
}, (final) => {
|
|
1124
|
+
lastResponse = final;
|
|
1125
|
+
resolve();
|
|
398
1126
|
});
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
const apiResp = await chat._adapter.send(reqBody, chat.config);
|
|
402
|
-
lastResponse = chat._adapter.parseResponse(apiResp);
|
|
403
|
-
}
|
|
1127
|
+
});
|
|
1128
|
+
else lastResponse = await chat.sendExisting();
|
|
404
1129
|
}
|
|
405
1130
|
return lastResponse;
|
|
406
1131
|
}
|
|
407
|
-
|
|
408
|
-
let finalMessage;
|
|
409
|
-
await originalMethod.call(chat, input, (chunk) => {
|
|
410
|
-
if (onProgress) onProgress(chunk);
|
|
411
|
-
}, async (final) => {
|
|
412
|
-
finalMessage = await processResponse(final);
|
|
413
|
-
if (onDone) onDone(finalMessage);
|
|
414
|
-
});
|
|
415
|
-
} else return await processResponse(await originalMethod.call(chat, input));
|
|
1132
|
+
return await processResponse(initialResponse);
|
|
416
1133
|
}
|
|
417
1134
|
};
|
|
418
1135
|
//#endregion
|
|
419
|
-
//#region src/
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
1136
|
+
//#region src/plugins/model-registry.js
|
|
1137
|
+
/**
|
|
1138
|
+
* model-registry 插件
|
|
1139
|
+
*
|
|
1140
|
+
* 职责:
|
|
1141
|
+
* 1. 内置常用模型的能力标签表(model → capabilities 映射)
|
|
1142
|
+
* 2. 安装时自动根据 config.model 查表,写入 config.capabilities
|
|
1143
|
+
* 3. 监听 config-updated 事件,切换模型时自动同步能力
|
|
1144
|
+
* 4. 提供 chat.registerModel(),允许用户追加/覆盖自定义模型
|
|
1145
|
+
*
|
|
1146
|
+
* 能力标签字段(全部可选,缺失视为 false / 未知):
|
|
1147
|
+
* {
|
|
1148
|
+
* reasoning: boolean — 是否返回 reasoning_content(思维链)
|
|
1149
|
+
* vision: boolean — 是否支持图片输入
|
|
1150
|
+
* toolCalling: boolean — 是否支持 function calling
|
|
1151
|
+
* streaming: boolean — 是否支持流式传输
|
|
1152
|
+
* maxInputTokens: number — 最大输入 token 数
|
|
1153
|
+
* maxOutputTokens: number — 最大输出 token 数
|
|
1154
|
+
* }
|
|
1155
|
+
*
|
|
1156
|
+
* 使用:
|
|
1157
|
+
* chat.use(modelRegistryPlugin);
|
|
1158
|
+
* // config.capabilities 现在已自动填充
|
|
1159
|
+
* chat.registerModel('my-custom-model', { toolCalling: true });
|
|
1160
|
+
*/
|
|
1161
|
+
var BUILTIN_MODELS = {
|
|
1162
|
+
"deepseek-chat": {
|
|
1163
|
+
reasoning: false,
|
|
1164
|
+
vision: false,
|
|
1165
|
+
toolCalling: true,
|
|
1166
|
+
streaming: true,
|
|
1167
|
+
maxInputTokens: 128e3,
|
|
1168
|
+
maxOutputTokens: 8192
|
|
1169
|
+
},
|
|
1170
|
+
"deepseek-reasoner": {
|
|
1171
|
+
reasoning: true,
|
|
1172
|
+
vision: false,
|
|
1173
|
+
toolCalling: true,
|
|
1174
|
+
streaming: true,
|
|
1175
|
+
maxInputTokens: 128e3,
|
|
1176
|
+
maxOutputTokens: 8192
|
|
1177
|
+
},
|
|
1178
|
+
"gpt-4o": {
|
|
1179
|
+
reasoning: false,
|
|
1180
|
+
vision: true,
|
|
1181
|
+
toolCalling: true,
|
|
1182
|
+
streaming: true,
|
|
1183
|
+
maxInputTokens: 128e3,
|
|
1184
|
+
maxOutputTokens: 16384
|
|
1185
|
+
},
|
|
1186
|
+
"gpt-4o-mini": {
|
|
1187
|
+
reasoning: false,
|
|
1188
|
+
vision: true,
|
|
1189
|
+
toolCalling: true,
|
|
1190
|
+
streaming: true,
|
|
1191
|
+
maxInputTokens: 128e3,
|
|
1192
|
+
maxOutputTokens: 16384
|
|
1193
|
+
},
|
|
1194
|
+
"gpt-3.5-turbo": {
|
|
1195
|
+
reasoning: false,
|
|
1196
|
+
vision: false,
|
|
1197
|
+
toolCalling: true,
|
|
1198
|
+
streaming: true,
|
|
1199
|
+
maxInputTokens: 16385,
|
|
1200
|
+
maxOutputTokens: 4096
|
|
1201
|
+
},
|
|
1202
|
+
"o1": {
|
|
1203
|
+
reasoning: true,
|
|
1204
|
+
vision: false,
|
|
1205
|
+
toolCalling: false,
|
|
1206
|
+
streaming: false,
|
|
1207
|
+
maxInputTokens: 2e5,
|
|
1208
|
+
maxOutputTokens: 1e5
|
|
1209
|
+
},
|
|
1210
|
+
"o3-mini": {
|
|
1211
|
+
reasoning: true,
|
|
1212
|
+
vision: false,
|
|
1213
|
+
toolCalling: true,
|
|
1214
|
+
streaming: true,
|
|
1215
|
+
maxInputTokens: 2e5,
|
|
1216
|
+
maxOutputTokens: 1e5
|
|
1217
|
+
},
|
|
1218
|
+
"claude-3.5-sonnet": {
|
|
1219
|
+
reasoning: false,
|
|
1220
|
+
vision: true,
|
|
1221
|
+
toolCalling: true,
|
|
1222
|
+
streaming: true,
|
|
1223
|
+
maxInputTokens: 2e5,
|
|
1224
|
+
maxOutputTokens: 8192
|
|
1225
|
+
},
|
|
1226
|
+
"claude-3.5-haiku": {
|
|
1227
|
+
reasoning: false,
|
|
1228
|
+
vision: true,
|
|
1229
|
+
toolCalling: true,
|
|
1230
|
+
streaming: true,
|
|
1231
|
+
maxInputTokens: 2e5,
|
|
1232
|
+
maxOutputTokens: 8192
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
var DEFAULT_CAPABILITIES = {
|
|
1236
|
+
streaming: true,
|
|
1237
|
+
toolCalling: false,
|
|
1238
|
+
reasoning: false,
|
|
1239
|
+
vision: false
|
|
1240
|
+
};
|
|
1241
|
+
var modelRegistryPlugin = {
|
|
1242
|
+
name: "model-registry",
|
|
1243
|
+
install(chatService) {
|
|
1244
|
+
this.chat = chatService;
|
|
1245
|
+
this._registry = new Map(Object.entries(BUILTIN_MODELS));
|
|
1246
|
+
/**
|
|
1247
|
+
* 注册/覆盖一个模型的能力标签
|
|
1248
|
+
* @param {string} name — 模型名称
|
|
1249
|
+
* @param {Object} capabilities — 能力标签对象(部分字段即可,未提供的取默认值)
|
|
1250
|
+
* @returns {ChatService}
|
|
1251
|
+
*/
|
|
1252
|
+
chatService.registerModel = (name, capabilities = {}) => {
|
|
1253
|
+
if (!name || typeof name !== "string" || !name.trim()) throw new Error("[model-registry] 模型名称必须是非空字符串");
|
|
1254
|
+
const merged = {
|
|
1255
|
+
...DEFAULT_CAPABILITIES,
|
|
1256
|
+
...capabilities
|
|
1257
|
+
};
|
|
1258
|
+
this._registry.set(name.trim(), merged);
|
|
1259
|
+
if (chatService.config.model === name.trim()) this._syncCapabilities();
|
|
1260
|
+
return chatService;
|
|
1261
|
+
};
|
|
1262
|
+
/**
|
|
1263
|
+
* 列出所有已注册的模型名称
|
|
1264
|
+
* @returns {Array<string>}
|
|
1265
|
+
*/
|
|
1266
|
+
chatService.listModels = () => {
|
|
1267
|
+
return [...this._registry.keys()];
|
|
1268
|
+
};
|
|
1269
|
+
this._syncCapabilities();
|
|
1270
|
+
chatService.on("config-updated", ({ changes }) => {
|
|
1271
|
+
if ("model" in changes) this._syncCapabilities();
|
|
1272
|
+
if ("capabilities" in changes && !("model" in changes)) {
|
|
1273
|
+
const current = this._lookupCapabilities();
|
|
1274
|
+
if (current) chatService.config.capabilities = {
|
|
1275
|
+
...current,
|
|
1276
|
+
...changes.capabilities
|
|
1277
|
+
};
|
|
1278
|
+
}
|
|
1279
|
+
});
|
|
1280
|
+
},
|
|
1281
|
+
_lookupCapabilities() {
|
|
1282
|
+
const model = this.chat.config.model;
|
|
1283
|
+
if (!model) return null;
|
|
1284
|
+
return this._registry.get(model) || null;
|
|
1285
|
+
},
|
|
1286
|
+
_syncCapabilities() {
|
|
1287
|
+
const caps = this._lookupCapabilities();
|
|
1288
|
+
if (caps) this.chat.config.capabilities = { ...caps };
|
|
1289
|
+
}
|
|
426
1290
|
};
|
|
427
1291
|
//#endregion
|
|
428
|
-
export { ChatService, EventEmitter, MessageStore,
|
|
1292
|
+
export { APIError, ChatService, ConfigurationError, EventEmitter, MessageFormatter, MessageStore, NetworkError, ParsingError, SystemPromptStore, assembleMessages, modelRegistryPlugin, openaiAdapter, toolCallingPlugin };
|
|
429
1293
|
|
|
430
1294
|
//# sourceMappingURL=my-ai-chat-framework.browser.es.js.map
|