@auipage/model 0.2.0-alpha.0 → 0.2.0-alpha.2
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 +6 -5
- package/dist/index.cjs +2 -0
- package/dist/index.js +671 -734
- package/dist/index.min.js +2 -0
- package/package.json +23 -5
- package/src/completions.js +1 -1
- package/dist/package.json +0 -3
package/dist/index.js
CHANGED
|
@@ -1,820 +1,757 @@
|
|
|
1
|
-
/*! @auipage/model v0.2.0-alpha.
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
})(this, (function (exports) { 'use strict';
|
|
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
|
-
// #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
|
-
}
|
|
1
|
+
/*! @auipage/model v0.2.0-alpha.2 */
|
|
2
|
+
// 极简 EventEmitter:on / off / emit,供 Response 复用
|
|
3
|
+
class Emitter {
|
|
4
|
+
constructor() {
|
|
5
|
+
this._events = Object.create(null);
|
|
46
6
|
}
|
|
47
7
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
|
-
}
|
|
8
|
+
on(event, listener) {
|
|
9
|
+
if (typeof listener !== 'function') return this;
|
|
10
|
+
const list = this._events[event] || (this._events[event] = []);
|
|
11
|
+
list.push(listener);
|
|
12
|
+
return this;
|
|
13
|
+
}
|
|
64
14
|
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
15
|
+
off(event, listener) {
|
|
16
|
+
const list = this._events[event];
|
|
17
|
+
if (!list) return this;
|
|
18
|
+
const idx = list.indexOf(listener);
|
|
19
|
+
if (idx >= 0) list.splice(idx, 1);
|
|
20
|
+
if (list.length === 0) delete this._events[event];
|
|
21
|
+
return this;
|
|
22
|
+
}
|
|
23
|
+
emit(event, ...args) {
|
|
24
|
+
const list = this._events[event];
|
|
25
|
+
if (!list || list.length === 0) return false;
|
|
26
|
+
// 复制一份再触发,避免 off 回调过程中影响本次派发
|
|
27
|
+
for (const fn of list.slice()) {
|
|
28
|
+
try {
|
|
29
|
+
fn.apply(null, args);
|
|
30
|
+
} catch (e) {
|
|
31
|
+
// 单个监听器异常不影响其它监听器,也不再冒泡成进程级异常
|
|
32
|
+
console.error(e);
|
|
74
33
|
}
|
|
75
|
-
return this;
|
|
76
|
-
// #end
|
|
77
34
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
|
|
40
|
+
|
|
41
|
+
class Response extends Emitter {
|
|
42
|
+
constructor() {
|
|
43
|
+
super();
|
|
44
|
+
this.status = 0;
|
|
45
|
+
this.headers = {};
|
|
46
|
+
this.ok = false;
|
|
47
|
+
this._done = false; // 标记是否已经 end/error,防止重复触发
|
|
48
|
+
this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
|
|
49
|
+
this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
|
|
50
|
+
this._cancel = null; // 由 createFetch 注入,用于中断底层请求
|
|
51
|
+
this._errorPending = null; // 消费者还没来得及注册时就发生的错误,注册后补发
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 注册监听;error 是一次性终态,注册时若已发生则补发
|
|
55
|
+
on(event, listener) {
|
|
56
|
+
super.on(event, listener);
|
|
57
|
+
if (event === 'error' && this._errorPending) {
|
|
58
|
+
const err = this._errorPending;
|
|
59
|
+
this._errorPending = null;
|
|
60
|
+
// 异步补发,避免在注册栈里同步回调
|
|
61
|
+
queueMicrotask(() => this.emit('error', err));
|
|
83
62
|
}
|
|
63
|
+
return this;
|
|
64
|
+
}
|
|
84
65
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
return headers[name];
|
|
91
|
-
}
|
|
66
|
+
// 主动取消请求,失败统一从 error 事件返回
|
|
67
|
+
cancel() {
|
|
68
|
+
if (this._cancel) this._cancel();
|
|
69
|
+
return this;
|
|
70
|
+
}
|
|
92
71
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
72
|
+
// 统一读取响应头:浏览器是 Headers 对象,Node 是普通对象
|
|
73
|
+
header(name) {
|
|
74
|
+
const headers = this.headers;
|
|
75
|
+
if (!headers) return undefined;
|
|
76
|
+
if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
|
|
77
|
+
return headers[name];
|
|
78
|
+
}
|
|
96
79
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
this._sseBuffer += payload;
|
|
80
|
+
// 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
|
|
81
|
+
_push(type, payload) {
|
|
82
|
+
if (this._done && type !== 'error') return;
|
|
101
83
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
84
|
+
// SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
|
|
85
|
+
if (type === 'data' && this._sseMode) {
|
|
86
|
+
this._sseBuffer += payload;
|
|
105
87
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
this.emit('data', payload);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
return;
|
|
113
|
-
// #end
|
|
114
|
-
}
|
|
88
|
+
// 按 \n\n 分割出完整事件,最后一段可能不完整
|
|
89
|
+
const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
|
|
90
|
+
this._sseBuffer = parts.pop();
|
|
115
91
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
if (
|
|
119
|
-
|
|
120
|
-
if (payload !== null) {
|
|
121
|
-
this.emit('data', payload);
|
|
122
|
-
}
|
|
123
|
-
this._sseBuffer = '';
|
|
92
|
+
for (const part of parts) {
|
|
93
|
+
const payload = this._extractSSEData(part);
|
|
94
|
+
if (payload !== null) {
|
|
95
|
+
this.emit('data', payload);
|
|
124
96
|
}
|
|
125
|
-
this._done = true;
|
|
126
97
|
}
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (type === 'end') {
|
|
102
|
+
// SSE 模式下,flush 缓冲区残留
|
|
103
|
+
if (this._sseMode && this._sseBuffer.trim()) {
|
|
104
|
+
const payload = this._extractSSEData(this._sseBuffer);
|
|
105
|
+
if (payload !== null) {
|
|
106
|
+
this.emit('data', payload);
|
|
134
107
|
}
|
|
108
|
+
this._sseBuffer = '';
|
|
135
109
|
}
|
|
136
|
-
|
|
137
|
-
this.emit(type, payload);
|
|
110
|
+
this._done = true;
|
|
138
111
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
dataLines.push(line.replace(/^data:\s*/, '').replace(/\r$/, ''));
|
|
147
|
-
}
|
|
112
|
+
if (type === 'error') {
|
|
113
|
+
this._done = true;
|
|
114
|
+
const listeners = this._events && this._events['error'];
|
|
115
|
+
if (!listeners || listeners.length === 0) {
|
|
116
|
+
// 消费者还没注册监听,先缓存,注册时补发
|
|
117
|
+
this._errorPending = payload;
|
|
118
|
+
return;
|
|
148
119
|
}
|
|
149
|
-
if (dataLines.length === 0) return null;
|
|
150
|
-
return dataLines.join('\n');
|
|
151
|
-
// #end
|
|
152
120
|
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// fetch 工厂:注入 adapter,返回对外的 fetch 函数
|
|
156
121
|
|
|
157
|
-
|
|
158
|
-
function isPlainBody(body) {
|
|
159
|
-
return Object.prototype.toString.call(body) === '[object Object]';
|
|
122
|
+
this.emit(type, payload);
|
|
160
123
|
}
|
|
161
124
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
125
|
+
// 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
|
|
126
|
+
_extractSSEData(raw) {
|
|
127
|
+
const dataLines = [];
|
|
128
|
+
for (const line of raw.split('\n')) {
|
|
129
|
+
if (line.startsWith('data:')) {
|
|
130
|
+
dataLines.push(line.replace(/^data:\s*/, '').replace(/\r$/, ''));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (dataLines.length === 0) return null;
|
|
134
|
+
return dataLines.join('\n');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// fetch 工厂:注入 adapter,返回对外的 fetch 函数
|
|
139
|
+
|
|
140
|
+
// 只有普通对象才自动 JSON 序列化,ArrayBufferView / Blob / FormData 等保持原样
|
|
141
|
+
function isPlainBody(body) {
|
|
142
|
+
return Object.prototype.toString.call(body) === '[object Object]';
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function createFetch(adapter) {
|
|
146
|
+
return function fetch(options) {
|
|
147
|
+
// 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
|
|
148
|
+
return new Promise((resolve, reject) => {
|
|
149
|
+
if (!options || !options.url) {
|
|
150
|
+
reject(new Error('fetch: options.url is required'));
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
176
153
|
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
154
|
+
// 请求体是普通对象时自动序列化,避免 Node 端 req.write(object) 抛 TypeError
|
|
155
|
+
if (isPlainBody(options.body)) {
|
|
156
|
+
options = Object.assign({}, options, { body: JSON.stringify(options.body) });
|
|
157
|
+
}
|
|
181
158
|
|
|
182
|
-
|
|
159
|
+
const response = new Response();
|
|
160
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
161
|
+
let timer = null;
|
|
162
|
+
let failed = false;
|
|
183
163
|
|
|
184
|
-
|
|
185
|
-
// 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
|
|
186
|
-
queueMicrotask(() => resolve(response));
|
|
187
|
-
// #end
|
|
164
|
+
response._cancel = () => { if (controller) controller.abort(); };
|
|
188
165
|
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
166
|
+
// adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
|
|
167
|
+
// 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
|
|
168
|
+
queueMicrotask(() => resolve(response));
|
|
169
|
+
const clearTimer = () => {
|
|
170
|
+
if (timer) {
|
|
171
|
+
clearTimeout(timer);
|
|
172
|
+
timer = null;
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
const hooks = {
|
|
176
|
+
onResponse(meta) {
|
|
177
|
+
if (meta && typeof meta.status === 'number') {
|
|
178
|
+
response.status = meta.status;
|
|
179
|
+
response.ok = meta.status >= 200 && meta.status < 300;
|
|
193
180
|
}
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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 });
|
|
181
|
+
if (meta && meta.headers) {
|
|
182
|
+
response.headers = meta.headers;
|
|
183
|
+
|
|
184
|
+
// 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
|
|
185
|
+
const contentType =
|
|
186
|
+
(typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
|
|
187
|
+
meta.headers['content-type'] ||
|
|
188
|
+
'';
|
|
189
|
+
if (contentType.includes('text/event-stream')) {
|
|
190
|
+
response._sseMode = true;
|
|
219
191
|
}
|
|
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
192
|
}
|
|
236
|
-
};
|
|
237
|
-
// #end
|
|
238
|
-
|
|
239
|
-
// #doc:abort
|
|
240
|
-
const abortWith = (err) => {
|
|
241
|
-
if (controller) controller.abort();
|
|
242
|
-
hooks.onError(err);
|
|
243
|
-
};
|
|
244
193
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
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;
|
|
194
|
+
// 非 2xx 单独通知:不占用 error 事件、不锁 _done,错误体照常投递
|
|
195
|
+
if (response.status >= 400) {
|
|
196
|
+
response.emit('http-error', { status: response.status, headers: response.headers });
|
|
258
197
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
198
|
+
},
|
|
199
|
+
onData(chunk) {
|
|
200
|
+
response._push('data', chunk);
|
|
201
|
+
},
|
|
202
|
+
onEnd() {
|
|
203
|
+
clearTimer();
|
|
204
|
+
response._push('end');
|
|
205
|
+
},
|
|
206
|
+
onError(err) {
|
|
207
|
+
if (failed) return;
|
|
208
|
+
failed = true;
|
|
209
|
+
clearTimer();
|
|
210
|
+
// 错误同时通过 error 事件 和 catch 暴露,避免遗漏
|
|
211
|
+
response._push('error', err);
|
|
212
|
+
reject(err);
|
|
262
213
|
}
|
|
214
|
+
};
|
|
215
|
+
const abortWith = (err) => {
|
|
216
|
+
if (controller) controller.abort();
|
|
217
|
+
hooks.onError(err);
|
|
218
|
+
};
|
|
263
219
|
|
|
264
|
-
|
|
265
|
-
|
|
220
|
+
// 超时:到点先中断底层请求,再走统一错误通道
|
|
221
|
+
if (options.timeout > 0) {
|
|
222
|
+
timer = setTimeout(() => {
|
|
223
|
+
timer = null;
|
|
224
|
+
abortWith(new Error('fetch: 请求超时(' + options.timeout + 'ms)'));
|
|
225
|
+
}, options.timeout);
|
|
226
|
+
}
|
|
266
227
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
hooks.onError(err);
|
|
228
|
+
// 外部 signal
|
|
229
|
+
if (options.signal) {
|
|
230
|
+
if (options.signal.aborted) {
|
|
231
|
+
abortWith(new Error('fetch: 请求已取消'));
|
|
272
232
|
return;
|
|
273
233
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
}
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
|
|
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
|
-
}
|
|
234
|
+
options.signal.addEventListener('abort', () => {
|
|
235
|
+
abortWith(new Error('fetch: 请求已取消'));
|
|
236
|
+
});
|
|
237
|
+
}
|
|
299
238
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
onEnd();
|
|
303
|
-
return;
|
|
304
|
-
}
|
|
239
|
+
// 把内部 controller 的 signal 交给 adapter,adapter 可据此中断底层请求
|
|
240
|
+
const requestOptions = controller ? Object.assign({}, options, { signal: controller.signal }) : options;
|
|
305
241
|
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
}
|
|
328
|
-
})();
|
|
329
|
-
})
|
|
330
|
-
.catch((err) => onError(err));
|
|
242
|
+
let ret;
|
|
243
|
+
try {
|
|
244
|
+
ret = adapter(requestOptions, hooks);
|
|
245
|
+
} catch (err) {
|
|
246
|
+
hooks.onError(err);
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
// adapter 允许返回 Promise,失败也要走同一条错误通道
|
|
250
|
+
if (ret && typeof ret.then === 'function') ret.then(null, hooks.onError);
|
|
251
|
+
});
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// 浏览器环境适配器:基于原生 fetch + ReadableStream
|
|
256
|
+
// adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
|
|
257
|
+
function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
258
|
+
const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
259
|
+
|
|
260
|
+
if (typeof fetch !== 'function') {
|
|
261
|
+
onError(new Error('Global fetch is not available in this environment'));
|
|
262
|
+
return;
|
|
331
263
|
}
|
|
332
264
|
|
|
333
|
-
|
|
334
|
-
|
|
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(若上游关心)
|
|
265
|
+
fetch(url, { method, headers, body, signal })
|
|
266
|
+
.then(async (res) => {
|
|
370
267
|
if (typeof onResponse === 'function') {
|
|
371
268
|
onResponse({
|
|
372
|
-
status: res.
|
|
269
|
+
status: res.status || 0,
|
|
373
270
|
headers: res.headers || {}
|
|
374
271
|
});
|
|
375
272
|
}
|
|
376
273
|
|
|
377
|
-
|
|
378
|
-
res.
|
|
379
|
-
|
|
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('请求已取消'));
|
|
274
|
+
// 没有 body(例如 204)直接结束
|
|
275
|
+
if (!res.body) {
|
|
276
|
+
onEnd();
|
|
391
277
|
return;
|
|
392
278
|
}
|
|
393
|
-
|
|
394
|
-
|
|
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
|
-
|
|
413
|
-
const fetch$1 = createFetch(adapter);
|
|
279
|
+
const reader = res.body.getReader();
|
|
280
|
+
const decoder = new TextDecoder('utf-8');
|
|
414
281
|
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
282
|
+
// 循环读取流直到 done
|
|
283
|
+
// 用 async IIFE 形式启动,错误统一走 onError
|
|
284
|
+
(async () => {
|
|
285
|
+
try {
|
|
286
|
+
// eslint-disable-next-line no-constant-condition
|
|
287
|
+
while (true) {
|
|
288
|
+
const { value, done } = await reader.read();
|
|
289
|
+
if (done) {
|
|
290
|
+
onEnd();
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
// value 是 Uint8Array,解码为字符串
|
|
294
|
+
onData(decoder.decode(value, { stream: true }));
|
|
295
|
+
}
|
|
296
|
+
} catch (err) {
|
|
297
|
+
onError(err);
|
|
298
|
+
}
|
|
299
|
+
})();
|
|
300
|
+
})
|
|
301
|
+
.catch((err) => onError(err));
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Node 环境适配器:基于 http / https,天然流式输出
|
|
305
|
+
// adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
|
|
306
|
+
// 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
|
|
307
|
+
// 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
|
|
308
|
+
async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
309
|
+
const [{ default: http }, { default: https }, { URL }] = await Promise.all([
|
|
310
|
+
import('http'),
|
|
311
|
+
import('https'),
|
|
312
|
+
import('url')
|
|
313
|
+
]);
|
|
314
|
+
const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
315
|
+
|
|
316
|
+
let parsed;
|
|
317
|
+
try {
|
|
318
|
+
parsed = new URL(url);
|
|
319
|
+
} catch (e) {
|
|
320
|
+
onError(e);
|
|
321
|
+
return;
|
|
419
322
|
}
|
|
420
323
|
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
324
|
+
const isHttps = parsed.protocol === 'https:';
|
|
325
|
+
const lib = isHttps ? https : http;
|
|
326
|
+
|
|
327
|
+
const reqOptions = {
|
|
328
|
+
method,
|
|
329
|
+
hostname: parsed.hostname,
|
|
330
|
+
port: parsed.port || (isHttps ? 443 : 80),
|
|
331
|
+
path: parsed.pathname + parsed.search,
|
|
332
|
+
headers
|
|
333
|
+
};
|
|
334
|
+
const req = lib.request(reqOptions, (res) => {
|
|
335
|
+
// 把 status / headers 同步给 Response(若上游关心)
|
|
336
|
+
if (typeof onResponse === 'function') {
|
|
337
|
+
onResponse({
|
|
338
|
+
status: res.statusCode || 0,
|
|
339
|
+
headers: res.headers || {}
|
|
340
|
+
});
|
|
341
|
+
}
|
|
428
342
|
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
343
|
+
res.setEncoding('utf8');
|
|
344
|
+
res.on('data', (chunk) => onData(chunk));
|
|
345
|
+
res.on('end', () => onEnd());
|
|
346
|
+
res.on('error', (err) => onError(err));
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
req.on('error', (err) => onError(err));
|
|
350
|
+
// 取消 / 超时:直接中断底层请求,错误从 req 的 error 事件返回
|
|
351
|
+
if (signal) {
|
|
352
|
+
if (signal.aborted) {
|
|
353
|
+
onError(new Error('请求已取消'));
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
signal.addEventListener('abort', () => {
|
|
357
|
+
req.destroy(new Error('请求已取消'));
|
|
358
|
+
});
|
|
433
359
|
}
|
|
434
360
|
|
|
435
|
-
|
|
436
|
-
|
|
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;
|
|
361
|
+
if (body != null) {
|
|
362
|
+
req.write(body);
|
|
445
363
|
}
|
|
364
|
+
req.end();
|
|
365
|
+
}
|
|
446
366
|
|
|
447
|
-
|
|
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)));
|
|
367
|
+
// 入口:环境判断 + 选择 adapter,构造并导出 fetch
|
|
469
368
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
// 解析 LLM 返回的推理内容(reasoning / reasoning_content)
|
|
474
|
-
// 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
|
|
475
|
-
function parseReasoning(reasoning, content) {
|
|
476
|
-
if (!/<\/think>/.test(reasoning)) return reasoning;
|
|
369
|
+
// 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
|
|
370
|
+
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
|
|
477
371
|
|
|
478
|
-
|
|
479
|
-
const thinkPart = parts[0].replace("<think>", "");
|
|
480
|
-
return {
|
|
481
|
-
reasoning: thinkPart,
|
|
482
|
-
content: parts[1] + (content || "")
|
|
483
|
-
};
|
|
484
|
-
}
|
|
372
|
+
const adapter = isBrowser ? browserAdapter : nodeAdapter;
|
|
485
373
|
|
|
486
|
-
|
|
487
|
-
const CLOSE = "</think>";
|
|
374
|
+
const fetch$1 = createFetch(adapter);
|
|
488
375
|
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
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
|
-
}
|
|
376
|
+
// 字符串转 JSON,适配 LLM 返回的各种流式格式:
|
|
377
|
+
// 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
|
|
378
|
+
function stripDataPrefix(text) {
|
|
379
|
+
return text.replace(/^data:\s*/, "");
|
|
380
|
+
}
|
|
500
381
|
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
382
|
+
function tryParse(text) {
|
|
383
|
+
try {
|
|
384
|
+
return { value: JSON.parse(text) };
|
|
385
|
+
} catch (e) {
|
|
386
|
+
return null;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function parseOne(text, origin) {
|
|
391
|
+
const parsed = tryParse(stripDataPrefix(text.trim()));
|
|
392
|
+
if (!parsed) throw new SyntaxError("模型返回无法解析:" + String(origin).slice(0, 120));
|
|
393
|
+
return parsed.value;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// 错误响应体({"error":{...}})直接抛出,交给调用方转成 reject
|
|
397
|
+
function checkError(result) {
|
|
398
|
+
if (Array.isArray(result)) {
|
|
399
|
+
for (const item of result) {
|
|
400
|
+
if (item && item.error) throw item.error;
|
|
401
|
+
}
|
|
402
|
+
return result;
|
|
403
|
+
}
|
|
404
|
+
if (result && result.error) throw result.error;
|
|
405
|
+
return result;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function parseString (value) {
|
|
409
|
+
let text = String(value == null ? "" : value).trim();
|
|
410
|
+
|
|
411
|
+
// 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
|
|
412
|
+
text = text.replace(/data:\s*\[DONE\]$/, "").trim();
|
|
413
|
+
if (text === "" || text === "[DONE]") return [];
|
|
414
|
+
// 单条:带 data: 前缀或裸 JSON
|
|
415
|
+
let single = tryParse(stripDataPrefix(text)) || tryParse(text);
|
|
416
|
+
if (single) return checkError(single.value);
|
|
417
|
+
|
|
418
|
+
// 多条 SSE 事件,以 "\n\ndata: " 分隔
|
|
419
|
+
const parts = text.split(/\r?\n\r?\ndata: /);
|
|
420
|
+
if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
|
|
421
|
+
// NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
|
|
422
|
+
const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
|
|
423
|
+
if (lines.length > 1) return checkError(lines.map(line => parseOne(line, text)));
|
|
424
|
+
|
|
425
|
+
throw new SyntaxError("模型返回无法解析:" + text.slice(0, 120));
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
// 解析 LLM 返回的推理内容(reasoning / reasoning_content)
|
|
429
|
+
// 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
|
|
430
|
+
function parseReasoning(reasoning, content) {
|
|
431
|
+
if (!/<\/think>/.test(reasoning)) return reasoning;
|
|
432
|
+
|
|
433
|
+
const parts = reasoning.split("</think>");
|
|
434
|
+
const thinkPart = parts[0].replace("<think>", "");
|
|
435
|
+
return {
|
|
436
|
+
reasoning: thinkPart,
|
|
437
|
+
content: parts[1] + (content || "")
|
|
438
|
+
};
|
|
439
|
+
}
|
|
521
440
|
|
|
522
|
-
|
|
523
|
-
|
|
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
|
-
}
|
|
441
|
+
const OPEN = "<think>";
|
|
442
|
+
const CLOSE = "</think>";
|
|
529
443
|
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
444
|
+
// 计算文本尾部与标签前缀的最长匹配长度
|
|
445
|
+
// 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
|
|
446
|
+
function partialTagLength(text, tag) {
|
|
447
|
+
const max = Math.min(tag.length - 1, text.length);
|
|
448
|
+
for (let len = max; len > 0; len--) {
|
|
449
|
+
if (text.endsWith(tag.slice(0, len))) return len;
|
|
450
|
+
}
|
|
451
|
+
return 0;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
|
|
455
|
+
// 这里把它剥离出来:思考片段归 thinkback,其余归正文
|
|
456
|
+
// 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
|
|
457
|
+
// 返回 { thinking, content }
|
|
458
|
+
function extractThink(content, state) {
|
|
459
|
+
const buf = (state.thinkBuf || "") + content;
|
|
460
|
+
state.thinkBuf = "";
|
|
461
|
+
|
|
462
|
+
// 正处于思考块内:寻找 </think>
|
|
463
|
+
if (state.inThink) {
|
|
464
|
+
const end = buf.indexOf(CLOSE);
|
|
465
|
+
if (end === -1) {
|
|
466
|
+
const hold = partialTagLength(buf, CLOSE);
|
|
467
|
+
state.thinkBuf = buf.slice(buf.length - hold);
|
|
468
|
+
return { thinking: buf.slice(0, buf.length - hold), content: "" };
|
|
469
|
+
}
|
|
470
|
+
state.inThink = false;
|
|
471
|
+
const rest = extractThink(buf.slice(end + CLOSE.length), state);
|
|
472
|
+
return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
|
|
473
|
+
}
|
|
538
474
|
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
475
|
+
// 正常正文:寻找 <think>
|
|
476
|
+
const start = buf.indexOf(OPEN);
|
|
477
|
+
if (start === -1) {
|
|
478
|
+
const hold = partialTagLength(buf, OPEN);
|
|
479
|
+
state.thinkBuf = buf.slice(buf.length - hold);
|
|
480
|
+
return { thinking: "", content: buf.slice(0, buf.length - hold) };
|
|
481
|
+
}
|
|
546
482
|
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
483
|
+
const end = buf.indexOf(CLOSE, start);
|
|
484
|
+
if (end !== -1) {
|
|
485
|
+
const rest = extractThink(buf.slice(end + CLOSE.length), state);
|
|
486
|
+
return {
|
|
487
|
+
thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
|
|
488
|
+
content: buf.slice(0, start) + rest.content
|
|
489
|
+
};
|
|
490
|
+
}
|
|
553
491
|
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
492
|
+
// 有 <think> 无 </think>:进入思考态
|
|
493
|
+
state.inThink = true;
|
|
494
|
+
const body = buf.slice(start + OPEN.length);
|
|
495
|
+
const hold = partialTagLength(body, CLOSE);
|
|
496
|
+
state.thinkBuf = body.slice(body.length - hold);
|
|
497
|
+
return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
|
|
501
|
+
function flushThink(state) {
|
|
502
|
+
const buf = state.thinkBuf || "";
|
|
503
|
+
state.thinkBuf = "";
|
|
504
|
+
return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
// 新调用的槽位:保留原始字段形状,只保证 function.arguments 是字符串
|
|
508
|
+
function normalizeCall(toolCall) {
|
|
509
|
+
const fn = toolCall.function || {};
|
|
510
|
+
return {
|
|
511
|
+
...toolCall,
|
|
512
|
+
function: {
|
|
513
|
+
...fn,
|
|
514
|
+
arguments: typeof fn.arguments === "string" ? fn.arguments : ""
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
}
|
|
565
518
|
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
if (!state._toolSlots) state._toolSlots = new Map();
|
|
519
|
+
// 续片:按 index 优先归并,否则追加到最后一个槽位
|
|
520
|
+
function mergeToolCall(state, toolCall) {
|
|
521
|
+
if (!state._toolSlots) state._toolSlots = new Map();
|
|
570
522
|
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
523
|
+
const calls = state.tool_calls;
|
|
524
|
+
const index = typeof toolCall.index === "number" ? toolCall.index : null;
|
|
525
|
+
const hasId = typeof toolCall.id === "string" && toolCall.id !== "";
|
|
574
526
|
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
527
|
+
// 带 id 视为新调用;同 id 重复下发时复用已有槽位
|
|
528
|
+
if (hasId) {
|
|
529
|
+
const exist = calls.find(call => call.id === toolCall.id);
|
|
530
|
+
if (exist) {
|
|
531
|
+
appendArguments(exist, toolCall);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
const slot = normalizeCall(toolCall);
|
|
535
|
+
calls.push(slot);
|
|
536
|
+
if (index !== null) state._toolSlots.set(index, slot);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
587
539
|
|
|
588
|
-
|
|
589
|
-
|
|
540
|
+
let slot = index !== null ? state._toolSlots.get(index) : null;
|
|
541
|
+
if (!slot && calls.length) slot = calls[calls.length - 1];
|
|
590
542
|
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
543
|
+
// 首片就没有 id:建占位槽位,后续分片补齐参数
|
|
544
|
+
if (!slot) {
|
|
545
|
+
slot = normalizeCall(toolCall);
|
|
546
|
+
calls.push(slot);
|
|
547
|
+
if (index !== null) state._toolSlots.set(index, slot);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
598
550
|
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
551
|
+
appendArguments(slot, toolCall);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function appendArguments(slot, toolCall) {
|
|
555
|
+
const fn = toolCall.function || {};
|
|
556
|
+
if (fn.name && !slot.function.name) slot.function.name = fn.name;
|
|
557
|
+
if (typeof fn.arguments === "string") slot.function.arguments += fn.arguments;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
|
|
561
|
+
function handleChoices(choices, { logback, thinkback }, state) {
|
|
562
|
+
if (!Array.isArray(choices)) return;
|
|
563
|
+
|
|
564
|
+
for (let i = 0; i < choices.length; i++) {
|
|
565
|
+
const delta = choices[i].delta;
|
|
566
|
+
|
|
567
|
+
// 推理内容(reasoning / reasoning_content 字段)
|
|
568
|
+
let reasoning = delta.reasoning || delta.reasoning_content;
|
|
569
|
+
if (reasoning) {
|
|
570
|
+
const parsed = parseReasoning(reasoning, delta.content);
|
|
571
|
+
if (typeof parsed === "object") {
|
|
572
|
+
reasoning = parsed.reasoning;
|
|
573
|
+
delta.content = parsed.content;
|
|
574
|
+
}
|
|
575
|
+
if (thinkback) thinkback(reasoning);
|
|
576
|
+
}
|
|
602
577
|
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
578
|
+
// 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
|
|
579
|
+
if (delta.content) {
|
|
580
|
+
const extracted = extractThink(delta.content, state);
|
|
581
|
+
if (extracted.thinking && thinkback) thinkback(extracted.thinking);
|
|
582
|
+
if (extracted.content) {
|
|
583
|
+
if (logback) logback(extracted.content);
|
|
584
|
+
state.content += extracted.content;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
608
587
|
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
588
|
+
// 工具调用分片
|
|
589
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
590
|
+
for (const toolCall of delta.tool_calls) {
|
|
591
|
+
mergeToolCall(state, toolCall);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
|
|
598
|
+
function flushThinkBuffer(state, { logback, thinkback }) {
|
|
599
|
+
const flushed = flushThink(state);
|
|
600
|
+
if (flushed.thinking && thinkback) thinkback(flushed.thinking);
|
|
601
|
+
if (flushed.content) {
|
|
602
|
+
if (logback) logback(flushed.content);
|
|
603
|
+
state.content += flushed.content;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
626
606
|
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
607
|
+
// 统一把各种错误形态收敛成 Error,保证 Promise 一定 settle
|
|
608
|
+
function toError(value, fallback) {
|
|
609
|
+
if (value instanceof Error) return value;
|
|
610
|
+
if (value && typeof value.message === "string") return new Error(value.message);
|
|
611
|
+
try {
|
|
612
|
+
return new Error(String(value));
|
|
613
|
+
} catch (e) {
|
|
614
|
+
return new Error(fallback || "模型请求失败");
|
|
615
|
+
}
|
|
616
|
+
}
|
|
636
617
|
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
}
|
|
642
|
-
}
|
|
643
|
-
}
|
|
644
|
-
}
|
|
618
|
+
// HTTP 错误:尽量带出响应体里的 error.message,方便定位
|
|
619
|
+
function errorFromHttp(meta, body) {
|
|
620
|
+
const status = meta && meta.status;
|
|
621
|
+
let detail = "";
|
|
645
622
|
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
623
|
+
if (body) {
|
|
624
|
+
try {
|
|
625
|
+
const parsed = JSON.parse(body);
|
|
626
|
+
const raw = parsed && parsed.error;
|
|
627
|
+
detail = (raw && (raw.message || raw)) || "";
|
|
628
|
+
} catch (e) {
|
|
629
|
+
detail = String(body).slice(0, 200);
|
|
630
|
+
}
|
|
631
|
+
if (detail && typeof detail !== "string") detail = JSON.stringify(detail);
|
|
632
|
+
}
|
|
655
633
|
|
|
656
|
-
|
|
657
|
-
|
|
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
|
-
}
|
|
634
|
+
return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
|
|
635
|
+
}
|
|
666
636
|
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
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
|
-
}
|
|
637
|
+
function completions(params, logback, thinkback) {
|
|
638
|
+
return new Promise((resolve, reject) => {
|
|
639
|
+
const state = { content: "", tool_calls: [] };
|
|
640
|
+
const callbacks = { logback, thinkback };
|
|
682
641
|
|
|
683
|
-
|
|
684
|
-
|
|
642
|
+
let buffer = "";
|
|
643
|
+
let httpError = null;
|
|
644
|
+
let streamError = null;
|
|
645
|
+
let settled = false;
|
|
685
646
|
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
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));
|
|
647
|
+
const finish = (fn, value) => {
|
|
648
|
+
if (settled) return;
|
|
649
|
+
settled = true;
|
|
650
|
+
fn(value);
|
|
651
|
+
};
|
|
652
|
+
const fail = value => finish(reject, toError(value, "模型请求失败"));
|
|
653
|
+
const body = {
|
|
654
|
+
model: this.model,
|
|
655
|
+
messages: params.messages,
|
|
656
|
+
tools: params.tools ? params.tools.map(tool => tool.description) : [],
|
|
657
|
+
stream: params.stream,
|
|
658
|
+
};
|
|
659
|
+
const temperature = params.temperature != null ? params.temperature : this.temperature;
|
|
660
|
+
const topP = params.topP != null ? params.topP : this.topP;
|
|
661
|
+
const maxTokens = params.maxTokens != null ? params.maxTokens : this.maxTokens;
|
|
662
|
+
if (temperature != null) body.temperature = temperature;
|
|
663
|
+
if (topP != null) body.top_p = topP;
|
|
664
|
+
if (maxTokens != null) body.max_tokens = maxTokens;
|
|
665
|
+
fetch$1({
|
|
666
|
+
url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
|
|
667
|
+
method: "POST",
|
|
668
|
+
headers: {
|
|
669
|
+
"Authorization": `Bearer ${this.apiKey}`,
|
|
670
|
+
"Content-Type": "application/json",
|
|
671
|
+
},
|
|
672
|
+
body: JSON.stringify(body),
|
|
673
|
+
timeout: params.timeout != null ? params.timeout : this.timeout,
|
|
674
|
+
signal: params.signal
|
|
675
|
+
}).then(res => {
|
|
676
|
+
|
|
677
|
+
// 非 2xx:非流式等错误体读完再判,流式直接中断
|
|
678
|
+
res.on("http-error", meta => {
|
|
679
|
+
httpError = meta;
|
|
680
|
+
if (params.stream) fail(errorFromHttp(meta));
|
|
681
|
+
});
|
|
682
|
+
|
|
683
|
+
// 数据流
|
|
684
|
+
res.on("data", chunk => {
|
|
685
|
+
if (settled) return;
|
|
686
|
+
if (!params.stream) {
|
|
687
|
+
buffer += chunk;
|
|
688
|
+
return;
|
|
689
|
+
}
|
|
690
|
+
let parsed;
|
|
691
|
+
try {
|
|
692
|
+
parsed = parseString(chunk.toString());
|
|
693
|
+
} catch (e) {
|
|
694
|
+
streamError = e;
|
|
695
|
+
fail(e);
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
try {
|
|
699
|
+
const items = Array.isArray(parsed) ? parsed : [parsed];
|
|
700
|
+
for (const item of items) handleChoices(item.choices, callbacks, state);
|
|
701
|
+
} catch (e) {
|
|
702
|
+
fail(e);
|
|
703
|
+
}
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
// 结束
|
|
707
|
+
res.on("end", () => {
|
|
708
|
+
if (!params.stream) {
|
|
709
|
+
if (httpError) {
|
|
710
|
+
fail(errorFromHttp(httpError, buffer));
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
try {
|
|
714
|
+
const parsed = parseString(buffer);
|
|
715
|
+
const choices = parsed && parsed.choices;
|
|
716
|
+
if (!choices || !choices[0] || !choices[0].message) {
|
|
717
|
+
throw new Error("模型响应缺少 choices[0].message");
|
|
718
|
+
}
|
|
719
|
+
handleChoices([{ delta: choices[0].message }], callbacks, state);
|
|
720
|
+
} catch (e) {
|
|
721
|
+
fail(e);
|
|
722
|
+
return;
|
|
723
|
+
}
|
|
724
|
+
} else if (streamError) {
|
|
725
|
+
fail(streamError);
|
|
726
|
+
return;
|
|
727
|
+
} else if (httpError) {
|
|
728
|
+
fail(errorFromHttp(httpError));
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// 冲刷 <think> 标签截断残留
|
|
733
|
+
flushThinkBuffer(state, callbacks);
|
|
734
|
+
finish(resolve, { content: state.content, tool_calls: state.tool_calls });
|
|
735
|
+
});
|
|
736
|
+
|
|
737
|
+
res.on("error", err => fail(err));
|
|
738
|
+
}).catch(err => fail(err));
|
|
798
739
|
|
|
799
|
-
|
|
800
|
-
|
|
740
|
+
});
|
|
741
|
+
}
|
|
801
742
|
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
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
|
|
814
|
-
}
|
|
743
|
+
function Model(fields) {
|
|
744
|
+
this.model = fields.model;
|
|
745
|
+
this.apiKey = fields.apiKey;
|
|
746
|
+
this.baseURL = fields.baseURL;
|
|
815
747
|
|
|
816
|
-
|
|
748
|
+
// 可选请求参数:显式传入才写进请求体,保持旧行为不变
|
|
749
|
+
this.temperature = fields.temperature;
|
|
750
|
+
this.topP = fields.topP;
|
|
751
|
+
this.maxTokens = fields.maxTokens;
|
|
752
|
+
this.timeout = fields.timeout;
|
|
753
|
+
}
|
|
817
754
|
|
|
818
|
-
|
|
755
|
+
Model.prototype.completions = completions;
|
|
819
756
|
|
|
820
|
-
}
|
|
757
|
+
export { Model };
|