@auipage/agent 0.1.0 → 0.2.0-alpha.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/AUTHORS.txt +6 -6
- package/CHANGELOG +29 -4
- package/README.md +136 -154
- package/dist/index.js +1024 -616
- package/package.json +3 -3
- package/src/callFuns.js +44 -35
- package/src/createTool.js +101 -60
- package/src/index.js +41 -21
- package/src/runConversation.js +65 -56
- package/types/agent.d.ts +58 -47
- package/types/create-tool.d.ts +44 -38
- package/types/index.d.ts +20 -20
- package/types/tool.d.ts +15 -15
package/dist/index.js
CHANGED
|
@@ -1,580 +1,927 @@
|
|
|
1
|
-
/*! @auipage/agent v0.
|
|
1
|
+
/*! @auipage/agent v0.2.0-alpha.0 */
|
|
2
2
|
(function (global, factory) {
|
|
3
3
|
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
|
4
4
|
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
|
5
5
|
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.auipage_agent = {}));
|
|
6
6
|
})(this, (function (exports) { 'use strict';
|
|
7
7
|
|
|
8
|
-
// 极简 EventEmitter:on / off / emit,供 Response 复用
|
|
9
|
-
class Emitter {
|
|
10
|
-
constructor() {
|
|
11
|
-
this._events = Object.create(null);
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
on(event, listener) {
|
|
15
|
-
if (typeof listener !== 'function') return this;
|
|
16
|
-
const list = this._events[event] || (this._events[event] = []);
|
|
17
|
-
list.push(listener);
|
|
18
|
-
return this;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
off(event, listener) {
|
|
22
|
-
const list = this._events[event];
|
|
23
|
-
if (!list) return this;
|
|
24
|
-
const idx = list.indexOf(listener);
|
|
25
|
-
if (idx >= 0) list.splice(idx, 1);
|
|
26
|
-
if (list.length === 0) delete this._events[event];
|
|
27
|
-
return this;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
emit
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
//
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return true;
|
|
44
|
-
|
|
8
|
+
// 极简 EventEmitter:on / off / emit,供 Response 复用
|
|
9
|
+
class Emitter {
|
|
10
|
+
constructor() {
|
|
11
|
+
this._events = Object.create(null);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
on(event, listener) {
|
|
15
|
+
if (typeof listener !== 'function') return this;
|
|
16
|
+
const list = this._events[event] || (this._events[event] = []);
|
|
17
|
+
list.push(listener);
|
|
18
|
+
return this;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
off(event, listener) {
|
|
22
|
+
const list = this._events[event];
|
|
23
|
+
if (!list) return this;
|
|
24
|
+
const idx = list.indexOf(listener);
|
|
25
|
+
if (idx >= 0) list.splice(idx, 1);
|
|
26
|
+
if (list.length === 0) delete this._events[event];
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// #doc:emit
|
|
31
|
+
emit(event, ...args) {
|
|
32
|
+
const list = this._events[event];
|
|
33
|
+
if (!list || list.length === 0) return false;
|
|
34
|
+
// 复制一份再触发,避免 off 回调过程中影响本次派发
|
|
35
|
+
for (const fn of list.slice()) {
|
|
36
|
+
try {
|
|
37
|
+
fn.apply(null, args);
|
|
38
|
+
} catch (e) {
|
|
39
|
+
// 单个监听器异常不影响其它监听器,也不再冒泡成进程级异常
|
|
40
|
+
console.error(e);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return true;
|
|
44
|
+
// #end
|
|
45
|
+
}
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
// Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
|
|
48
|
-
|
|
49
|
-
class Response extends Emitter {
|
|
50
|
-
constructor() {
|
|
51
|
-
super();
|
|
52
|
-
|
|
53
|
-
this.
|
|
54
|
-
this.
|
|
55
|
-
this.
|
|
56
|
-
this.
|
|
57
|
-
this.
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
this.
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
this.
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
48
|
+
// Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
|
|
49
|
+
|
|
50
|
+
class Response extends Emitter {
|
|
51
|
+
constructor() {
|
|
52
|
+
super();
|
|
53
|
+
// #doc:state
|
|
54
|
+
this.status = 0;
|
|
55
|
+
this.headers = {};
|
|
56
|
+
this.ok = false;
|
|
57
|
+
this._done = false; // 标记是否已经 end/error,防止重复触发
|
|
58
|
+
this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
|
|
59
|
+
this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
|
|
60
|
+
this._cancel = null; // 由 createFetch 注入,用于中断底层请求
|
|
61
|
+
this._errorPending = null; // 消费者还没来得及注册时就发生的错误,注册后补发
|
|
62
|
+
// #end
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// 注册监听;error 是一次性终态,注册时若已发生则补发
|
|
66
|
+
// #doc:replay
|
|
67
|
+
on(event, listener) {
|
|
68
|
+
super.on(event, listener);
|
|
69
|
+
if (event === 'error' && this._errorPending) {
|
|
70
|
+
const err = this._errorPending;
|
|
71
|
+
this._errorPending = null;
|
|
72
|
+
// 异步补发,避免在注册栈里同步回调
|
|
73
|
+
queueMicrotask(() => this.emit('error', err));
|
|
74
|
+
}
|
|
75
|
+
return this;
|
|
76
|
+
// #end
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 主动取消请求,失败统一从 error 事件返回
|
|
80
|
+
cancel() {
|
|
81
|
+
if (this._cancel) this._cancel();
|
|
82
|
+
return this;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// 统一读取响应头:浏览器是 Headers 对象,Node 是普通对象
|
|
86
|
+
header(name) {
|
|
87
|
+
const headers = this.headers;
|
|
88
|
+
if (!headers) return undefined;
|
|
89
|
+
if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
|
|
90
|
+
return headers[name];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
|
|
94
|
+
_push(type, payload) {
|
|
95
|
+
if (this._done && type !== 'error') return;
|
|
96
|
+
|
|
97
|
+
// SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
|
|
98
|
+
// #doc:sse
|
|
99
|
+
if (type === 'data' && this._sseMode) {
|
|
100
|
+
this._sseBuffer += payload;
|
|
101
|
+
|
|
102
|
+
// 按 \n\n 分割出完整事件,最后一段可能不完整
|
|
103
|
+
const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
|
|
104
|
+
this._sseBuffer = parts.pop();
|
|
105
|
+
|
|
106
|
+
for (const part of parts) {
|
|
107
|
+
const payload = this._extractSSEData(part);
|
|
108
|
+
if (payload !== null) {
|
|
109
|
+
this.emit('data', payload);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return;
|
|
113
|
+
// #end
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (type === 'end') {
|
|
117
|
+
// SSE 模式下,flush 缓冲区残留
|
|
118
|
+
if (this._sseMode && this._sseBuffer.trim()) {
|
|
119
|
+
const payload = this._extractSSEData(this._sseBuffer);
|
|
120
|
+
if (payload !== null) {
|
|
121
|
+
this.emit('data', payload);
|
|
122
|
+
}
|
|
123
|
+
this._sseBuffer = '';
|
|
124
|
+
}
|
|
125
|
+
this._done = true;
|
|
126
|
+
}
|
|
127
|
+
if (type === 'error') {
|
|
128
|
+
this._done = true;
|
|
129
|
+
const listeners = this._events && this._events['error'];
|
|
130
|
+
if (!listeners || listeners.length === 0) {
|
|
131
|
+
// 消费者还没注册监听,先缓存,注册时补发
|
|
132
|
+
this._errorPending = payload;
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
this.emit(type, payload);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
|
|
141
|
+
// #doc:extract
|
|
142
|
+
_extractSSEData(raw) {
|
|
143
|
+
const dataLines = [];
|
|
144
|
+
for (const line of raw.split('\n')) {
|
|
145
|
+
if (line.startsWith('data:')) {
|
|
146
|
+
dataLines.push(line.replace(/^data:\s*/, '').replace(/\r$/, ''));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (dataLines.length === 0) return null;
|
|
150
|
+
return dataLines.join('\n');
|
|
151
|
+
// #end
|
|
152
|
+
}
|
|
108
153
|
}
|
|
109
154
|
|
|
110
|
-
// fetch 工厂:注入 adapter,返回对外的 fetch 函数
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
return new Promise((resolve, reject) => {
|
|
116
|
-
if (!options || !options.url) {
|
|
117
|
-
reject(new Error('fetch: options.url is required'));
|
|
118
|
-
return;
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const response = new Response();
|
|
122
|
-
|
|
123
|
-
// adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
|
|
124
|
-
// 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
|
|
125
|
-
queueMicrotask(() => resolve(response));
|
|
126
|
-
|
|
127
|
-
adapter(options, {
|
|
128
|
-
onResponse(meta) {
|
|
129
|
-
if (meta && typeof meta.status === 'number') {
|
|
130
|
-
response.status = meta.status;
|
|
131
|
-
response.ok = meta.status >= 200 && meta.status < 300;
|
|
132
|
-
}
|
|
133
|
-
if (meta && meta.headers) {
|
|
134
|
-
response.headers = meta.headers;
|
|
135
|
-
|
|
136
|
-
// 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
|
|
137
|
-
const contentType =
|
|
138
|
-
(typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
|
|
139
|
-
meta.headers['content-type'] ||
|
|
140
|
-
'';
|
|
141
|
-
if (contentType.includes('text/event-stream')) {
|
|
142
|
-
response._sseMode = true;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
},
|
|
146
|
-
onData(chunk) {
|
|
147
|
-
response._push('data', chunk);
|
|
148
|
-
},
|
|
149
|
-
onEnd() {
|
|
150
|
-
response._push('end');
|
|
151
|
-
},
|
|
152
|
-
onError(err) {
|
|
153
|
-
// 错误同时通过 error 事件 和 catch 暴露,避免遗漏
|
|
154
|
-
response._push('error', err);
|
|
155
|
-
reject(err);
|
|
156
|
-
}
|
|
157
|
-
});
|
|
158
|
-
});
|
|
159
|
-
};
|
|
155
|
+
// fetch 工厂:注入 adapter,返回对外的 fetch 函数
|
|
156
|
+
|
|
157
|
+
// 只有普通对象才自动 JSON 序列化,ArrayBufferView / Blob / FormData 等保持原样
|
|
158
|
+
function isPlainBody(body) {
|
|
159
|
+
return Object.prototype.toString.call(body) === '[object Object]';
|
|
160
160
|
}
|
|
161
161
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if (
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
162
|
+
function createFetch(adapter) {
|
|
163
|
+
// #doc:factory
|
|
164
|
+
return function fetch(options) {
|
|
165
|
+
// 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
|
|
166
|
+
return new Promise((resolve, reject) => {
|
|
167
|
+
if (!options || !options.url) {
|
|
168
|
+
reject(new Error('fetch: options.url is required'));
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// 请求体是普通对象时自动序列化,避免 Node 端 req.write(object) 抛 TypeError
|
|
173
|
+
if (isPlainBody(options.body)) {
|
|
174
|
+
options = Object.assign({}, options, { body: JSON.stringify(options.body) });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const response = new Response();
|
|
178
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
179
|
+
let timer = null;
|
|
180
|
+
let failed = false;
|
|
181
|
+
|
|
182
|
+
response._cancel = () => { if (controller) controller.abort(); };
|
|
183
|
+
|
|
184
|
+
// adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
|
|
185
|
+
// 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
|
|
186
|
+
queueMicrotask(() => resolve(response));
|
|
187
|
+
// #end
|
|
188
|
+
|
|
189
|
+
const clearTimer = () => {
|
|
190
|
+
if (timer) {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
timer = null;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
// #doc:hooks
|
|
197
|
+
const hooks = {
|
|
198
|
+
onResponse(meta) {
|
|
199
|
+
if (meta && typeof meta.status === 'number') {
|
|
200
|
+
response.status = meta.status;
|
|
201
|
+
response.ok = meta.status >= 200 && meta.status < 300;
|
|
202
|
+
}
|
|
203
|
+
if (meta && meta.headers) {
|
|
204
|
+
response.headers = meta.headers;
|
|
205
|
+
|
|
206
|
+
// 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
|
|
207
|
+
const contentType =
|
|
208
|
+
(typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
|
|
209
|
+
meta.headers['content-type'] ||
|
|
210
|
+
'';
|
|
211
|
+
if (contentType.includes('text/event-stream')) {
|
|
212
|
+
response._sseMode = true;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// 非 2xx 单独通知:不占用 error 事件、不锁 _done,错误体照常投递
|
|
217
|
+
if (response.status >= 400) {
|
|
218
|
+
response.emit('http-error', { status: response.status, headers: response.headers });
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
onData(chunk) {
|
|
222
|
+
response._push('data', chunk);
|
|
223
|
+
},
|
|
224
|
+
onEnd() {
|
|
225
|
+
clearTimer();
|
|
226
|
+
response._push('end');
|
|
227
|
+
},
|
|
228
|
+
onError(err) {
|
|
229
|
+
if (failed) return;
|
|
230
|
+
failed = true;
|
|
231
|
+
clearTimer();
|
|
232
|
+
// 错误同时通过 error 事件 和 catch 暴露,避免遗漏
|
|
233
|
+
response._push('error', err);
|
|
234
|
+
reject(err);
|
|
235
|
+
}
|
|
236
|
+
};
|
|
237
|
+
// #end
|
|
238
|
+
|
|
239
|
+
// #doc:abort
|
|
240
|
+
const abortWith = (err) => {
|
|
241
|
+
if (controller) controller.abort();
|
|
242
|
+
hooks.onError(err);
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// 超时:到点先中断底层请求,再走统一错误通道
|
|
246
|
+
if (options.timeout > 0) {
|
|
247
|
+
timer = setTimeout(() => {
|
|
248
|
+
timer = null;
|
|
249
|
+
abortWith(new Error('fetch: 请求超时(' + options.timeout + 'ms)'));
|
|
250
|
+
}, options.timeout);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 外部 signal
|
|
254
|
+
if (options.signal) {
|
|
255
|
+
if (options.signal.aborted) {
|
|
256
|
+
abortWith(new Error('fetch: 请求已取消'));
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
options.signal.addEventListener('abort', () => {
|
|
260
|
+
abortWith(new Error('fetch: 请求已取消'));
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// 把内部 controller 的 signal 交给 adapter,adapter 可据此中断底层请求
|
|
265
|
+
const requestOptions = controller ? Object.assign({}, options, { signal: controller.signal }) : options;
|
|
266
|
+
|
|
267
|
+
let ret;
|
|
268
|
+
try {
|
|
269
|
+
ret = adapter(requestOptions, hooks);
|
|
270
|
+
} catch (err) {
|
|
271
|
+
hooks.onError(err);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
// adapter 允许返回 Promise,失败也要走同一条错误通道
|
|
275
|
+
if (ret && typeof ret.then === 'function') ret.then(null, hooks.onError);
|
|
276
|
+
// #end
|
|
277
|
+
});
|
|
278
|
+
};
|
|
210
279
|
}
|
|
211
280
|
|
|
212
|
-
//
|
|
213
|
-
// adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
req.write(body);
|
|
263
|
-
}
|
|
264
|
-
req.end();
|
|
281
|
+
// 浏览器环境适配器:基于原生 fetch + ReadableStream
|
|
282
|
+
// adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
|
|
283
|
+
function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
284
|
+
const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
285
|
+
|
|
286
|
+
if (typeof fetch !== 'function') {
|
|
287
|
+
onError(new Error('Global fetch is not available in this environment'));
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
fetch(url, { method, headers, body, signal })
|
|
292
|
+
.then(async (res) => {
|
|
293
|
+
if (typeof onResponse === 'function') {
|
|
294
|
+
onResponse({
|
|
295
|
+
status: res.status || 0,
|
|
296
|
+
headers: res.headers || {}
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// 没有 body(例如 204)直接结束
|
|
301
|
+
if (!res.body) {
|
|
302
|
+
onEnd();
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// #doc:read
|
|
307
|
+
const reader = res.body.getReader();
|
|
308
|
+
const decoder = new TextDecoder('utf-8');
|
|
309
|
+
|
|
310
|
+
// 循环读取流直到 done
|
|
311
|
+
// 用 async IIFE 形式启动,错误统一走 onError
|
|
312
|
+
(async () => {
|
|
313
|
+
try {
|
|
314
|
+
// eslint-disable-next-line no-constant-condition
|
|
315
|
+
while (true) {
|
|
316
|
+
const { value, done } = await reader.read();
|
|
317
|
+
if (done) {
|
|
318
|
+
onEnd();
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
// value 是 Uint8Array,解码为字符串
|
|
322
|
+
onData(decoder.decode(value, { stream: true }));
|
|
323
|
+
// #end
|
|
324
|
+
}
|
|
325
|
+
} catch (err) {
|
|
326
|
+
onError(err);
|
|
327
|
+
}
|
|
328
|
+
})();
|
|
329
|
+
})
|
|
330
|
+
.catch((err) => onError(err));
|
|
265
331
|
}
|
|
266
332
|
|
|
267
|
-
//
|
|
268
|
-
|
|
269
|
-
//
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
333
|
+
// Node 环境适配器:基于 http / https,天然流式输出
|
|
334
|
+
// adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
|
|
335
|
+
// 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
|
|
336
|
+
// 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
|
|
337
|
+
async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
338
|
+
// #doc:lazy
|
|
339
|
+
const [{ default: http }, { default: https }, { URL }] = await Promise.all([
|
|
340
|
+
import('http'),
|
|
341
|
+
import('https'),
|
|
342
|
+
import('url')
|
|
343
|
+
]);
|
|
344
|
+
// #end
|
|
345
|
+
|
|
346
|
+
const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
347
|
+
|
|
348
|
+
let parsed;
|
|
349
|
+
try {
|
|
350
|
+
parsed = new URL(url);
|
|
351
|
+
} catch (e) {
|
|
352
|
+
onError(e);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const isHttps = parsed.protocol === 'https:';
|
|
357
|
+
const lib = isHttps ? https : http;
|
|
358
|
+
|
|
359
|
+
const reqOptions = {
|
|
360
|
+
method,
|
|
361
|
+
hostname: parsed.hostname,
|
|
362
|
+
port: parsed.port || (isHttps ? 443 : 80),
|
|
363
|
+
path: parsed.pathname + parsed.search,
|
|
364
|
+
headers
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
// #doc:req
|
|
368
|
+
const req = lib.request(reqOptions, (res) => {
|
|
369
|
+
// 把 status / headers 同步给 Response(若上游关心)
|
|
370
|
+
if (typeof onResponse === 'function') {
|
|
371
|
+
onResponse({
|
|
372
|
+
status: res.statusCode || 0,
|
|
373
|
+
headers: res.headers || {}
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
res.setEncoding('utf8');
|
|
378
|
+
res.on('data', (chunk) => onData(chunk));
|
|
379
|
+
res.on('end', () => onEnd());
|
|
380
|
+
res.on('error', (err) => onError(err));
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
req.on('error', (err) => onError(err));
|
|
384
|
+
// #end
|
|
385
|
+
|
|
386
|
+
// 取消 / 超时:直接中断底层请求,错误从 req 的 error 事件返回
|
|
387
|
+
// #doc:abort
|
|
388
|
+
if (signal) {
|
|
389
|
+
if (signal.aborted) {
|
|
390
|
+
onError(new Error('请求已取消'));
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
signal.addEventListener('abort', () => {
|
|
394
|
+
req.destroy(new Error('请求已取消'));
|
|
395
|
+
// #end
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (body != null) {
|
|
400
|
+
req.write(body);
|
|
401
|
+
}
|
|
402
|
+
req.end();
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// 入口:环境判断 + 选择 adapter,构造并导出 fetch
|
|
406
|
+
|
|
407
|
+
// 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
|
|
408
|
+
// #doc:pick
|
|
409
|
+
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
|
|
410
|
+
|
|
411
|
+
const adapter = isBrowser ? browserAdapter : nodeAdapter;
|
|
412
|
+
|
|
274
413
|
const fetch$1 = createFetch(adapter);
|
|
275
414
|
|
|
276
|
-
// 字符串转JSON
|
|
277
|
-
//
|
|
278
|
-
function
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
if (/\r{0,1}\n\r{0,1}\ndata: /.test(value)) {
|
|
282
|
-
return JSON.parse("[" + (value.split(/\r{0,1}\n\r{0,1}\ndata: /)).join(",") + "]");
|
|
283
|
-
} else if (value === "[DONE]") {
|
|
284
|
-
return [];
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
let result = JSON.parse(value);
|
|
288
|
-
if (result.error) throw result.error;
|
|
289
|
-
|
|
290
|
-
return result;
|
|
415
|
+
// 字符串转 JSON,适配 LLM 返回的各种流式格式:
|
|
416
|
+
// 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
|
|
417
|
+
function stripDataPrefix(text) {
|
|
418
|
+
return text.replace(/^data:\s*/, "");
|
|
291
419
|
}
|
|
292
420
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
const thinkPart = parts[0].replace("<think>", "");
|
|
300
|
-
return {
|
|
301
|
-
reasoning: thinkPart,
|
|
302
|
-
content: parts[1] + (content || "")
|
|
303
|
-
};
|
|
304
|
-
}
|
|
305
|
-
|
|
306
|
-
const OPEN = "<think>";
|
|
307
|
-
const CLOSE = "</think>";
|
|
308
|
-
|
|
309
|
-
// 计算文本尾部与标签前缀的最长匹配长度
|
|
310
|
-
// 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
|
|
311
|
-
function partialTagLength(text, tag) {
|
|
312
|
-
const max = Math.min(tag.length - 1, text.length);
|
|
313
|
-
for (let len = max; len > 0; len--) {
|
|
314
|
-
if (text.endsWith(tag.slice(0, len))) return len;
|
|
315
|
-
}
|
|
316
|
-
return 0;
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
// 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
|
|
320
|
-
// 这里把它剥离出来:思考片段归 thinkback,其余归正文
|
|
321
|
-
// 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
|
|
322
|
-
// 返回 { thinking, content }
|
|
323
|
-
function extractThink(content, state) {
|
|
324
|
-
const buf = (state.thinkBuf || "") + content;
|
|
325
|
-
state.thinkBuf = "";
|
|
326
|
-
|
|
327
|
-
// 正处于思考块内:寻找 </think>
|
|
328
|
-
if (state.inThink) {
|
|
329
|
-
const end = buf.indexOf(CLOSE);
|
|
330
|
-
if (end === -1) {
|
|
331
|
-
const hold = partialTagLength(buf, CLOSE);
|
|
332
|
-
state.thinkBuf = buf.slice(buf.length - hold);
|
|
333
|
-
return { thinking: buf.slice(0, buf.length - hold), content: "" };
|
|
334
|
-
}
|
|
335
|
-
state.inThink = false;
|
|
336
|
-
const rest = extractThink(buf.slice(end + CLOSE.length), state);
|
|
337
|
-
return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
// 正常正文:寻找 <think>
|
|
341
|
-
const start = buf.indexOf(OPEN);
|
|
342
|
-
if (start === -1) {
|
|
343
|
-
const hold = partialTagLength(buf, OPEN);
|
|
344
|
-
state.thinkBuf = buf.slice(buf.length - hold);
|
|
345
|
-
return { thinking: "", content: buf.slice(0, buf.length - hold) };
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
const end = buf.indexOf(CLOSE, start);
|
|
349
|
-
if (end !== -1) {
|
|
350
|
-
const rest = extractThink(buf.slice(end + CLOSE.length), state);
|
|
351
|
-
return {
|
|
352
|
-
thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
|
|
353
|
-
content: buf.slice(0, start) + rest.content
|
|
354
|
-
};
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
// 有 <think> 无 </think>:进入思考态
|
|
358
|
-
state.inThink = true;
|
|
359
|
-
const body = buf.slice(start + OPEN.length);
|
|
360
|
-
const hold = partialTagLength(body, CLOSE);
|
|
361
|
-
state.thinkBuf = body.slice(body.length - hold);
|
|
362
|
-
return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
// 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
|
|
366
|
-
function flushThink(state) {
|
|
367
|
-
const buf = state.thinkBuf || "";
|
|
368
|
-
state.thinkBuf = "";
|
|
369
|
-
return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
|
|
421
|
+
function tryParse(text) {
|
|
422
|
+
try {
|
|
423
|
+
return { value: JSON.parse(text) };
|
|
424
|
+
} catch (e) {
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
370
427
|
}
|
|
371
428
|
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
const delta = choices[i].delta;
|
|
377
|
-
|
|
378
|
-
// 推理内容(reasoning / reasoning_content 字段)
|
|
379
|
-
let reasoning = delta.reasoning || delta.reasoning_content;
|
|
380
|
-
if (reasoning) {
|
|
381
|
-
const parsed = parseReasoning(reasoning, delta.content);
|
|
382
|
-
if (typeof parsed === "object") {
|
|
383
|
-
reasoning = parsed.reasoning;
|
|
384
|
-
delta.content = parsed.content;
|
|
385
|
-
}
|
|
386
|
-
if (thinkback) thinkback(reasoning);
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
// 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
|
|
390
|
-
if (delta.content) {
|
|
391
|
-
const extracted = extractThink(delta.content, state);
|
|
392
|
-
if (extracted.thinking && thinkback) thinkback(extracted.thinking);
|
|
393
|
-
if (extracted.content) {
|
|
394
|
-
if (logback) logback(extracted.content);
|
|
395
|
-
state.content += extracted.content;
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
// 工具调用
|
|
400
|
-
if (delta.tool_calls) {
|
|
401
|
-
for (const toolCall of delta.tool_calls) {
|
|
402
|
-
if (toolCall.id) {
|
|
403
|
-
state.tool_calls.push(toolCall);
|
|
404
|
-
} else {
|
|
405
|
-
state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
// 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
|
|
413
|
-
function flushThinkBuffer(state, { logback, thinkback }) {
|
|
414
|
-
const flushed = flushThink(state);
|
|
415
|
-
if (flushed.thinking && thinkback) thinkback(flushed.thinking);
|
|
416
|
-
if (flushed.content) {
|
|
417
|
-
if (logback) logback(flushed.content);
|
|
418
|
-
state.content += flushed.content;
|
|
419
|
-
}
|
|
429
|
+
function parseOne(text, origin) {
|
|
430
|
+
const parsed = tryParse(stripDataPrefix(text.trim()));
|
|
431
|
+
if (!parsed) throw new SyntaxError("模型返回无法解析:" + String(origin).slice(0, 120));
|
|
432
|
+
return parsed.value;
|
|
420
433
|
}
|
|
421
434
|
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
const
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
435
|
+
// 错误响应体({"error":{...}})直接抛出,交给调用方转成 reject
|
|
436
|
+
function checkError(result) {
|
|
437
|
+
if (Array.isArray(result)) {
|
|
438
|
+
for (const item of result) {
|
|
439
|
+
if (item && item.error) throw item.error;
|
|
440
|
+
}
|
|
441
|
+
return result;
|
|
442
|
+
}
|
|
443
|
+
if (result && result.error) throw result.error;
|
|
444
|
+
return result;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function parseString (value) {
|
|
448
|
+
let text = String(value == null ? "" : value).trim();
|
|
449
|
+
|
|
450
|
+
// 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
|
|
451
|
+
// #doc:done
|
|
452
|
+
text = text.replace(/data:\s*\[DONE\]$/, "").trim();
|
|
453
|
+
if (text === "" || text === "[DONE]") return [];
|
|
454
|
+
// #end
|
|
455
|
+
|
|
456
|
+
// 单条:带 data: 前缀或裸 JSON
|
|
457
|
+
let single = tryParse(stripDataPrefix(text)) || tryParse(text);
|
|
458
|
+
if (single) return checkError(single.value);
|
|
459
|
+
|
|
460
|
+
// 多条 SSE 事件,以 "\n\ndata: " 分隔
|
|
461
|
+
// #doc:multi
|
|
462
|
+
const parts = text.split(/\r?\n\r?\ndata: /);
|
|
463
|
+
if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
|
|
464
|
+
// #end
|
|
465
|
+
|
|
466
|
+
// NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
|
|
467
|
+
const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
|
|
468
|
+
if (lines.length > 1) return checkError(lines.map(line => parseOne(line, text)));
|
|
469
|
+
|
|
470
|
+
throw new SyntaxError("模型返回无法解析:" + text.slice(0, 120));
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// 解析 LLM 返回的推理内容(reasoning / reasoning_content)
|
|
474
|
+
// 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
|
|
475
|
+
function parseReasoning(reasoning, content) {
|
|
476
|
+
if (!/<\/think>/.test(reasoning)) return reasoning;
|
|
477
|
+
|
|
478
|
+
const parts = reasoning.split("</think>");
|
|
479
|
+
const thinkPart = parts[0].replace("<think>", "");
|
|
480
|
+
return {
|
|
481
|
+
reasoning: thinkPart,
|
|
482
|
+
content: parts[1] + (content || "")
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
const OPEN = "<think>";
|
|
487
|
+
const CLOSE = "</think>";
|
|
488
|
+
|
|
489
|
+
// 计算文本尾部与标签前缀的最长匹配长度
|
|
490
|
+
// 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
|
|
491
|
+
// #doc:partial
|
|
492
|
+
function partialTagLength(text, tag) {
|
|
493
|
+
const max = Math.min(tag.length - 1, text.length);
|
|
494
|
+
for (let len = max; len > 0; len--) {
|
|
495
|
+
if (text.endsWith(tag.slice(0, len))) return len;
|
|
496
|
+
}
|
|
497
|
+
return 0;
|
|
498
|
+
// #end
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
|
|
502
|
+
// 这里把它剥离出来:思考片段归 thinkback,其余归正文
|
|
503
|
+
// 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
|
|
504
|
+
// 返回 { thinking, content }
|
|
505
|
+
function extractThink(content, state) {
|
|
506
|
+
const buf = (state.thinkBuf || "") + content;
|
|
507
|
+
state.thinkBuf = "";
|
|
508
|
+
|
|
509
|
+
// 正处于思考块内:寻找 </think>
|
|
510
|
+
if (state.inThink) {
|
|
511
|
+
const end = buf.indexOf(CLOSE);
|
|
512
|
+
if (end === -1) {
|
|
513
|
+
const hold = partialTagLength(buf, CLOSE);
|
|
514
|
+
state.thinkBuf = buf.slice(buf.length - hold);
|
|
515
|
+
return { thinking: buf.slice(0, buf.length - hold), content: "" };
|
|
516
|
+
}
|
|
517
|
+
state.inThink = false;
|
|
518
|
+
const rest = extractThink(buf.slice(end + CLOSE.length), state);
|
|
519
|
+
return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// 正常正文:寻找 <think>
|
|
523
|
+
const start = buf.indexOf(OPEN);
|
|
524
|
+
if (start === -1) {
|
|
525
|
+
const hold = partialTagLength(buf, OPEN);
|
|
526
|
+
state.thinkBuf = buf.slice(buf.length - hold);
|
|
527
|
+
return { thinking: "", content: buf.slice(0, buf.length - hold) };
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
const end = buf.indexOf(CLOSE, start);
|
|
531
|
+
if (end !== -1) {
|
|
532
|
+
const rest = extractThink(buf.slice(end + CLOSE.length), state);
|
|
533
|
+
return {
|
|
534
|
+
thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
|
|
535
|
+
content: buf.slice(0, start) + rest.content
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// 有 <think> 无 </think>:进入思考态
|
|
540
|
+
state.inThink = true;
|
|
541
|
+
const body = buf.slice(start + OPEN.length);
|
|
542
|
+
const hold = partialTagLength(body, CLOSE);
|
|
543
|
+
state.thinkBuf = body.slice(body.length - hold);
|
|
544
|
+
return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
|
|
548
|
+
function flushThink(state) {
|
|
549
|
+
const buf = state.thinkBuf || "";
|
|
550
|
+
state.thinkBuf = "";
|
|
551
|
+
return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// 新调用的槽位:保留原始字段形状,只保证 function.arguments 是字符串
|
|
555
|
+
function normalizeCall(toolCall) {
|
|
556
|
+
const fn = toolCall.function || {};
|
|
557
|
+
return {
|
|
558
|
+
...toolCall,
|
|
559
|
+
function: {
|
|
560
|
+
...fn,
|
|
561
|
+
arguments: typeof fn.arguments === "string" ? fn.arguments : ""
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// 续片:按 index 优先归并,否则追加到最后一个槽位
|
|
567
|
+
// #doc:merge
|
|
568
|
+
function mergeToolCall(state, toolCall) {
|
|
569
|
+
if (!state._toolSlots) state._toolSlots = new Map();
|
|
570
|
+
|
|
571
|
+
const calls = state.tool_calls;
|
|
572
|
+
const index = typeof toolCall.index === "number" ? toolCall.index : null;
|
|
573
|
+
const hasId = typeof toolCall.id === "string" && toolCall.id !== "";
|
|
574
|
+
|
|
575
|
+
// 带 id 视为新调用;同 id 重复下发时复用已有槽位
|
|
576
|
+
if (hasId) {
|
|
577
|
+
const exist = calls.find(call => call.id === toolCall.id);
|
|
578
|
+
if (exist) {
|
|
579
|
+
appendArguments(exist, toolCall);
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
const slot = normalizeCall(toolCall);
|
|
583
|
+
calls.push(slot);
|
|
584
|
+
if (index !== null) state._toolSlots.set(index, slot);
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
let slot = index !== null ? state._toolSlots.get(index) : null;
|
|
589
|
+
if (!slot && calls.length) slot = calls[calls.length - 1];
|
|
590
|
+
|
|
591
|
+
// 首片就没有 id:建占位槽位,后续分片补齐参数
|
|
592
|
+
if (!slot) {
|
|
593
|
+
slot = normalizeCall(toolCall);
|
|
594
|
+
calls.push(slot);
|
|
595
|
+
if (index !== null) state._toolSlots.set(index, slot);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
appendArguments(slot, toolCall);
|
|
600
|
+
// #end
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function appendArguments(slot, toolCall) {
|
|
604
|
+
const fn = toolCall.function || {};
|
|
605
|
+
if (fn.name && !slot.function.name) slot.function.name = fn.name;
|
|
606
|
+
if (typeof fn.arguments === "string") slot.function.arguments += fn.arguments;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
// 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
|
|
610
|
+
function handleChoices(choices, { logback, thinkback }, state) {
|
|
611
|
+
if (!Array.isArray(choices)) return;
|
|
612
|
+
|
|
613
|
+
for (let i = 0; i < choices.length; i++) {
|
|
614
|
+
const delta = choices[i].delta;
|
|
615
|
+
|
|
616
|
+
// 推理内容(reasoning / reasoning_content 字段)
|
|
617
|
+
let reasoning = delta.reasoning || delta.reasoning_content;
|
|
618
|
+
if (reasoning) {
|
|
619
|
+
const parsed = parseReasoning(reasoning, delta.content);
|
|
620
|
+
if (typeof parsed === "object") {
|
|
621
|
+
reasoning = parsed.reasoning;
|
|
622
|
+
delta.content = parsed.content;
|
|
623
|
+
}
|
|
624
|
+
if (thinkback) thinkback(reasoning);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
|
|
628
|
+
if (delta.content) {
|
|
629
|
+
const extracted = extractThink(delta.content, state);
|
|
630
|
+
if (extracted.thinking && thinkback) thinkback(extracted.thinking);
|
|
631
|
+
if (extracted.content) {
|
|
632
|
+
if (logback) logback(extracted.content);
|
|
633
|
+
state.content += extracted.content;
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// 工具调用分片
|
|
638
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
639
|
+
for (const toolCall of delta.tool_calls) {
|
|
640
|
+
mergeToolCall(state, toolCall);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
|
|
647
|
+
function flushThinkBuffer(state, { logback, thinkback }) {
|
|
648
|
+
const flushed = flushThink(state);
|
|
649
|
+
if (flushed.thinking && thinkback) thinkback(flushed.thinking);
|
|
650
|
+
if (flushed.content) {
|
|
651
|
+
if (logback) logback(flushed.content);
|
|
652
|
+
state.content += flushed.content;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// 统一把各种错误形态收敛成 Error,保证 Promise 一定 settle
|
|
657
|
+
function toError(value, fallback) {
|
|
658
|
+
if (value instanceof Error) return value;
|
|
659
|
+
if (value && typeof value.message === "string") return new Error(value.message);
|
|
660
|
+
try {
|
|
661
|
+
return new Error(String(value));
|
|
662
|
+
} catch (e) {
|
|
663
|
+
return new Error(fallback || "模型请求失败");
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// HTTP 错误:尽量带出响应体里的 error.message,方便定位
|
|
668
|
+
function errorFromHttp(meta, body) {
|
|
669
|
+
const status = meta && meta.status;
|
|
670
|
+
let detail = "";
|
|
671
|
+
|
|
672
|
+
if (body) {
|
|
673
|
+
try {
|
|
674
|
+
const parsed = JSON.parse(body);
|
|
675
|
+
const raw = parsed && parsed.error;
|
|
676
|
+
detail = (raw && (raw.message || raw)) || "";
|
|
677
|
+
} catch (e) {
|
|
678
|
+
detail = String(body).slice(0, 200);
|
|
679
|
+
}
|
|
680
|
+
if (detail && typeof detail !== "string") detail = JSON.stringify(detail);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
function completions(params, logback, thinkback) {
|
|
687
|
+
return new Promise((resolve, reject) => {
|
|
688
|
+
|
|
689
|
+
// #doc:state
|
|
690
|
+
const state = { content: "", tool_calls: [] };
|
|
691
|
+
const callbacks = { logback, thinkback };
|
|
692
|
+
|
|
693
|
+
let buffer = "";
|
|
694
|
+
let httpError = null;
|
|
695
|
+
let streamError = null;
|
|
696
|
+
let settled = false;
|
|
697
|
+
|
|
698
|
+
const finish = (fn, value) => {
|
|
699
|
+
if (settled) return;
|
|
700
|
+
settled = true;
|
|
701
|
+
fn(value);
|
|
702
|
+
};
|
|
703
|
+
const fail = value => finish(reject, toError(value, "模型请求失败"));
|
|
704
|
+
// #end
|
|
705
|
+
|
|
706
|
+
// #doc:body
|
|
707
|
+
const body = {
|
|
708
|
+
model: this.model,
|
|
709
|
+
messages: params.messages,
|
|
710
|
+
tools: params.tools ? params.tools.map(tool => tool.description) : [],
|
|
711
|
+
stream: params.stream,
|
|
712
|
+
};
|
|
713
|
+
const temperature = params.temperature != null ? params.temperature : this.temperature;
|
|
714
|
+
const topP = params.topP != null ? params.topP : this.topP;
|
|
715
|
+
const maxTokens = params.maxTokens != null ? params.maxTokens : this.maxTokens;
|
|
716
|
+
if (temperature != null) body.temperature = temperature;
|
|
717
|
+
if (topP != null) body.top_p = topP;
|
|
718
|
+
if (maxTokens != null) body.max_tokens = maxTokens;
|
|
719
|
+
// #end
|
|
720
|
+
|
|
721
|
+
fetch$1({
|
|
722
|
+
url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
|
|
723
|
+
method: "POST",
|
|
724
|
+
headers: {
|
|
725
|
+
"Authorization": `Bearer ${this.apiKey}`,
|
|
726
|
+
"Content-Type": "application/json",
|
|
727
|
+
},
|
|
728
|
+
body: JSON.stringify(body),
|
|
729
|
+
timeout: params.timeout != null ? params.timeout : this.timeout,
|
|
730
|
+
signal: params.signal
|
|
731
|
+
// #end
|
|
732
|
+
}).then(res => {
|
|
733
|
+
|
|
734
|
+
// 非 2xx:非流式等错误体读完再判,流式直接中断
|
|
735
|
+
res.on("http-error", meta => {
|
|
736
|
+
httpError = meta;
|
|
737
|
+
if (params.stream) fail(errorFromHttp(meta));
|
|
738
|
+
});
|
|
739
|
+
|
|
740
|
+
// 数据流
|
|
741
|
+
// #doc:stream
|
|
742
|
+
res.on("data", chunk => {
|
|
743
|
+
if (settled) return;
|
|
744
|
+
if (!params.stream) {
|
|
745
|
+
buffer += chunk;
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
let parsed;
|
|
749
|
+
try {
|
|
750
|
+
parsed = parseString(chunk.toString());
|
|
751
|
+
} catch (e) {
|
|
752
|
+
streamError = e;
|
|
753
|
+
fail(e);
|
|
754
|
+
// #end
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
try {
|
|
758
|
+
const items = Array.isArray(parsed) ? parsed : [parsed];
|
|
759
|
+
for (const item of items) handleChoices(item.choices, callbacks, state);
|
|
760
|
+
} catch (e) {
|
|
761
|
+
fail(e);
|
|
762
|
+
}
|
|
763
|
+
});
|
|
764
|
+
|
|
765
|
+
// 结束
|
|
766
|
+
res.on("end", () => {
|
|
767
|
+
if (!params.stream) {
|
|
768
|
+
if (httpError) {
|
|
769
|
+
fail(errorFromHttp(httpError, buffer));
|
|
770
|
+
return;
|
|
771
|
+
}
|
|
772
|
+
try {
|
|
773
|
+
const parsed = parseString(buffer);
|
|
774
|
+
const choices = parsed && parsed.choices;
|
|
775
|
+
if (!choices || !choices[0] || !choices[0].message) {
|
|
776
|
+
throw new Error("模型响应缺少 choices[0].message");
|
|
777
|
+
}
|
|
778
|
+
handleChoices([{ delta: choices[0].message }], callbacks, state);
|
|
779
|
+
} catch (e) {
|
|
780
|
+
fail(e);
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
} else if (streamError) {
|
|
784
|
+
fail(streamError);
|
|
785
|
+
return;
|
|
786
|
+
} else if (httpError) {
|
|
787
|
+
fail(errorFromHttp(httpError));
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// 冲刷 <think> 标签截断残留
|
|
792
|
+
flushThinkBuffer(state, callbacks);
|
|
793
|
+
finish(resolve, { content: state.content, tool_calls: state.tool_calls });
|
|
794
|
+
});
|
|
795
|
+
|
|
796
|
+
res.on("error", err => fail(err));
|
|
797
|
+
}).catch(err => fail(err));
|
|
798
|
+
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// #doc:ctor
|
|
803
|
+
function Model(fields) {
|
|
804
|
+
this.model = fields.model;
|
|
805
|
+
this.apiKey = fields.apiKey;
|
|
806
|
+
this.baseURL = fields.baseURL;
|
|
807
|
+
|
|
808
|
+
// 可选请求参数:显式传入才写进请求体,保持旧行为不变
|
|
809
|
+
this.temperature = fields.temperature;
|
|
810
|
+
this.topP = fields.topP;
|
|
811
|
+
this.maxTokens = fields.maxTokens;
|
|
812
|
+
this.timeout = fields.timeout;
|
|
813
|
+
// #end
|
|
479
814
|
}
|
|
480
815
|
|
|
481
|
-
function Model(fields) {
|
|
482
|
-
this.model = fields.model;
|
|
483
|
-
this.apiKey = fields.apiKey;
|
|
484
|
-
this.baseURL = fields.baseURL;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
816
|
Model.prototype.completions = completions;
|
|
488
817
|
|
|
489
|
-
/**
|
|
490
|
-
* 根据模型返回的 tool_calls,依次在 _this.tools 中查找匹配的工具并执行,
|
|
491
|
-
* 返回与 tool_calls 等长的结果数组(同步值/异步值都会被规范化)。
|
|
492
|
-
*
|
|
493
|
-
* @param {Object} _this Agent 实例
|
|
494
|
-
* @param {Array} tool_calls 模型返回的工具调用列表
|
|
495
|
-
* @returns {Promise<Array>} 每个工具的执行结果,未匹配到的槽位会被填入错误说明字符串
|
|
496
|
-
*/
|
|
497
|
-
function callFuns(_this, tool_calls) {
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
)
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
//
|
|
517
|
-
|
|
518
|
-
}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
818
|
+
/**
|
|
819
|
+
* 根据模型返回的 tool_calls,依次在 _this.tools 中查找匹配的工具并执行,
|
|
820
|
+
* 返回与 tool_calls 等长的结果数组(同步值/异步值都会被规范化)。
|
|
821
|
+
*
|
|
822
|
+
* @param {Object} _this Agent 实例
|
|
823
|
+
* @param {Array} tool_calls 模型返回的工具调用列表
|
|
824
|
+
* @returns {Promise<Array>} 每个工具的执行结果,未匹配到的槽位会被填入错误说明字符串
|
|
825
|
+
*/
|
|
826
|
+
function callFuns(_this, tool_calls) {
|
|
827
|
+
|
|
828
|
+
// #doc:map
|
|
829
|
+
const tasks = (tool_calls || []).map(call => {
|
|
830
|
+
const fn = (call && call.function) || {};
|
|
831
|
+
const tool = (_this.tools || []).find(
|
|
832
|
+
t => t.description.function.name === fn.name
|
|
833
|
+
);
|
|
834
|
+
|
|
835
|
+
if (!tool) {
|
|
836
|
+
return Promise.resolve("工具" + fn.name + "不存在");
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
if (typeof tool.execute !== "function") {
|
|
840
|
+
return Promise.resolve("工具" + fn.name + "缺少 execute");
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
let args;
|
|
844
|
+
try {
|
|
845
|
+
// 无参工具:arguments 为空字符串或缺失时按 {} 处理
|
|
846
|
+
args = typeof fn.arguments === "string" && fn.arguments.trim() ? JSON.parse(fn.arguments) : {};
|
|
847
|
+
} catch (e) {
|
|
848
|
+
return Promise.resolve("参数解析失败:" + e);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
try {
|
|
852
|
+
// 工具内部报错(含同步抛错)也不要阻断对话,转成字符串继续往下走
|
|
853
|
+
return Promise.resolve(tool.execute(args)).catch(e => "运行出错:" + e);
|
|
854
|
+
} catch (e) {
|
|
855
|
+
return Promise.resolve("运行出错:" + e);
|
|
856
|
+
// #end
|
|
857
|
+
}
|
|
858
|
+
});
|
|
859
|
+
|
|
860
|
+
return Promise.all(tasks);
|
|
523
861
|
}
|
|
524
862
|
|
|
525
|
-
/**
|
|
526
|
-
* 把一次工具调用的执行结果转成 tool 消息。
|
|
527
|
-
*/
|
|
528
|
-
function toToolMessage(call, value) {
|
|
529
|
-
return {
|
|
530
|
-
role: "tool",
|
|
531
|
-
tool_call_id: call.id,
|
|
532
|
-
tool_name: call.function.name,
|
|
533
|
-
content: typeof value === "string" ? value : (JSON.stringify(value) + "")
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
/**
|
|
538
|
-
* 把模型响应按 role 追加到 messages,返回是否还有工具调用需要下一轮处理。
|
|
539
|
-
*/
|
|
540
|
-
function appendAssistantMessage(messages, result) {
|
|
541
|
-
if (result.content) {
|
|
542
|
-
messages.push({ role: "assistant", content: result.content });
|
|
543
|
-
}
|
|
544
|
-
if (result.tool_calls && result.tool_calls.length > 0) {
|
|
545
|
-
messages.push({ role: "assistant", tool_calls: result.tool_calls });
|
|
546
|
-
return true;
|
|
547
|
-
}
|
|
548
|
-
return false;
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
/**
|
|
552
|
-
* 执行模型对话循环:
|
|
553
|
-
* 1. 调用模型获取响应
|
|
554
|
-
* 2. 若返回工具调用,依次执行工具并将结果追加到 messages,继续循环
|
|
555
|
-
* 3. 否则将最终内容 resolve 给调用方
|
|
556
|
-
*/
|
|
557
|
-
async function runConversation(_this, messages, logback, thinkback) {
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
const
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
}
|
|
577
|
-
|
|
863
|
+
/**
|
|
864
|
+
* 把一次工具调用的执行结果转成 tool 消息。
|
|
865
|
+
*/
|
|
866
|
+
function toToolMessage(call, value) {
|
|
867
|
+
return {
|
|
868
|
+
role: "tool",
|
|
869
|
+
tool_call_id: call.id,
|
|
870
|
+
tool_name: call.function.name,
|
|
871
|
+
content: typeof value === "string" ? value : (JSON.stringify(value) + "")
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
/**
|
|
876
|
+
* 把模型响应按 role 追加到 messages,返回是否还有工具调用需要下一轮处理。
|
|
877
|
+
*/
|
|
878
|
+
function appendAssistantMessage(messages, result) {
|
|
879
|
+
if (result.content) {
|
|
880
|
+
messages.push({ role: "assistant", content: result.content });
|
|
881
|
+
}
|
|
882
|
+
if (result.tool_calls && result.tool_calls.length > 0) {
|
|
883
|
+
messages.push({ role: "assistant", tool_calls: result.tool_calls });
|
|
884
|
+
return true;
|
|
885
|
+
}
|
|
886
|
+
return false;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* 执行模型对话循环:
|
|
891
|
+
* 1. 调用模型获取响应
|
|
892
|
+
* 2. 若返回工具调用,依次执行工具并将结果追加到 messages,继续循环
|
|
893
|
+
* 3. 否则将最终内容 resolve 给调用方
|
|
894
|
+
*/
|
|
895
|
+
async function runConversation(_this, messages, logback, thinkback) {
|
|
896
|
+
|
|
897
|
+
// maxSteps 为 0 表示不限制
|
|
898
|
+
// #doc:loop
|
|
899
|
+
const maxSteps = _this.maxSteps > 0 ? _this.maxSteps : Infinity;
|
|
900
|
+
|
|
901
|
+
for (let step = 1; step <= maxSteps; step++) {
|
|
902
|
+
|
|
903
|
+
const result = await _this.model.completions({
|
|
904
|
+
messages,
|
|
905
|
+
tools: _this.tools,
|
|
906
|
+
stream: _this.stream,
|
|
907
|
+
signal: _this.signal || void 0,
|
|
908
|
+
}, logback, thinkback);
|
|
909
|
+
|
|
910
|
+
const hasToolCalls = appendAssistantMessage(messages, result);
|
|
911
|
+
|
|
912
|
+
if (!hasToolCalls) {
|
|
913
|
+
return result.content;
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
const toolResults = await callFuns(_this, result.tool_calls);
|
|
917
|
+
|
|
918
|
+
result.tool_calls.forEach((call, i) => {
|
|
919
|
+
messages.push(toToolMessage(call, toolResults[i]));
|
|
920
|
+
});
|
|
921
|
+
// #end
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
throw new Error("工具调用步骤超过 maxSteps 上限:" + _this.maxSteps);
|
|
578
925
|
}
|
|
579
926
|
|
|
580
927
|
function initOption(setOption, defaultOption) {
|
|
@@ -585,77 +932,138 @@
|
|
|
585
932
|
return defaultOption;
|
|
586
933
|
}
|
|
587
934
|
|
|
588
|
-
function CreateTool(ms) {
|
|
589
|
-
this.ms = ms;
|
|
590
|
-
}
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
result
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
935
|
+
function CreateTool(ms) {
|
|
936
|
+
this.ms = ms;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* 包装一个工具。
|
|
941
|
+
*
|
|
942
|
+
* @param {object} input description + 可选 execute(缺省即前端工具)
|
|
943
|
+
* @param {object} [options] { timeout } 前端工具等待页面回传的超时毫秒数,0 表示不限制
|
|
944
|
+
*/
|
|
945
|
+
CreateTool.prototype.create = function ({ description, execute }, options) {
|
|
946
|
+
let _this = this;
|
|
947
|
+
const timeout = options && options.timeout > 0 ? options.timeout : 0;
|
|
948
|
+
|
|
949
|
+
return {
|
|
950
|
+
description,
|
|
951
|
+
execute: async function (args) {
|
|
952
|
+
let toolInfo = {
|
|
953
|
+
type: "tool-call",
|
|
954
|
+
status: "pending",
|
|
955
|
+
id: Date.now().toString() + "_" + Math.random().toString(36).substring(2).toUpperCase(),
|
|
956
|
+
name: description.function.name,
|
|
957
|
+
caller: execute ? "backend" : "frontend",
|
|
958
|
+
args
|
|
959
|
+
};
|
|
960
|
+
|
|
961
|
+
// 后端工具调用
|
|
962
|
+
// #doc:backend
|
|
963
|
+
if (execute) {
|
|
964
|
+
_this.ms.send(toolInfo); // 开始调用工具
|
|
965
|
+
|
|
966
|
+
let result, status;
|
|
967
|
+
try {
|
|
968
|
+
result = await execute(args);
|
|
969
|
+
status = "success"; // 调用成功
|
|
970
|
+
} catch (error) {
|
|
971
|
+
result = error;
|
|
972
|
+
status = "error"; // 调用失败
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
_this.ms.send(initOption({ // 结束调用工具
|
|
976
|
+
status,
|
|
977
|
+
result
|
|
978
|
+
}, toolInfo));
|
|
979
|
+
|
|
980
|
+
// 失败继续抛出,由 callFuns 统一转成给模型的错误文本
|
|
981
|
+
if (status === "error") throw result;
|
|
982
|
+
|
|
983
|
+
return result;
|
|
984
|
+
// #end
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// 前端工具调用
|
|
988
|
+
let settle = null;
|
|
989
|
+
let timer = null;
|
|
990
|
+
|
|
991
|
+
const done = () => {
|
|
992
|
+
if (timer) { clearTimeout(timer); timer = null; }
|
|
993
|
+
delete globalThis[toolInfo.id];
|
|
994
|
+
};
|
|
995
|
+
|
|
996
|
+
// 先建好 Promise 再推事件,避免页面同步回传时 _resolve 还不存在
|
|
997
|
+
const waiting = new Promise((resolve, reject) => {
|
|
998
|
+
settle = { resolve, reject };
|
|
999
|
+
});
|
|
1000
|
+
|
|
1001
|
+
globalThis[toolInfo.id] = function (result, status) {
|
|
1002
|
+
if (!settle) return;
|
|
1003
|
+
const current = settle;
|
|
1004
|
+
settle = null;
|
|
1005
|
+
done();
|
|
1006
|
+
if (status === "error") current.reject(result);
|
|
1007
|
+
else current.resolve(result);
|
|
1008
|
+
};
|
|
1009
|
+
|
|
1010
|
+
if (timeout > 0) {
|
|
1011
|
+
timer = setTimeout(() => {
|
|
1012
|
+
if (!settle) return;
|
|
1013
|
+
const current = settle;
|
|
1014
|
+
settle = null;
|
|
1015
|
+
done();
|
|
1016
|
+
current.reject(new Error("前端工具调用超时:" + description.function.name));
|
|
1017
|
+
}, timeout);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
try {
|
|
1021
|
+
_this.ms.send(toolInfo); // 开始调用工具
|
|
1022
|
+
} catch (error) {
|
|
1023
|
+
settle = null;
|
|
1024
|
+
done();
|
|
1025
|
+
throw error;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
return waiting;
|
|
1029
|
+
}
|
|
1030
|
+
};
|
|
643
1031
|
};
|
|
644
1032
|
|
|
645
|
-
function Agent(option) {
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
this.
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
1033
|
+
function Agent(option) {
|
|
1034
|
+
option = option || {};
|
|
1035
|
+
|
|
1036
|
+
// #doc:ctor
|
|
1037
|
+
this.model = new Model(option.model);
|
|
1038
|
+
this.tools = option.tools || [];
|
|
1039
|
+
this.systemPrompt = option.systemPrompt || "";
|
|
1040
|
+
this.stream = option.stream || false;
|
|
1041
|
+
|
|
1042
|
+
// 工具调用循环上限,0 表示不限制
|
|
1043
|
+
this.maxSteps = option.maxSteps > 0 ? option.maxSteps : 0;
|
|
1044
|
+
|
|
1045
|
+
// 取消信号,透传给每次模型请求
|
|
1046
|
+
this.signal = option.signal || null;
|
|
1047
|
+
// #end
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
Agent.prototype.generate = function (messages, logback, thinkback) {
|
|
1051
|
+
if (!Array.isArray(messages)) messages = [];
|
|
1052
|
+
|
|
1053
|
+
// 注入 system 提示词;首条已是同内容时跳过,避免复用同一数组时累积(原地修改,保持契约)
|
|
1054
|
+
// #doc:system
|
|
1055
|
+
if (this.systemPrompt) {
|
|
1056
|
+
let first = messages[0];
|
|
1057
|
+
if (!first || first.role !== "system" || first.content !== this.systemPrompt) {
|
|
1058
|
+
messages.unshift({
|
|
1059
|
+
role: "system",
|
|
1060
|
+
content: this.systemPrompt
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
// #end
|
|
1065
|
+
|
|
1066
|
+
return runConversation(this, messages, logback, thinkback);
|
|
659
1067
|
};
|
|
660
1068
|
|
|
661
1069
|
exports.Agent = Agent;
|