@auipage/model 0.2.0-alpha.0 → 0.2.0-alpha.1

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/dist/index.js CHANGED
@@ -1,820 +1,757 @@
1
- /*! @auipage/model v0.2.0-alpha.0 */
2
- (function (global, factory) {
3
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.auipage_model = {}));
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.1 */
2
+ // 极简 EventEmitter:on / off / emit,供 Response 复用
3
+ class Emitter {
4
+ constructor() {
5
+ this._events = Object.create(null);
46
6
  }
47
7
 
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
- }
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
- // 注册监听;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));
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
- // 主动取消请求,失败统一从 error 事件返回
80
- cancel() {
81
- if (this._cancel) this._cancel();
82
- return this;
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
- // 统一读取响应头:浏览器是 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
- }
66
+ // 主动取消请求,失败统一从 error 事件返回
67
+ cancel() {
68
+ if (this._cancel) this._cancel();
69
+ return this;
70
+ }
92
71
 
93
- // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
94
- _push(type, payload) {
95
- if (this._done && type !== 'error') return;
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
- // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
98
- // #doc:sse
99
- if (type === 'data' && this._sseMode) {
100
- this._sseBuffer += payload;
80
+ // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
81
+ _push(type, payload) {
82
+ if (this._done && type !== 'error') return;
101
83
 
102
- // 按 \n\n 分割出完整事件,最后一段可能不完整
103
- const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
104
- this._sseBuffer = parts.pop();
84
+ // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
85
+ if (type === 'data' && this._sseMode) {
86
+ this._sseBuffer += payload;
105
87
 
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
- }
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
- 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 = '';
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
- 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;
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
- // 从一个 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
- }
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
- // 只有普通对象才自动 JSON 序列化,ArrayBufferView / Blob / FormData 等保持原样
158
- function isPlainBody(body) {
159
- return Object.prototype.toString.call(body) === '[object Object]';
122
+ this.emit(type, payload);
160
123
  }
161
124
 
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
- }
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
- const response = new Response();
178
- const controller = typeof AbortController === 'function' ? new AbortController() : null;
179
- let timer = null;
180
- let failed = false;
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
- response._cancel = () => { if (controller) controller.abort(); };
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
- // adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
185
- // 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
186
- queueMicrotask(() => resolve(response));
187
- // #end
164
+ response._cancel = () => { if (controller) controller.abort(); };
188
165
 
189
- const clearTimer = () => {
190
- if (timer) {
191
- clearTimeout(timer);
192
- timer = null;
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
- // #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 });
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
- 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;
194
+ // 非 2xx 单独通知:不占用 error 事件、不锁 _done,错误体照常投递
195
+ if (response.status >= 400) {
196
+ response.emit('http-error', { status: response.status, headers: response.headers });
258
197
  }
259
- options.signal.addEventListener('abort', () => {
260
- abortWith(new Error('fetch: 请求已取消'));
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
- // 把内部 controller 的 signal 交给 adapter,adapter 可据此中断底层请求
265
- const requestOptions = controller ? Object.assign({}, options, { signal: controller.signal }) : options;
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
- let ret;
268
- try {
269
- ret = adapter(requestOptions, hooks);
270
- } catch (err) {
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
- // adapter 允许返回 Promise,失败也要走同一条错误通道
275
- if (ret && typeof ret.then === 'function') ret.then(null, hooks.onError);
276
- // #end
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
- // 没有 body(例如 204)直接结束
301
- if (!res.body) {
302
- onEnd();
303
- return;
304
- }
239
+ // 把内部 controller 的 signal 交给 adapter,adapter 可据此中断底层请求
240
+ const requestOptions = controller ? Object.assign({}, options, { signal: controller.signal }) : options;
305
241
 
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));
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
- // 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(若上游关心)
265
+ fetch(url, { method, headers, body, signal })
266
+ .then(async (res) => {
370
267
  if (typeof onResponse === 'function') {
371
268
  onResponse({
372
- status: res.statusCode || 0,
269
+ status: res.status || 0,
373
270
  headers: res.headers || {}
374
271
  });
375
272
  }
376
273
 
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('请求已取消'));
274
+ // 没有 body(例如 204)直接结束
275
+ if (!res.body) {
276
+ onEnd();
391
277
  return;
392
278
  }
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
-
413
- const fetch$1 = createFetch(adapter);
279
+ const reader = res.body.getReader();
280
+ const decoder = new TextDecoder('utf-8');
414
281
 
415
- // 字符串转 JSON,适配 LLM 返回的各种流式格式:
416
- // 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
417
- function stripDataPrefix(text) {
418
- return text.replace(/^data:\s*/, "");
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
- function tryParse(text) {
422
- try {
423
- return { value: JSON.parse(text) };
424
- } catch (e) {
425
- return null;
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
- 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;
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
- // 错误响应体({"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;
361
+ if (body != null) {
362
+ req.write(body);
445
363
  }
364
+ req.end();
365
+ }
446
366
 
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)));
367
+ // 入口:环境判断 + 选择 adapter,构造并导出 fetch
469
368
 
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;
369
+ // 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
370
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
477
371
 
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
- }
372
+ const adapter = isBrowser ? browserAdapter : nodeAdapter;
485
373
 
486
- const OPEN = "<think>";
487
- const CLOSE = "</think>";
374
+ const fetch$1 = createFetch(adapter);
488
375
 
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
- }
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
- // 部分模型(如 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
- }
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
- // 正常正文:寻找 <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
- }
441
+ const OPEN = "<think>";
442
+ const CLOSE = "</think>";
529
443
 
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
- }
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
- // 有 <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
- }
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
- // 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
548
- function flushThink(state) {
549
- const buf = state.thinkBuf || "";
550
- state.thinkBuf = "";
551
- return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
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
- // 新调用的槽位:保留原始字段形状,只保证 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
- }
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
- // 续片:按 index 优先归并,否则追加到最后一个槽位
567
- // #doc:merge
568
- function mergeToolCall(state, toolCall) {
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
- const calls = state.tool_calls;
572
- const index = typeof toolCall.index === "number" ? toolCall.index : null;
573
- const hasId = typeof toolCall.id === "string" && toolCall.id !== "";
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
- // 带 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
- }
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
- let slot = index !== null ? state._toolSlots.get(index) : null;
589
- if (!slot && calls.length) slot = calls[calls.length - 1];
540
+ let slot = index !== null ? state._toolSlots.get(index) : null;
541
+ if (!slot && calls.length) slot = calls[calls.length - 1];
590
542
 
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
- }
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
- appendArguments(slot, toolCall);
600
- // #end
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
- 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
- }
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
- // 处理单批 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
- }
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
- // 正文内容:剥离混在 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
- }
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
- if (Array.isArray(delta.tool_calls)) {
639
- for (const toolCall of delta.tool_calls) {
640
- mergeToolCall(state, toolCall);
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
- // 流结束时调用:把 <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
- }
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
- // 统一把各种错误形态收敛成 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
- }
634
+ return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
635
+ }
666
636
 
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
- }
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
- return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
684
- }
642
+ let buffer = "";
643
+ let httpError = null;
644
+ let streamError = null;
645
+ let settled = false;
685
646
 
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));
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
- // #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
814
- }
743
+ function Model(fields) {
744
+ this.model = fields.model;
745
+ this.apiKey = fields.apiKey;
746
+ this.baseURL = fields.baseURL;
815
747
 
816
- Model.prototype.completions = completions;
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
- exports.Model = Model;
755
+ Model.prototype.completions = completions;
819
756
 
820
- }));
757
+ export { Model };