my-ai-chat-framework 2.7.0 → 3.0.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/CHANGELOG.md +65 -0
- package/LICENSE +20 -20
- package/README.md +100 -13
- package/README_ZH.md +375 -0
- package/dist/my-ai-chat-framework.browser.es.js +758 -248
- package/dist/my-ai-chat-framework.browser.es.js.map +1 -1
- package/dist/my-ai-chat-framework.browser.umd.js +762 -247
- package/dist/my-ai-chat-framework.browser.umd.js.map +1 -1
- package/dist/my-ai-chat-framework.node.cjs.js +762 -247
- package/dist/my-ai-chat-framework.node.cjs.js.map +1 -1
- package/docs/DEVELOPER.md +479 -0
- package/package.json +31 -8
- package/src/adapters/openai.js +82 -7
- package/src/core/ChatService.js +415 -61
- package/src/core/Errors.js +59 -59
- package/src/core/MessageStore.js +27 -0
- package/src/core/Pipeline.js +48 -0
- package/src/core/SystemPromptStore.js +118 -118
- package/src/index.js +6 -4
- package/src/plugins/model-registry.js +223 -187
- package/src/plugins/tool-calling.js +215 -185
- package/src/utils/MessageFormatter.js +204 -204
- package/src/utils/typeCheck.js +11 -11
- package/src/utils/url.js +17 -17
|
@@ -143,6 +143,25 @@
|
|
|
143
143
|
return [];
|
|
144
144
|
}
|
|
145
145
|
/**
|
|
146
|
+
* 撤回到指定消息 id 的上一个用户消息,删除两者之间的所有消息
|
|
147
|
+
* 适用于重发
|
|
148
|
+
* @param {string} id — 目标消息 id
|
|
149
|
+
* @returns {Array} 被删除的消息列表
|
|
150
|
+
*/
|
|
151
|
+
undoToPreviousUser(id) {
|
|
152
|
+
let targetIndex = -1;
|
|
153
|
+
let previousUserIndex = -1;
|
|
154
|
+
for (let i = this._messages.length - 1; i >= 0; i--) {
|
|
155
|
+
if (this._messages[i].id === id) targetIndex = i;
|
|
156
|
+
if (targetIndex >= 0 && this._messages[i].role === "user") {
|
|
157
|
+
previousUserIndex = i;
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (targetIndex >= 0 && previousUserIndex >= 0) return this._messages.splice(previousUserIndex + 1, targetIndex - previousUserIndex);
|
|
162
|
+
return [];
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
146
165
|
* 更新消息:按 id 查找并合并 changes,不新增消息
|
|
147
166
|
* @param {string} id — 消息 id
|
|
148
167
|
* @param {Object} changes — 要合并的字段
|
|
@@ -312,7 +331,85 @@
|
|
|
312
331
|
}
|
|
313
332
|
};
|
|
314
333
|
//#endregion
|
|
334
|
+
//#region src/core/Pipeline.js
|
|
335
|
+
/**
|
|
336
|
+
* Pipeline —— 极简顺序管道(v3.0 提案 · 阶段 1)
|
|
337
|
+
*
|
|
338
|
+
* 三个概念(对照 pipeline-demo.html):
|
|
339
|
+
* - 小车 ctx —— 本次请求的全部"状态",车间之间只通过它交接
|
|
340
|
+
* - 车间 stage —— { name, run(ctx) },只干一件事,不认别的车间
|
|
341
|
+
* - 调度 run() —— for + await,顺序执行(线性,无"回程";洋葱能力留给阶段 2 的 after 车间)
|
|
342
|
+
*/
|
|
343
|
+
var Pipeline = class {
|
|
344
|
+
constructor() {
|
|
345
|
+
this._stages = [];
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* 注册一个车间(追加到末尾)。
|
|
349
|
+
* @param {{name: string, run: (ctx: object) => void | Promise<void>}} stage
|
|
350
|
+
* @returns {Pipeline} this,支持链式
|
|
351
|
+
*/
|
|
352
|
+
register(stage) {
|
|
353
|
+
if (!stage || typeof stage.run !== "function") throw new TypeError("Pipeline.register: stage 需要 { name, run(ctx) },运行 run 必须是函数");
|
|
354
|
+
this._stages.push(stage);
|
|
355
|
+
return this;
|
|
356
|
+
}
|
|
357
|
+
/** 按名字移除车间(移除不存在的名字是安全的) */
|
|
358
|
+
unregister(name) {
|
|
359
|
+
this._stages = this._stages.filter((s) => s.name !== name);
|
|
360
|
+
return this;
|
|
361
|
+
}
|
|
362
|
+
/** 列出当前车间名(调试用) */
|
|
363
|
+
names() {
|
|
364
|
+
return this._stages.map((s) => s.name);
|
|
365
|
+
}
|
|
366
|
+
/** 把小车开过所有车间;返回 ctx(车间可改 ctx 上的字段) */
|
|
367
|
+
async run(ctx) {
|
|
368
|
+
for (const stage of this._stages) await stage.run(ctx);
|
|
369
|
+
return ctx;
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
//#endregion
|
|
315
373
|
//#region src/core/ChatService.js
|
|
374
|
+
/**
|
|
375
|
+
* @typedef {Object} ChatAdapter 适配器协议(v3.0:写同级适配器只需实现这 4+1 个方法)
|
|
376
|
+
* @property {Function} buildRequest (messages, config, systemPrompts) => requestBody
|
|
377
|
+
* @property {Function} send (body, config, opts) => Promise<apiResponse>
|
|
378
|
+
* @property {Function} stream (body, config, onProgress, onDone, opts) => Promise<void>
|
|
379
|
+
* @property {Function} parseResponse (apiResponse) => assistantMessage
|
|
380
|
+
* @property {Function} [getRequestDefaults] () => 默认请求参数(可选)
|
|
381
|
+
* @property {Function} [install] (chatService, options) 插件式安装(可选)
|
|
382
|
+
*/
|
|
383
|
+
/**
|
|
384
|
+
* @typedef {Object} PipelineContext 管道小车 ctx(public pipe 车间可见/可改的全部字段)
|
|
385
|
+
* @property {Object} options 原始请求选项
|
|
386
|
+
* @property {*} userInput 用户输入(可为 undefined)
|
|
387
|
+
* @property {boolean} addUser 是否已新增/将新增用户消息
|
|
388
|
+
* @property {MessageStore} messages 消息列表(可读可改:push / unshift / update)
|
|
389
|
+
* @property {SystemPromptStore} systemPrompts 系统提示词(可读可改)
|
|
390
|
+
* @property {Object} config 合并后的请求级配置(prepareInput 后生效)
|
|
391
|
+
* @property {boolean} isStream 本次是否流式
|
|
392
|
+
* @property {Function|null} onProgress 流式进度回调
|
|
393
|
+
* @property {Function|null} onDone 流式完成回调
|
|
394
|
+
* @property {string|null} mergeToEntry 续写目标 id(null = 普通发送)
|
|
395
|
+
* @property {*} body 请求体(buildRequest 后产出)
|
|
396
|
+
* @property {*} result 最终结果(send 后产出)
|
|
397
|
+
*/
|
|
398
|
+
/**
|
|
399
|
+
* @typedef {Object} PipeStage 车间(v3.0 公开扩展单元)
|
|
400
|
+
* @property {string} name 车间名(唯一,不能与内部车间重名)
|
|
401
|
+
* @property {string} [phase] 'beforeSend'(默认)| 'afterSend'
|
|
402
|
+
* @property {Function} run (ctx: PipelineContext) => void | Promise<void>
|
|
403
|
+
*/
|
|
404
|
+
var SESSION_CONFIG_KEYS = [
|
|
405
|
+
"model",
|
|
406
|
+
"temperature",
|
|
407
|
+
"maxTokens",
|
|
408
|
+
"modelParams",
|
|
409
|
+
"system",
|
|
410
|
+
"retry",
|
|
411
|
+
"ephemeralContinue"
|
|
412
|
+
];
|
|
316
413
|
var ChatService = class extends EventEmitter {
|
|
317
414
|
constructor(config = {}) {
|
|
318
415
|
super();
|
|
@@ -326,17 +423,106 @@
|
|
|
326
423
|
this._processResponse = null;
|
|
327
424
|
const model = this.config.model || this.config.modelParams?.model;
|
|
328
425
|
if (!model || typeof model !== "string" || !model.trim()) throw new ConfigurationError("缺少 model 配置");
|
|
329
|
-
|
|
426
|
+
this._assertValidConfig(this.config);
|
|
427
|
+
if (typeof config.system === "string" && config.system.trim()) this.systemPrompts.set(config.system);
|
|
428
|
+
if (config.adapter) this.setAdapter(config.adapter);
|
|
429
|
+
this._userStages = [];
|
|
430
|
+
this._pipeline = this._buildPipeline();
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* 校验配置中的可校验字段(model 必填由构造器负责,这里只校验存在性)
|
|
434
|
+
* @throws {ConfigurationError}
|
|
435
|
+
*/
|
|
436
|
+
_assertValidConfig(cfg) {
|
|
437
|
+
const temperature = cfg.modelParams?.temperature ?? cfg.temperature;
|
|
330
438
|
if (temperature !== void 0 && (typeof temperature !== "number" || temperature < 0 || temperature > 2)) throw new ConfigurationError(`temperature 必须在 0-2 之间,当前值: ${temperature}`);
|
|
331
|
-
const maxTokens =
|
|
439
|
+
const maxTokens = cfg.modelParams?.maxTokens ?? cfg.maxTokens;
|
|
332
440
|
if (maxTokens !== void 0 && (typeof maxTokens !== "number" || maxTokens < 1 || !Number.isInteger(maxTokens))) throw new ConfigurationError(`maxTokens 必须为正整数,当前值: ${maxTokens}`);
|
|
333
|
-
|
|
441
|
+
const model = cfg.model ?? cfg.modelParams?.model;
|
|
442
|
+
if (model !== void 0 && (typeof model !== "string" || !model.trim())) throw new ConfigurationError("model 必须是非空字符串");
|
|
443
|
+
}
|
|
444
|
+
use(plugin, options = {}) {
|
|
445
|
+
plugin.install(this, options);
|
|
446
|
+
return this;
|
|
334
447
|
}
|
|
335
|
-
|
|
336
|
-
|
|
448
|
+
/**
|
|
449
|
+
* 往请求管道里挂一个"车间"。
|
|
450
|
+
* - phase 'beforeSend'(默认):在内部 beforeRequest 钩子之后、构建请求体之前执行
|
|
451
|
+
* - phase 'afterSend' :在内部发送(流式/非流式)完成、结果落位之后执行(可改 ctx.result)
|
|
452
|
+
* 不注册任何车间 = 行为与版本 2.8.x 完全一致。
|
|
453
|
+
* @param {PipeStage} stage
|
|
454
|
+
* @returns {ChatService} this
|
|
455
|
+
* @throws {ConfigurationError} 参数非法 / 名字被占用 / 与内部车间重名
|
|
456
|
+
*/
|
|
457
|
+
pipe(stage) {
|
|
458
|
+
if (!stage || typeof stage !== "object" || typeof stage.run !== "function") throw new ConfigurationError("pipe: 需要 { name, phase?, run(ctx) },run 必须是函数");
|
|
459
|
+
if (typeof stage.name !== "string" || !stage.name.trim()) throw new ConfigurationError("pipe: 需要 name(车间名,非空字符串)");
|
|
460
|
+
if ([
|
|
461
|
+
"prepareInput",
|
|
462
|
+
"beforeSend",
|
|
463
|
+
"autoContinue",
|
|
464
|
+
"buildRequest",
|
|
465
|
+
"send"
|
|
466
|
+
].includes(stage.name)) throw new ConfigurationError(`pipe: "${stage.name}" 是内部车间名,请换一个名字`);
|
|
467
|
+
if (this._userStages.some((s) => s.name === stage.name)) throw new ConfigurationError(`pipe: 车间 "${stage.name}" 已存在,请先 chat.unpipe("${stage.name}")`);
|
|
468
|
+
const phase = stage.phase === "afterSend" ? "afterSend" : "beforeSend";
|
|
469
|
+
this._userStages.push({
|
|
470
|
+
name: stage.name,
|
|
471
|
+
phase,
|
|
472
|
+
run: stage.run
|
|
473
|
+
});
|
|
474
|
+
this._rebuildPipeline();
|
|
337
475
|
return this;
|
|
338
476
|
}
|
|
477
|
+
/** 移除一个用户车间(移除不存在的名字是安全的)。@returns {ChatService} this */
|
|
478
|
+
unpipe(name) {
|
|
479
|
+
const before = this._userStages.length;
|
|
480
|
+
this._userStages = this._userStages.filter((s) => s.name !== name);
|
|
481
|
+
if (this._userStages.length !== before) this._rebuildPipeline();
|
|
482
|
+
return this;
|
|
483
|
+
}
|
|
484
|
+
/** 查看当前管道里所有车间名(调试/说明用,含内部车间) */
|
|
485
|
+
get pipelineStages() {
|
|
486
|
+
return this._pipeline.names();
|
|
487
|
+
}
|
|
488
|
+
/** 重建内部管道:内部 5 车间 + 用户车间按 phase 插入 */
|
|
489
|
+
_buildPipeline() {
|
|
490
|
+
const p = new Pipeline();
|
|
491
|
+
p.register({
|
|
492
|
+
name: "prepareInput",
|
|
493
|
+
run: (ctx) => this._stagePrepareInput(ctx)
|
|
494
|
+
});
|
|
495
|
+
p.register({
|
|
496
|
+
name: "beforeSend",
|
|
497
|
+
run: (ctx) => this._stageBeforeSend(ctx)
|
|
498
|
+
});
|
|
499
|
+
for (const s of this._userStages) if (s.phase === "beforeSend") p.register({
|
|
500
|
+
name: s.name,
|
|
501
|
+
run: (ctx) => s.run(ctx)
|
|
502
|
+
});
|
|
503
|
+
p.register({
|
|
504
|
+
name: "autoContinue",
|
|
505
|
+
run: (ctx) => this._stageAutoContinue(ctx)
|
|
506
|
+
});
|
|
507
|
+
p.register({
|
|
508
|
+
name: "buildRequest",
|
|
509
|
+
run: (ctx) => this._stageBuildRequest(ctx)
|
|
510
|
+
});
|
|
511
|
+
p.register({
|
|
512
|
+
name: "send",
|
|
513
|
+
run: (ctx) => this._stageSend(ctx)
|
|
514
|
+
});
|
|
515
|
+
for (const s of this._userStages) if (s.phase === "afterSend") p.register({
|
|
516
|
+
name: s.name,
|
|
517
|
+
run: (ctx) => s.run(ctx)
|
|
518
|
+
});
|
|
519
|
+
return p;
|
|
520
|
+
}
|
|
521
|
+
_rebuildPipeline() {
|
|
522
|
+
this._pipeline = this._buildPipeline();
|
|
523
|
+
}
|
|
339
524
|
setAdapter(adapter) {
|
|
525
|
+
assertAdapter(adapter);
|
|
340
526
|
this._adapter = adapter;
|
|
341
527
|
}
|
|
342
528
|
abort() {
|
|
@@ -357,17 +543,24 @@
|
|
|
357
543
|
this.messages.update(target.id, {
|
|
358
544
|
_complete: true,
|
|
359
545
|
prefix: void 0,
|
|
360
|
-
_ephemeral:
|
|
546
|
+
_ephemeral: false
|
|
361
547
|
});
|
|
362
548
|
return target;
|
|
363
549
|
} catch (err) {
|
|
364
|
-
this.messages.update(target.id, {
|
|
550
|
+
this.messages.update(target.id, {
|
|
551
|
+
_complete: true,
|
|
552
|
+
prefix: void 0,
|
|
553
|
+
_ephemeral: false
|
|
554
|
+
});
|
|
555
|
+
if (err.name === "AbortError") {
|
|
556
|
+
this.emit("aborted", { timestamp: Date.now() });
|
|
557
|
+
return target;
|
|
558
|
+
}
|
|
365
559
|
throw err;
|
|
366
560
|
}
|
|
367
561
|
}
|
|
368
562
|
async continueLastStream(onProgress, onDone) {
|
|
369
563
|
const target = this._prepareContinue();
|
|
370
|
-
console.log("[DEBUG] continueLastStream target.id:", target.id);
|
|
371
564
|
this.messages.update(target.id, { prefix: true });
|
|
372
565
|
const baseLen = (target.content || "").length;
|
|
373
566
|
try {
|
|
@@ -388,11 +581,19 @@
|
|
|
388
581
|
this.messages.update(target.id, {
|
|
389
582
|
_complete: true,
|
|
390
583
|
prefix: void 0,
|
|
391
|
-
_ephemeral:
|
|
584
|
+
_ephemeral: false
|
|
392
585
|
});
|
|
393
586
|
return target;
|
|
394
587
|
} catch (err) {
|
|
395
|
-
this.messages.update(target.id, {
|
|
588
|
+
this.messages.update(target.id, {
|
|
589
|
+
_complete: true,
|
|
590
|
+
prefix: void 0,
|
|
591
|
+
_ephemeral: false
|
|
592
|
+
});
|
|
593
|
+
if (err.name === "AbortError") {
|
|
594
|
+
this.emit("aborted", { timestamp: Date.now() });
|
|
595
|
+
return target;
|
|
596
|
+
}
|
|
396
597
|
throw err;
|
|
397
598
|
}
|
|
398
599
|
}
|
|
@@ -402,7 +603,20 @@
|
|
|
402
603
|
if (last && (last.role === "assistant" || last._ephemeral)) return last;
|
|
403
604
|
throw new Error("最后一条消息不是 assistant,无法续写");
|
|
404
605
|
}
|
|
606
|
+
/**
|
|
607
|
+
* 运行时修改配置(仅会话层字段)。
|
|
608
|
+
*
|
|
609
|
+
* 白名单:model / temperature / maxTokens / modelParams / system / retry / ephemeralContinue。
|
|
610
|
+
* - 运输层(apiKey/baseUrl/headers):归适配器,要改就换适配器实例
|
|
611
|
+
* - 请求参数默认值:走适配器工厂 options 或请求级覆盖(chat.send(x, params))
|
|
612
|
+
* - 能力表:归 modelRegistry 插件
|
|
613
|
+
*
|
|
614
|
+
* 与构造器一样经过校验,不能注入非法值。
|
|
615
|
+
* @throws {ConfigurationError} 非白名单字段或非法值
|
|
616
|
+
*/
|
|
405
617
|
updateConfig(partial) {
|
|
618
|
+
for (const key of Object.keys(partial)) if (!SESSION_CONFIG_KEYS.includes(key)) throw new ConfigurationError(`updateConfig 不支持修改 "${key}"。允许的会话层字段: ${SESSION_CONFIG_KEYS.join(", ")}`);
|
|
619
|
+
this._assertValidConfig(partial);
|
|
406
620
|
Object.assign(this.config, partial);
|
|
407
621
|
if (typeof partial.system === "string") this.systemPrompts.set(partial.system);
|
|
408
622
|
this.emit("config-updated", {
|
|
@@ -410,36 +624,72 @@
|
|
|
410
624
|
timestamp: Date.now()
|
|
411
625
|
});
|
|
412
626
|
}
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
627
|
+
/**
|
|
628
|
+
* 合并请求参数(近者优先):
|
|
629
|
+
* 适配器默认(getRequestDefaults) ← 会话配置(this.config) ← 本次覆盖(params)
|
|
630
|
+
* modelParams 深层合并;平铺便捷键(temperature/maxTokens/reasoningEffort)自动折叠进 modelParams
|
|
631
|
+
*/
|
|
632
|
+
_mergeRequestConfig(params = {}) {
|
|
633
|
+
const adapterDefaults = this._adapter?.getRequestDefaults?.() || {};
|
|
634
|
+
const requestConfig = {
|
|
635
|
+
...adapterDefaults,
|
|
636
|
+
...this.config,
|
|
637
|
+
...params
|
|
638
|
+
};
|
|
639
|
+
const modelParams = {
|
|
640
|
+
...adapterDefaults.modelParams || {},
|
|
641
|
+
...this.config.modelParams || {},
|
|
642
|
+
...params.modelParams || {}
|
|
643
|
+
};
|
|
644
|
+
for (const key of [
|
|
645
|
+
"temperature",
|
|
646
|
+
"maxTokens",
|
|
647
|
+
"reasoningEffort"
|
|
648
|
+
]) {
|
|
649
|
+
const value = params[key] ?? this.config[key] ?? adapterDefaults[key];
|
|
650
|
+
if (value !== void 0) modelParams[key] = value;
|
|
430
651
|
}
|
|
431
|
-
|
|
432
|
-
|
|
652
|
+
requestConfig.modelParams = modelParams;
|
|
653
|
+
return requestConfig;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* 内部调度(v3.0 提案 · 阶段 1):造一辆小车 ctx,开过内部管道,返回结果。
|
|
657
|
+
* 行为与旧版 _request 完全一致,只是把固定线拆成了车间(见 _stage* 方法)。
|
|
658
|
+
*
|
|
659
|
+
* ctx 字段(车间可见):
|
|
660
|
+
* options —— 原始请求选项
|
|
661
|
+
* userInput —— 用户输入
|
|
662
|
+
* addUser —— 是否新增用户消息
|
|
663
|
+
* messages —— MessageStore(可读可改)
|
|
664
|
+
* systemPrompts —— SystemPromptStore
|
|
665
|
+
* config —— 合并后的请求级配置(prepareInput 车间产出)
|
|
666
|
+
* isStream —— 本次是否流式
|
|
667
|
+
* onProgress —— 流式进度回调(可为 null)
|
|
668
|
+
* onDone —— 流式完成回调(可为 null)
|
|
669
|
+
* mergeToEntry —— 续写目标 id(空 = 普通发送)
|
|
670
|
+
* body —— adapter 构建出的请求体(buildRequest 车间产出)
|
|
671
|
+
* result —— 最终结果(send 车间产出)
|
|
672
|
+
*/
|
|
673
|
+
async _request(options = {}) {
|
|
674
|
+
const ctx = {
|
|
675
|
+
options,
|
|
676
|
+
userInput: options.userInput,
|
|
677
|
+
addUser: options.addUser !== false,
|
|
678
|
+
messages: this.messages,
|
|
679
|
+
systemPrompts: this.systemPrompts,
|
|
680
|
+
config: null,
|
|
681
|
+
isStream: !!options.isStream,
|
|
682
|
+
onProgress: options.onProgress || null,
|
|
683
|
+
onDone: options.onDone || null,
|
|
684
|
+
mergeToEntry: options.mergeToEntry || null,
|
|
685
|
+
body: null,
|
|
686
|
+
result: null
|
|
687
|
+
};
|
|
433
688
|
try {
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
onProgress,
|
|
437
|
-
onDone,
|
|
438
|
-
mergeToEntry,
|
|
439
|
-
maxRetries: retryCfg.maxRetries ?? 0,
|
|
440
|
-
retryDelay: retryCfg.retryDelay ?? 1e3
|
|
441
|
-
});
|
|
689
|
+
await this._pipeline.run(ctx);
|
|
690
|
+
return ctx.result;
|
|
442
691
|
} catch (error) {
|
|
692
|
+
if (error.name === "AbortError") throw error;
|
|
443
693
|
this.emit("error", {
|
|
444
694
|
error,
|
|
445
695
|
timestamp: Date.now()
|
|
@@ -447,6 +697,49 @@
|
|
|
447
697
|
throw error;
|
|
448
698
|
}
|
|
449
699
|
}
|
|
700
|
+
/** 车间 1:加用户消息 → 合并请求参数 → 广播 sending */
|
|
701
|
+
async _stagePrepareInput(ctx) {
|
|
702
|
+
this._addUserMessage(ctx.userInput, ctx.addUser);
|
|
703
|
+
ctx.config = this._mergeRequestConfig(ctx.options.params);
|
|
704
|
+
this.emit("sending", {
|
|
705
|
+
addUser: ctx.addUser,
|
|
706
|
+
userInput: ctx.userInput,
|
|
707
|
+
timestamp: Date.now()
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
/** 车间 2:发送前钩子(兼容桥:事件钩子照发;阶段 4 会迁到 beforeSend 公开位置) */
|
|
711
|
+
async _stageBeforeSend(ctx) {
|
|
712
|
+
await this._hooks.emitAsync("beforeRequest", {
|
|
713
|
+
messages: ctx.messages,
|
|
714
|
+
config: ctx.config,
|
|
715
|
+
options: ctx.options
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
/** 车间 3:自动续写检测(ephemeralContinue 时,底部若有 prefix 消息则续写) */
|
|
719
|
+
async _stageAutoContinue(ctx) {
|
|
720
|
+
if (this.config.ephemeralContinue && !ctx.mergeToEntry) {
|
|
721
|
+
const msgs = ctx.messages.getAll();
|
|
722
|
+
const last = msgs[msgs.length - 1];
|
|
723
|
+
if (last && last.prefix && (last.role === "assistant" || last._ephemeral)) ctx.mergeToEntry = last.id;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
/** 车间 4:构建请求体 */
|
|
727
|
+
async _stageBuildRequest(ctx) {
|
|
728
|
+
ctx.body = this._adapter.buildRequest(ctx.messages.getAll(), ctx.config, ctx.systemPrompts.getEnabled());
|
|
729
|
+
}
|
|
730
|
+
/** 车间 5:发送(流式/非流式 + 重试 + 占位消息 + _processResponse 工具钩子) */
|
|
731
|
+
async _stageSend(ctx) {
|
|
732
|
+
const retryCfg = this.config.retry || {};
|
|
733
|
+
ctx.result = await this._withRetry(ctx.body, {
|
|
734
|
+
isStream: ctx.isStream,
|
|
735
|
+
onProgress: ctx.onProgress,
|
|
736
|
+
onDone: ctx.onDone,
|
|
737
|
+
mergeToEntry: ctx.mergeToEntry,
|
|
738
|
+
config: ctx.config,
|
|
739
|
+
maxRetries: retryCfg.maxRetries ?? 0,
|
|
740
|
+
retryDelay: retryCfg.retryDelay ?? 1e3
|
|
741
|
+
});
|
|
742
|
+
}
|
|
450
743
|
_addUserMessage(userInput, addUser) {
|
|
451
744
|
if (addUser && userInput !== void 0) {
|
|
452
745
|
const msg = typeof userInput === "string" ? {
|
|
@@ -460,7 +753,7 @@
|
|
|
460
753
|
}
|
|
461
754
|
}
|
|
462
755
|
/** retry 循环,占位消息只 push 一次 */
|
|
463
|
-
async _withRetry(body, { isStream, onProgress, onDone, mergeToEntry, maxRetries, retryDelay }) {
|
|
756
|
+
async _withRetry(body, { isStream, onProgress, onDone, mergeToEntry, config, maxRetries, retryDelay }) {
|
|
464
757
|
let lastError = null;
|
|
465
758
|
const adapterOptions = { signal: this._abortController?.signal };
|
|
466
759
|
let placeholder = null;
|
|
@@ -496,10 +789,11 @@
|
|
|
496
789
|
base,
|
|
497
790
|
mergeToEntry,
|
|
498
791
|
onProgress,
|
|
499
|
-
onDone
|
|
792
|
+
onDone,
|
|
793
|
+
config
|
|
500
794
|
});
|
|
501
795
|
else {
|
|
502
|
-
const resp = await this._adapter.send(body,
|
|
796
|
+
const resp = await this._adapter.send(body, config, adapterOptions);
|
|
503
797
|
let result = this._handleResult(this._adapter.parseResponse(resp), mergeToEntry);
|
|
504
798
|
if (this._processResponse && !mergeToEntry) result = await this._processResponse(result, { isStream: false });
|
|
505
799
|
return result;
|
|
@@ -518,12 +812,21 @@
|
|
|
518
812
|
this._isGenerating = false;
|
|
519
813
|
throw lastError;
|
|
520
814
|
}
|
|
521
|
-
/**
|
|
522
|
-
|
|
815
|
+
/**
|
|
816
|
+
* 流式处理:ChatService 维护占位消息,adapter 只负责解析 SSE
|
|
817
|
+
*
|
|
818
|
+
* 参数说明:
|
|
819
|
+
* - placeholder:流式期间实时更新的目标消息(续写时 = target 本身,普通发送时 = 新建的空消息)
|
|
820
|
+
* - base:续写时保存的旧内容快照,用于和 API 新内容拼接
|
|
821
|
+
* - mergeToEntry:续写目标的 id,有值时走续写逻辑
|
|
822
|
+
* - onProgress:外部回调,每收到一个 chunk 触发
|
|
823
|
+
* - onDone:流结束回调
|
|
824
|
+
*/
|
|
825
|
+
async _stream(body, adapterOptions, { placeholder, base, mergeToEntry, onProgress, onDone, config }) {
|
|
523
826
|
let finalMsg = null;
|
|
524
|
-
await this._adapter.stream(body,
|
|
525
|
-
placeholder.content = snap.content || "";
|
|
526
|
-
if (snap.reasoningContent) placeholder.reasoningContent = snap.reasoningContent;
|
|
827
|
+
await this._adapter.stream(body, config, (snap) => {
|
|
828
|
+
placeholder.content = mergeToEntry && base ? base.content + (snap.content || "") : snap.content || "";
|
|
829
|
+
if (snap.reasoningContent) placeholder.reasoningContent = mergeToEntry && base ? base.reasoning + snap.reasoningContent : snap.reasoningContent;
|
|
527
830
|
if (snap.toolCalls) placeholder.toolCalls = [...snap.toolCalls];
|
|
528
831
|
this.emit("stream-progress", snap);
|
|
529
832
|
if (onProgress) onProgress(snap);
|
|
@@ -537,7 +840,9 @@
|
|
|
537
840
|
if (mergeToEntry && base) {
|
|
538
841
|
const changes = {
|
|
539
842
|
content: base.content + (final.content || ""),
|
|
540
|
-
_complete: true
|
|
843
|
+
_complete: true,
|
|
844
|
+
_ephemeral: false,
|
|
845
|
+
prefix: void 0
|
|
541
846
|
};
|
|
542
847
|
if (final.reasoningContent) changes.reasoningContent = base.reasoning + final.reasoningContent;
|
|
543
848
|
if (final.toolCalls) changes.toolCalls = final.toolCalls;
|
|
@@ -564,7 +869,9 @@
|
|
|
564
869
|
}
|
|
565
870
|
const changes = {
|
|
566
871
|
content: (entry.content || "") + (assistantMsg.content || ""),
|
|
567
|
-
_complete: true
|
|
872
|
+
_complete: true,
|
|
873
|
+
_ephemeral: false,
|
|
874
|
+
prefix: void 0
|
|
568
875
|
};
|
|
569
876
|
if (assistantMsg.reasoningContent) changes.reasoningContent = (entry.reasoningContent || "") + assistantMsg.reasoningContent;
|
|
570
877
|
if (assistantMsg.toolCalls) changes.toolCalls = assistantMsg.toolCalls;
|
|
@@ -577,20 +884,44 @@
|
|
|
577
884
|
this.emit("message", assistantMsg);
|
|
578
885
|
return assistantMsg;
|
|
579
886
|
}
|
|
580
|
-
|
|
887
|
+
/**
|
|
888
|
+
* 发送消息。
|
|
889
|
+
* @param {string|Object} userInput - 用户输入
|
|
890
|
+
* @param {Object} [params] - 请求级参数覆盖(model/temperature/modelParams 等,仅本次生效)
|
|
891
|
+
*/
|
|
892
|
+
async send(userInput, params) {
|
|
581
893
|
this._abortController = new AbortController();
|
|
582
894
|
try {
|
|
583
895
|
return await this._request({
|
|
584
896
|
userInput,
|
|
585
897
|
addUser: true,
|
|
586
|
-
isStream: false
|
|
898
|
+
isStream: false,
|
|
899
|
+
params
|
|
587
900
|
});
|
|
901
|
+
} catch (err) {
|
|
902
|
+
if (err.name === "AbortError") {
|
|
903
|
+
this.emit("aborted", { timestamp: Date.now() });
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
throw err;
|
|
588
907
|
} finally {
|
|
589
908
|
this._abortController = null;
|
|
590
909
|
this._isGenerating = false;
|
|
591
910
|
}
|
|
592
911
|
}
|
|
593
|
-
|
|
912
|
+
/**
|
|
913
|
+
* 流式发送。
|
|
914
|
+
* @param {string|Object} userInput - 用户输入
|
|
915
|
+
* @param {Object} [params] - 请求级参数覆盖(仅本次生效)
|
|
916
|
+
* @param {Function} [onProgress] - 流式进度回调
|
|
917
|
+
* @param {Function} [onDone] - 流式完成回调
|
|
918
|
+
*/
|
|
919
|
+
async stream(userInput, params, onProgress, onDone) {
|
|
920
|
+
if (typeof params === "function") {
|
|
921
|
+
onDone = onProgress;
|
|
922
|
+
onProgress = params;
|
|
923
|
+
params = void 0;
|
|
924
|
+
}
|
|
594
925
|
this._abortController = new AbortController();
|
|
595
926
|
try {
|
|
596
927
|
return await this._request({
|
|
@@ -598,40 +929,92 @@
|
|
|
598
929
|
addUser: true,
|
|
599
930
|
isStream: true,
|
|
600
931
|
onProgress,
|
|
601
|
-
onDone
|
|
932
|
+
onDone,
|
|
933
|
+
params
|
|
602
934
|
});
|
|
935
|
+
} catch (err) {
|
|
936
|
+
if (err.name === "AbortError") {
|
|
937
|
+
this.emit("aborted", { timestamp: Date.now() });
|
|
938
|
+
return;
|
|
939
|
+
}
|
|
940
|
+
throw err;
|
|
603
941
|
} finally {
|
|
604
942
|
this._abortController = null;
|
|
605
943
|
this._isGenerating = false;
|
|
606
944
|
}
|
|
607
945
|
}
|
|
608
|
-
|
|
946
|
+
/**
|
|
947
|
+
* 重发当前消息(不加用户消息)。
|
|
948
|
+
* @param {Object} [params] - 请求级参数覆盖(仅本次生效)
|
|
949
|
+
*/
|
|
950
|
+
async sendExisting(params) {
|
|
609
951
|
this._abortController = new AbortController();
|
|
610
952
|
try {
|
|
611
953
|
return await this._request({
|
|
612
954
|
addUser: false,
|
|
613
|
-
isStream: false
|
|
955
|
+
isStream: false,
|
|
956
|
+
params
|
|
614
957
|
});
|
|
958
|
+
} catch (err) {
|
|
959
|
+
if (err.name === "AbortError") {
|
|
960
|
+
this.emit("aborted", { timestamp: Date.now() });
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
throw err;
|
|
615
964
|
} finally {
|
|
616
965
|
this._abortController = null;
|
|
617
966
|
this._isGenerating = false;
|
|
618
967
|
}
|
|
619
968
|
}
|
|
620
|
-
|
|
969
|
+
/**
|
|
970
|
+
* 流式重发(不加用户消息)。
|
|
971
|
+
* @param {Object} [params] - 请求级参数覆盖(仅本次生效)
|
|
972
|
+
* @param {Function} [onProgress] - 流式进度回调
|
|
973
|
+
* @param {Function} [onDone] - 流式完成回调
|
|
974
|
+
*/
|
|
975
|
+
async sendExistingStream(params, onProgress, onDone) {
|
|
976
|
+
if (typeof params === "function") {
|
|
977
|
+
onDone = onProgress;
|
|
978
|
+
onProgress = params;
|
|
979
|
+
params = void 0;
|
|
980
|
+
}
|
|
621
981
|
this._abortController = new AbortController();
|
|
622
982
|
try {
|
|
623
983
|
return await this._request({
|
|
624
984
|
addUser: false,
|
|
625
985
|
isStream: true,
|
|
626
986
|
onProgress,
|
|
627
|
-
onDone
|
|
987
|
+
onDone,
|
|
988
|
+
params
|
|
628
989
|
});
|
|
990
|
+
} catch (err) {
|
|
991
|
+
if (err.name === "AbortError") {
|
|
992
|
+
this.emit("aborted", { timestamp: Date.now() });
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
throw err;
|
|
629
996
|
} finally {
|
|
630
997
|
this._abortController = null;
|
|
631
998
|
this._isGenerating = false;
|
|
632
999
|
}
|
|
633
1000
|
}
|
|
634
1001
|
};
|
|
1002
|
+
/**
|
|
1003
|
+
* 校验 adapter 是否满足协议(v3.0 · 阶段 3)。
|
|
1004
|
+
* 缺少必要方法时抛 ConfigurationError,并列出缺少的方法名——写"同级适配器"不再靠猜。
|
|
1005
|
+
* @param {*} adapter
|
|
1006
|
+
* @throws {ConfigurationError}
|
|
1007
|
+
*/
|
|
1008
|
+
function assertAdapter(adapter) {
|
|
1009
|
+
if (!adapter || typeof adapter !== "object") throw new ConfigurationError("setAdapter: adapter 必须是对象(如 openaiAdapter / createOpenAIAdapter() 实例)");
|
|
1010
|
+
const missing = [
|
|
1011
|
+
"buildRequest",
|
|
1012
|
+
"send",
|
|
1013
|
+
"stream",
|
|
1014
|
+
"parseResponse"
|
|
1015
|
+
].filter((k) => typeof adapter[k] !== "function");
|
|
1016
|
+
if (missing.length) throw new ConfigurationError(`setAdapter: adapter 缺少必要方法: ${missing.join(", ")}(协议见 ChatService.js 顶部的 @typedef ChatAdapter)`);
|
|
1017
|
+
}
|
|
635
1018
|
//#endregion
|
|
636
1019
|
//#region src/utils/url.js
|
|
637
1020
|
/**
|
|
@@ -809,17 +1192,48 @@
|
|
|
809
1192
|
* OpenAI 兼容 API 适配器
|
|
810
1193
|
* 支持 DeepSeek 等完全兼容 OpenAI 接口的服务
|
|
811
1194
|
*/
|
|
1195
|
+
var TRANSPORT_KEYS = [
|
|
1196
|
+
"apiKey",
|
|
1197
|
+
"baseUrl",
|
|
1198
|
+
"apiUrl",
|
|
1199
|
+
"path",
|
|
1200
|
+
"headers"
|
|
1201
|
+
];
|
|
812
1202
|
var openaiAdapter = {
|
|
813
1203
|
name: "openai",
|
|
814
|
-
install(chatService) {
|
|
1204
|
+
install(chatService, options = {}) {
|
|
1205
|
+
if (this._transport) this._transport = {
|
|
1206
|
+
...this._transport,
|
|
1207
|
+
...options
|
|
1208
|
+
};
|
|
815
1209
|
chatService.setAdapter(this);
|
|
816
1210
|
},
|
|
1211
|
+
_resolveConfig(config) {
|
|
1212
|
+
const transport = this._transport || {};
|
|
1213
|
+
const resolved = {
|
|
1214
|
+
...config,
|
|
1215
|
+
...transport
|
|
1216
|
+
};
|
|
1217
|
+
if (transport.modelParams) resolved.modelParams = {
|
|
1218
|
+
...transport.modelParams,
|
|
1219
|
+
...config.modelParams || {}
|
|
1220
|
+
};
|
|
1221
|
+
return resolved;
|
|
1222
|
+
},
|
|
1223
|
+
getRequestDefaults() {
|
|
1224
|
+
if (!this._transport) return {};
|
|
1225
|
+
const defaults = {};
|
|
1226
|
+
for (const [key, value] of Object.entries(this._transport)) if (!TRANSPORT_KEYS.includes(key) && value !== void 0) defaults[key] = value;
|
|
1227
|
+
return defaults;
|
|
1228
|
+
},
|
|
817
1229
|
buildRequest(messages, config, systemPrompts = []) {
|
|
1230
|
+
config = this._resolveConfig(config);
|
|
818
1231
|
const model = config.model || config.modelParams?.model;
|
|
819
1232
|
if (!model) throw new Error("Missing required config: model (either at top level or in modelParams)");
|
|
820
|
-
const
|
|
821
|
-
const
|
|
822
|
-
const
|
|
1233
|
+
const mp = config.modelParams || {};
|
|
1234
|
+
const temperature = mp.temperature ?? config.temperature ?? .7;
|
|
1235
|
+
const maxTokens = mp.maxTokens ?? config.maxTokens ?? 2e3;
|
|
1236
|
+
const reasoningEffort = mp.reasoningEffort ?? config.reasoningEffort;
|
|
823
1237
|
const requestBody = {
|
|
824
1238
|
model,
|
|
825
1239
|
messages: MessageFormatter.format({
|
|
@@ -833,11 +1247,30 @@
|
|
|
833
1247
|
max_tokens: maxTokens,
|
|
834
1248
|
stream: false
|
|
835
1249
|
};
|
|
1250
|
+
if (mp.topP !== void 0) requestBody.top_p = mp.topP;
|
|
1251
|
+
if (mp.frequencyPenalty !== void 0) requestBody.frequency_penalty = mp.frequencyPenalty;
|
|
1252
|
+
if (mp.presencePenalty !== void 0) requestBody.presence_penalty = mp.presencePenalty;
|
|
1253
|
+
if (mp.stop !== void 0) requestBody.stop = mp.stop;
|
|
1254
|
+
if (mp.responseFormat !== void 0) requestBody.response_format = mp.responseFormat;
|
|
1255
|
+
if (mp.seed !== void 0) requestBody.seed = mp.seed;
|
|
836
1256
|
if (config.tools && Array.isArray(config.tools) && config.tools.length > 0) {
|
|
837
1257
|
requestBody.tools = config.tools;
|
|
838
1258
|
requestBody.tool_choice = "auto";
|
|
839
1259
|
}
|
|
840
|
-
if (reasoningEffort
|
|
1260
|
+
if (reasoningEffort !== void 0) requestBody.reasoning_effort = reasoningEffort;
|
|
1261
|
+
const consumedKeys = new Set([
|
|
1262
|
+
"model",
|
|
1263
|
+
"temperature",
|
|
1264
|
+
"maxTokens",
|
|
1265
|
+
"reasoningEffort",
|
|
1266
|
+
"topP",
|
|
1267
|
+
"frequencyPenalty",
|
|
1268
|
+
"presencePenalty",
|
|
1269
|
+
"stop",
|
|
1270
|
+
"responseFormat",
|
|
1271
|
+
"seed"
|
|
1272
|
+
]);
|
|
1273
|
+
for (const [key, value] of Object.entries(mp)) if (!consumedKeys.has(key) && value !== void 0) requestBody[key] = value;
|
|
841
1274
|
return requestBody;
|
|
842
1275
|
},
|
|
843
1276
|
_getUrl(config) {
|
|
@@ -850,6 +1283,7 @@
|
|
|
850
1283
|
},
|
|
851
1284
|
async send(requestBody, config, options = {}) {
|
|
852
1285
|
try {
|
|
1286
|
+
config = this._resolveConfig(config);
|
|
853
1287
|
const url = this._getUrl(config);
|
|
854
1288
|
const headers = {
|
|
855
1289
|
"Content-Type": "application/json",
|
|
@@ -884,6 +1318,7 @@
|
|
|
884
1318
|
return internal;
|
|
885
1319
|
},
|
|
886
1320
|
async stream(requestBody, config, onProgress, onDone, options = {}) {
|
|
1321
|
+
config = this._resolveConfig(config);
|
|
887
1322
|
const streamBody = {
|
|
888
1323
|
...requestBody,
|
|
889
1324
|
stream: true
|
|
@@ -977,165 +1412,213 @@
|
|
|
977
1412
|
throw new APIError(errorMessage, response.status, null, errorText);
|
|
978
1413
|
}
|
|
979
1414
|
};
|
|
1415
|
+
/**
|
|
1416
|
+
* 创建 OpenAI 兼容适配器实例(工厂)。
|
|
1417
|
+
*
|
|
1418
|
+
* 与单例 openaiAdapter 的区别:每个实例自持一份运输配置(apiKey/baseUrl/apiUrl/path/headers),
|
|
1419
|
+
* 互不干扰——解决"同一适配器装到多个 ChatService 互相覆盖"的单例陷阱。
|
|
1420
|
+
*
|
|
1421
|
+
* 用法:
|
|
1422
|
+
* const adapter = createOpenAIAdapter({ apiKey, baseUrl, modelParams: { temperature: 0.8 } });
|
|
1423
|
+
* const chat = new ChatService({ adapter, model: 'deepseek-chat' });
|
|
1424
|
+
* chat.use(adapter); // 或直接 new ChatService({ adapter })
|
|
1425
|
+
*
|
|
1426
|
+
* 非运输键(model/modelParams/messageFormat/resolveImage/capabilities 等)会作为
|
|
1427
|
+
* "请求默认参数"供会话层合并,单次请求仍可覆盖。
|
|
1428
|
+
*/
|
|
1429
|
+
function createOpenAIAdapter(options = {}) {
|
|
1430
|
+
return {
|
|
1431
|
+
...openaiAdapter,
|
|
1432
|
+
_transport: { ...options }
|
|
1433
|
+
};
|
|
1434
|
+
}
|
|
980
1435
|
//#endregion
|
|
981
1436
|
//#region src/plugins/tool-calling.js
|
|
982
1437
|
/**
|
|
983
1438
|
* 工具调用插件
|
|
984
1439
|
* 功能:拦截助手消息中的 tool_calls,执行对应的工具,将结果作为 tool 消息加入对话,
|
|
985
1440
|
* 然后自动继续对话(通过 sendExisting / sendExistingStream),直到没有新的工具调用。
|
|
986
|
-
*
|
|
1441
|
+
*
|
|
987
1442
|
* 设计要点:
|
|
988
1443
|
* - 支持普通请求和流式请求(通过 isStream 标志区分)
|
|
989
1444
|
* - 支持多次工具调用循环(maxIterations 防止无限循环)
|
|
990
|
-
* -
|
|
1445
|
+
* - 并行执行工具
|
|
991
1446
|
* - 工具执行失败时,仍然返回错误信息给 AI,而不是中断整个流程
|
|
992
1447
|
* - 触发 tool-error 事件,方便用户监听工具执行异常
|
|
1448
|
+
*
|
|
1449
|
+
* 注意:请使用 createToolCallingPlugin() 工厂创建实例。
|
|
1450
|
+
* 默认导出的 toolCallingPlugin 是兼容用的模块级单例,装到多个 ChatService
|
|
1451
|
+
* 实例会互相覆盖(executor 表、工具定义、配置),新代码不要直接用单例。
|
|
993
1452
|
*/
|
|
994
|
-
var toolCallingPlugin =
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1453
|
+
var toolCallingPlugin = createToolCallingPlugin();
|
|
1454
|
+
/**
|
|
1455
|
+
* 创建工具调用插件实例(工厂)。
|
|
1456
|
+
* @param {Object} [options] — { timeout, maxIterations }
|
|
1457
|
+
*/
|
|
1458
|
+
function createToolCallingPlugin(options = {}) {
|
|
1459
|
+
return {
|
|
1460
|
+
name: "tool-calling",
|
|
1461
|
+
maxIterations: options.maxIterations || 5,
|
|
1462
|
+
_options: { ...options },
|
|
1463
|
+
_tools: /* @__PURE__ */ new Map(),
|
|
1464
|
+
_toolDefs: [],
|
|
1465
|
+
chatService: null,
|
|
1466
|
+
install(chatService, options = {}) {
|
|
1467
|
+
this._options = {
|
|
1468
|
+
...this._options,
|
|
1469
|
+
...options
|
|
1470
|
+
};
|
|
1471
|
+
this.chatService = chatService;
|
|
1472
|
+
chatService.pipe({
|
|
1473
|
+
name: "tool-calling-inject",
|
|
1474
|
+
phase: "beforeSend",
|
|
1475
|
+
run: ({ config }) => {
|
|
1476
|
+
if (this._toolDefs.length) config.tools = this._toolDefs;
|
|
1477
|
+
}
|
|
1013
1478
|
});
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1479
|
+
/**
|
|
1480
|
+
* 注册工具
|
|
1481
|
+
* @param {string} name - 工具名称(唯一标识)
|
|
1482
|
+
* @param {string} description - 工具描述(告诉 AI 何时调用)
|
|
1483
|
+
* @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
|
|
1484
|
+
* @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
|
|
1485
|
+
* @returns {ChatService} 返回 chatService 实例,支持链式调用
|
|
1486
|
+
*/
|
|
1487
|
+
chatService.registerTool = (name, description, executor, parameters = {}) => {
|
|
1488
|
+
this._tools.set(name, {
|
|
1489
|
+
executor,
|
|
1490
|
+
description
|
|
1491
|
+
});
|
|
1492
|
+
const toolDefinition = {
|
|
1493
|
+
type: "function",
|
|
1494
|
+
function: {
|
|
1495
|
+
name,
|
|
1496
|
+
description,
|
|
1497
|
+
parameters: {
|
|
1498
|
+
type: "object",
|
|
1499
|
+
properties: parameters,
|
|
1500
|
+
required: Object.keys(parameters).filter((key) => parameters[key]?.required)
|
|
1501
|
+
}
|
|
1023
1502
|
}
|
|
1024
|
-
}
|
|
1503
|
+
};
|
|
1504
|
+
if (!this._toolDefs.find((t) => t.function.name === name)) this._toolDefs.push(toolDefinition);
|
|
1505
|
+
return chatService;
|
|
1025
1506
|
};
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
const
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
const tool = self._tools.get(toolName);
|
|
1068
|
-
if (!tool) {
|
|
1069
|
-
chat.emit("tool-error", {
|
|
1070
|
-
toolName,
|
|
1071
|
-
error: /* @__PURE__ */ new Error(`Tool not registered: ${toolName}`),
|
|
1072
|
-
toolCallId: call.id,
|
|
1073
|
-
stage: "lookup",
|
|
1074
|
-
timestamp: Date.now()
|
|
1075
|
-
});
|
|
1076
|
-
return {
|
|
1077
|
-
tool_call_id: call.id,
|
|
1078
|
-
error: `工具 ${toolName} 未注册`,
|
|
1079
|
-
success: false
|
|
1080
|
-
};
|
|
1081
|
-
}
|
|
1082
|
-
try {
|
|
1083
|
-
const toolTimeout = chat.config.toolTimeout;
|
|
1084
|
-
let execPromise = tool.executor(args);
|
|
1085
|
-
if (toolTimeout && typeof toolTimeout === "number" && toolTimeout > 0) {
|
|
1086
|
-
const timeoutErr = /* @__PURE__ */ new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
|
|
1087
|
-
timeoutErr.name = "ToolTimeoutError";
|
|
1088
|
-
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(timeoutErr), toolTimeout));
|
|
1089
|
-
execPromise = Promise.race([execPromise, timeoutPromise]);
|
|
1507
|
+
chatService.pipe({
|
|
1508
|
+
name: "tool-calling-loop",
|
|
1509
|
+
phase: "afterSend",
|
|
1510
|
+
run: async (ctx) => {
|
|
1511
|
+
ctx.result = await this._handleWithTools(ctx.result, ctx.isStream, ctx.onProgress || void 0, ctx.onDone || void 0);
|
|
1512
|
+
}
|
|
1513
|
+
});
|
|
1514
|
+
},
|
|
1515
|
+
async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
|
|
1516
|
+
const self = this;
|
|
1517
|
+
const chat = this.chatService;
|
|
1518
|
+
let iteration = 0;
|
|
1519
|
+
/**
|
|
1520
|
+
* 递归处理工具调用
|
|
1521
|
+
* @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
|
|
1522
|
+
* @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
|
|
1523
|
+
*/
|
|
1524
|
+
async function processResponse(initialResponse) {
|
|
1525
|
+
let lastResponse = initialResponse;
|
|
1526
|
+
while (iteration < self.maxIterations) {
|
|
1527
|
+
const toolCalls = lastResponse?.toolCalls;
|
|
1528
|
+
if (!toolCalls || toolCalls.length === 0) break;
|
|
1529
|
+
iteration++;
|
|
1530
|
+
const toolResults = await Promise.all(toolCalls.map(async (call) => {
|
|
1531
|
+
const toolName = call.function?.name;
|
|
1532
|
+
let args;
|
|
1533
|
+
try {
|
|
1534
|
+
args = JSON.parse(call.function?.arguments || "{}");
|
|
1535
|
+
} catch (parseErr) {
|
|
1536
|
+
chat.emit("tool-error", {
|
|
1537
|
+
toolName: toolName || "unknown",
|
|
1538
|
+
error: parseErr,
|
|
1539
|
+
toolCallId: call.id,
|
|
1540
|
+
stage: "parse",
|
|
1541
|
+
timestamp: Date.now()
|
|
1542
|
+
});
|
|
1543
|
+
return {
|
|
1544
|
+
tool_call_id: call.id,
|
|
1545
|
+
error: `参数解析失败: ${parseErr.message}`,
|
|
1546
|
+
success: false
|
|
1547
|
+
};
|
|
1090
1548
|
}
|
|
1091
|
-
const
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1549
|
+
const tool = self._tools.get(toolName);
|
|
1550
|
+
if (!tool) {
|
|
1551
|
+
chat.emit("tool-error", {
|
|
1552
|
+
toolName,
|
|
1553
|
+
error: /* @__PURE__ */ new Error(`Tool not registered: ${toolName}`),
|
|
1554
|
+
toolCallId: call.id,
|
|
1555
|
+
stage: "lookup",
|
|
1556
|
+
timestamp: Date.now()
|
|
1557
|
+
});
|
|
1558
|
+
return {
|
|
1559
|
+
tool_call_id: call.id,
|
|
1560
|
+
error: `工具 ${toolName} 未注册`,
|
|
1561
|
+
success: false
|
|
1562
|
+
};
|
|
1563
|
+
}
|
|
1564
|
+
try {
|
|
1565
|
+
const toolTimeout = self._options.timeout ?? chat.config.toolTimeout;
|
|
1566
|
+
let execPromise = tool.executor(args);
|
|
1567
|
+
if (toolTimeout && typeof toolTimeout === "number" && toolTimeout > 0) {
|
|
1568
|
+
const timeoutErr = /* @__PURE__ */ new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
|
|
1569
|
+
timeoutErr.name = "ToolTimeoutError";
|
|
1570
|
+
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(timeoutErr), toolTimeout));
|
|
1571
|
+
execPromise = Promise.race([execPromise, timeoutPromise]);
|
|
1572
|
+
}
|
|
1573
|
+
const result = await execPromise;
|
|
1574
|
+
chat.emit("tool-success", {
|
|
1575
|
+
toolName,
|
|
1576
|
+
result,
|
|
1577
|
+
toolCallId: call.id,
|
|
1578
|
+
timestamp: Date.now()
|
|
1579
|
+
});
|
|
1580
|
+
return {
|
|
1581
|
+
tool_call_id: call.id,
|
|
1582
|
+
content: typeof result === "string" ? result : JSON.stringify(result),
|
|
1583
|
+
success: true
|
|
1584
|
+
};
|
|
1585
|
+
} catch (err) {
|
|
1586
|
+
const stage = err.name === "ToolTimeoutError" ? "timeout" : "execute";
|
|
1587
|
+
chat.emit("tool-error", {
|
|
1588
|
+
toolName,
|
|
1589
|
+
error: err,
|
|
1590
|
+
toolCallId: call.id,
|
|
1591
|
+
stage,
|
|
1592
|
+
timestamp: Date.now()
|
|
1593
|
+
});
|
|
1594
|
+
return {
|
|
1595
|
+
tool_call_id: call.id,
|
|
1596
|
+
error: err.message,
|
|
1597
|
+
success: false
|
|
1598
|
+
};
|
|
1599
|
+
}
|
|
1600
|
+
}));
|
|
1601
|
+
for (const tr of toolResults) {
|
|
1602
|
+
const content = tr.success ? tr.content : tr.error || "工具执行失败";
|
|
1603
|
+
chat.messages.addTool(content, tr.tool_call_id);
|
|
1117
1604
|
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
lastResponse = chunk;
|
|
1127
|
-
}, (final) => {
|
|
1128
|
-
lastResponse = final;
|
|
1129
|
-
resolve();
|
|
1605
|
+
if (isStream) await new Promise((resolve) => {
|
|
1606
|
+
chat.sendExistingStream((chunk) => {
|
|
1607
|
+
if (onProgress) onProgress(chunk);
|
|
1608
|
+
lastResponse = chunk;
|
|
1609
|
+
}, (final) => {
|
|
1610
|
+
lastResponse = final;
|
|
1611
|
+
resolve();
|
|
1612
|
+
});
|
|
1130
1613
|
});
|
|
1131
|
-
|
|
1132
|
-
|
|
1614
|
+
else lastResponse = await chat.sendExisting();
|
|
1615
|
+
}
|
|
1616
|
+
return lastResponse;
|
|
1133
1617
|
}
|
|
1134
|
-
return
|
|
1618
|
+
return await processResponse(initialResponse);
|
|
1135
1619
|
}
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
};
|
|
1620
|
+
};
|
|
1621
|
+
}
|
|
1139
1622
|
//#endregion
|
|
1140
1623
|
//#region src/plugins/model-registry.js
|
|
1141
1624
|
/**
|
|
@@ -1242,56 +1725,83 @@
|
|
|
1242
1725
|
reasoning: false,
|
|
1243
1726
|
vision: false
|
|
1244
1727
|
};
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1728
|
+
/**
|
|
1729
|
+
* 注意:请使用 createModelRegistryPlugin() 工厂创建实例。
|
|
1730
|
+
* 默认导出的 modelRegistryPlugin 是兼容用的模块级单例,装到多个 ChatService
|
|
1731
|
+
* 实例会互相覆盖(注册表、实例引用),新代码不要直接用单例。
|
|
1732
|
+
*/
|
|
1733
|
+
var modelRegistryPlugin = createModelRegistryPlugin();
|
|
1734
|
+
/**
|
|
1735
|
+
* 创建模型能力注册表插件实例(工厂)。
|
|
1736
|
+
* @param {Object} [options] — { models: { '模型名': capabilities } }(合并进内置表)
|
|
1737
|
+
*/
|
|
1738
|
+
function createModelRegistryPlugin(options = {}) {
|
|
1739
|
+
return {
|
|
1740
|
+
name: "model-registry",
|
|
1741
|
+
_options: { ...options },
|
|
1742
|
+
_registry: new Map([...Object.entries(BUILTIN_MODELS), ...Object.entries(options.models || {})]),
|
|
1743
|
+
chat: null,
|
|
1744
|
+
install(chatService, options = {}) {
|
|
1745
|
+
this._options = {
|
|
1746
|
+
...this._options,
|
|
1747
|
+
...options
|
|
1261
1748
|
};
|
|
1262
|
-
this.
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
chatService.on("config-updated", ({ changes }) => {
|
|
1275
|
-
if ("model" in changes) this._syncCapabilities();
|
|
1276
|
-
if ("capabilities" in changes && !("model" in changes)) {
|
|
1277
|
-
const current = this._lookupCapabilities();
|
|
1278
|
-
if (current) chatService.config.capabilities = {
|
|
1279
|
-
...current,
|
|
1280
|
-
...changes.capabilities
|
|
1749
|
+
this.chat = chatService;
|
|
1750
|
+
/**
|
|
1751
|
+
* 注册/覆盖一个模型的能力标签
|
|
1752
|
+
* @param {string} name — 模型名称
|
|
1753
|
+
* @param {Object} capabilities — 能力标签对象(部分字段即可,未提供的取默认值)
|
|
1754
|
+
* @returns {ChatService}
|
|
1755
|
+
*/
|
|
1756
|
+
chatService.registerModel = (name, capabilities = {}) => {
|
|
1757
|
+
if (!name || typeof name !== "string" || !name.trim()) throw new Error("[model-registry] 模型名称必须是非空字符串");
|
|
1758
|
+
const merged = {
|
|
1759
|
+
...DEFAULT_CAPABILITIES,
|
|
1760
|
+
...capabilities
|
|
1281
1761
|
};
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1762
|
+
this._registry.set(name.trim(), merged);
|
|
1763
|
+
if (chatService.config.model === name.trim()) this._syncCapabilities();
|
|
1764
|
+
return chatService;
|
|
1765
|
+
};
|
|
1766
|
+
/**
|
|
1767
|
+
* 列出所有已注册的模型名称
|
|
1768
|
+
* @returns {Array<string>}
|
|
1769
|
+
*/
|
|
1770
|
+
chatService.listModels = () => {
|
|
1771
|
+
return [...this._registry.keys()];
|
|
1772
|
+
};
|
|
1773
|
+
this._syncCapabilities();
|
|
1774
|
+
chatService.pipe({
|
|
1775
|
+
name: "model-registry-caps",
|
|
1776
|
+
phase: "beforeSend",
|
|
1777
|
+
run: ({ config }) => {
|
|
1778
|
+
if (!config.model) return;
|
|
1779
|
+
const caps = this._registry.get(config.model);
|
|
1780
|
+
if (caps) config.capabilities = { ...caps };
|
|
1781
|
+
}
|
|
1782
|
+
});
|
|
1783
|
+
chatService.on("config-updated", ({ changes }) => {
|
|
1784
|
+
if ("model" in changes) this._syncCapabilities();
|
|
1785
|
+
if ("capabilities" in changes && !("model" in changes)) {
|
|
1786
|
+
const current = this._lookupCapabilities();
|
|
1787
|
+
if (current) chatService.config.capabilities = {
|
|
1788
|
+
...current,
|
|
1789
|
+
...changes.capabilities
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
});
|
|
1793
|
+
},
|
|
1794
|
+
_lookupCapabilities() {
|
|
1795
|
+
const model = this.chat.config.model;
|
|
1796
|
+
if (!model) return null;
|
|
1797
|
+
return this._registry.get(model) || null;
|
|
1798
|
+
},
|
|
1799
|
+
_syncCapabilities() {
|
|
1800
|
+
const caps = this._lookupCapabilities();
|
|
1801
|
+
if (caps) this.chat.config.capabilities = { ...caps };
|
|
1802
|
+
}
|
|
1803
|
+
};
|
|
1804
|
+
}
|
|
1295
1805
|
//#endregion
|
|
1296
1806
|
exports.APIError = APIError;
|
|
1297
1807
|
exports.ChatService = ChatService;
|
|
@@ -1301,8 +1811,13 @@
|
|
|
1301
1811
|
exports.MessageStore = MessageStore;
|
|
1302
1812
|
exports.NetworkError = NetworkError;
|
|
1303
1813
|
exports.ParsingError = ParsingError;
|
|
1814
|
+
exports.Pipeline = Pipeline;
|
|
1304
1815
|
exports.SystemPromptStore = SystemPromptStore;
|
|
1305
1816
|
exports.assembleMessages = assembleMessages;
|
|
1817
|
+
exports.assertAdapter = assertAdapter;
|
|
1818
|
+
exports.createModelRegistryPlugin = createModelRegistryPlugin;
|
|
1819
|
+
exports.createOpenAIAdapter = createOpenAIAdapter;
|
|
1820
|
+
exports.createToolCallingPlugin = createToolCallingPlugin;
|
|
1306
1821
|
exports.modelRegistryPlugin = modelRegistryPlugin;
|
|
1307
1822
|
exports.openaiAdapter = openaiAdapter;
|
|
1308
1823
|
exports.toolCallingPlugin = toolCallingPlugin;
|