@auipage/model 0.1.0-alpha.4 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,407 +1,489 @@
1
- /*! @auipage/model v0.1.0-alpha.4 */
1
+ /*! @auipage/model v0.1.0 */
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
4
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
5
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.auipage_model = {}));
6
6
  })(this, (function (exports) { 'use strict';
7
7
 
8
- // 极简 EventEmitter:on / off / emit,供 Response 复用
9
- class Emitter {
10
- constructor() {
11
- this._events = Object.create(null);
12
- }
13
-
14
- on(event, listener) {
15
- if (typeof listener !== 'function') return this;
16
- const list = this._events[event] || (this._events[event] = []);
17
- list.push(listener);
18
- return this;
19
- }
20
-
21
- off(event, listener) {
22
- const list = this._events[event];
23
- if (!list) return this;
24
- const idx = list.indexOf(listener);
25
- if (idx >= 0) list.splice(idx, 1);
26
- if (list.length === 0) delete this._events[event];
27
- return this;
28
- }
29
-
30
- emit(event, ...args) {
31
- const list = this._events[event];
32
- if (!list || list.length === 0) return false;
33
- // 复制一份再触发,避免 off 回调过程中影响本次派发
34
- for (const fn of list.slice()) {
35
- try {
36
- fn.apply(null, args);
37
- } catch (e) {
38
- // 单个监听器异常不影响其它监听器
39
- // 用 queueMicrotask 抛到全局,避免污染 emit 调用栈
40
- queueMicrotask(() => { throw e; });
41
- }
42
- }
43
- return true;
44
- }
8
+ // 极简 EventEmitter:on / off / emit,供 Response 复用
9
+ class Emitter {
10
+ constructor() {
11
+ this._events = Object.create(null);
12
+ }
13
+
14
+ on(event, listener) {
15
+ if (typeof listener !== 'function') return this;
16
+ const list = this._events[event] || (this._events[event] = []);
17
+ list.push(listener);
18
+ return this;
19
+ }
20
+
21
+ off(event, listener) {
22
+ const list = this._events[event];
23
+ if (!list) return this;
24
+ const idx = list.indexOf(listener);
25
+ if (idx >= 0) list.splice(idx, 1);
26
+ if (list.length === 0) delete this._events[event];
27
+ return this;
28
+ }
29
+
30
+ emit(event, ...args) {
31
+ const list = this._events[event];
32
+ if (!list || list.length === 0) return false;
33
+ // 复制一份再触发,避免 off 回调过程中影响本次派发
34
+ for (const fn of list.slice()) {
35
+ try {
36
+ fn.apply(null, args);
37
+ } catch (e) {
38
+ // 单个监听器异常不影响其它监听器
39
+ // 用 queueMicrotask 抛到全局,避免污染 emit 调用栈
40
+ queueMicrotask(() => { throw e; });
41
+ }
42
+ }
43
+ return true;
44
+ }
45
45
  }
46
46
 
47
- // Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
48
-
49
- class Response extends Emitter {
50
- constructor() {
51
- super();
52
- this.status = 0;
53
- this.headers = {};
54
- this.ok = false;
55
- this._done = false; // 标记是否已经 end/error,防止重复触发
56
- this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
57
- this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
58
- }
59
-
60
- // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
61
- _push(type, payload) {
62
- if (this._done && type !== 'error') return;
63
-
64
- // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
65
- if (type === 'data' && this._sseMode) {
66
- this._sseBuffer += payload;
67
-
68
- // 按 \n\n 分割出完整事件,最后一段可能不完整
69
- const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
70
- this._sseBuffer = parts.pop();
71
-
72
- for (const part of parts) {
73
- const payload = this._extractSSEData(part);
74
- if (payload !== null) {
75
- this.emit('data', payload);
76
- }
77
- }
78
- return;
79
- }
80
-
81
- if (type === 'end') {
82
- // SSE 模式下,flush 缓冲区残留
83
- if (this._sseMode && this._sseBuffer.trim()) {
84
- const payload = this._extractSSEData(this._sseBuffer);
85
- if (payload !== null) {
86
- this.emit('data', payload);
87
- }
88
- this._sseBuffer = '';
89
- }
90
- this._done = true;
91
- }
92
- if (type === 'error') this._done = true;
93
-
94
- this.emit(type, payload);
95
- }
96
-
97
- // 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
98
- _extractSSEData(raw) {
99
- const dataLines = [];
100
- for (const line of raw.split('\n')) {
101
- if (line.startsWith('data:')) {
102
- dataLines.push(line.replace(/^data:\s*/, ''));
103
- }
104
- }
105
- if (dataLines.length === 0) return null;
106
- return dataLines.join('\n');
107
- }
47
+ // Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
48
+
49
+ class Response extends Emitter {
50
+ constructor() {
51
+ super();
52
+ this.status = 0;
53
+ this.headers = {};
54
+ this.ok = false;
55
+ this._done = false; // 标记是否已经 end/error,防止重复触发
56
+ this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
57
+ this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
58
+ }
59
+
60
+ // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
61
+ _push(type, payload) {
62
+ if (this._done && type !== 'error') return;
63
+
64
+ // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
65
+ if (type === 'data' && this._sseMode) {
66
+ this._sseBuffer += payload;
67
+
68
+ // 按 \n\n 分割出完整事件,最后一段可能不完整
69
+ const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
70
+ this._sseBuffer = parts.pop();
71
+
72
+ for (const part of parts) {
73
+ const payload = this._extractSSEData(part);
74
+ if (payload !== null) {
75
+ this.emit('data', payload);
76
+ }
77
+ }
78
+ return;
79
+ }
80
+
81
+ if (type === 'end') {
82
+ // SSE 模式下,flush 缓冲区残留
83
+ if (this._sseMode && this._sseBuffer.trim()) {
84
+ const payload = this._extractSSEData(this._sseBuffer);
85
+ if (payload !== null) {
86
+ this.emit('data', payload);
87
+ }
88
+ this._sseBuffer = '';
89
+ }
90
+ this._done = true;
91
+ }
92
+ if (type === 'error') this._done = true;
93
+
94
+ this.emit(type, payload);
95
+ }
96
+
97
+ // 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
98
+ _extractSSEData(raw) {
99
+ const dataLines = [];
100
+ for (const line of raw.split('\n')) {
101
+ if (line.startsWith('data:')) {
102
+ dataLines.push(line.replace(/^data:\s*/, ''));
103
+ }
104
+ }
105
+ if (dataLines.length === 0) return null;
106
+ return dataLines.join('\n');
107
+ }
108
108
  }
109
109
 
110
- // fetch 工厂:注入 adapter,返回对外的 fetch 函数
111
-
112
- function createFetch(adapter) {
113
- return function fetch(options) {
114
- // 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
115
- return new Promise((resolve, reject) => {
116
- if (!options || !options.url) {
117
- reject(new Error('fetch: options.url is required'));
118
- return;
119
- }
120
-
121
- const response = new Response();
122
-
123
- // adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
124
- // 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
125
- queueMicrotask(() => resolve(response));
126
-
127
- adapter(options, {
128
- onResponse(meta) {
129
- if (meta && typeof meta.status === 'number') {
130
- response.status = meta.status;
131
- response.ok = meta.status >= 200 && meta.status < 300;
132
- }
133
- if (meta && meta.headers) {
134
- response.headers = meta.headers;
135
-
136
- // 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
137
- const contentType =
138
- (typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
139
- meta.headers['content-type'] ||
140
- '';
141
- if (contentType.includes('text/event-stream')) {
142
- response._sseMode = true;
143
- }
144
- }
145
- },
146
- onData(chunk) {
147
- response._push('data', chunk);
148
- },
149
- onEnd() {
150
- response._push('end');
151
- },
152
- onError(err) {
153
- // 错误同时通过 error 事件 和 catch 暴露,避免遗漏
154
- response._push('error', err);
155
- reject(err);
156
- }
157
- });
158
- });
159
- };
110
+ // fetch 工厂:注入 adapter,返回对外的 fetch 函数
111
+
112
+ function createFetch(adapter) {
113
+ return function fetch(options) {
114
+ // 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
115
+ return new Promise((resolve, reject) => {
116
+ if (!options || !options.url) {
117
+ reject(new Error('fetch: options.url is required'));
118
+ return;
119
+ }
120
+
121
+ const response = new Response();
122
+
123
+ // adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
124
+ // 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
125
+ queueMicrotask(() => resolve(response));
126
+
127
+ adapter(options, {
128
+ onResponse(meta) {
129
+ if (meta && typeof meta.status === 'number') {
130
+ response.status = meta.status;
131
+ response.ok = meta.status >= 200 && meta.status < 300;
132
+ }
133
+ if (meta && meta.headers) {
134
+ response.headers = meta.headers;
135
+
136
+ // 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
137
+ const contentType =
138
+ (typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
139
+ meta.headers['content-type'] ||
140
+ '';
141
+ if (contentType.includes('text/event-stream')) {
142
+ response._sseMode = true;
143
+ }
144
+ }
145
+ },
146
+ onData(chunk) {
147
+ response._push('data', chunk);
148
+ },
149
+ onEnd() {
150
+ response._push('end');
151
+ },
152
+ onError(err) {
153
+ // 错误同时通过 error 事件 和 catch 暴露,避免遗漏
154
+ response._push('error', err);
155
+ reject(err);
156
+ }
157
+ });
158
+ });
159
+ };
160
160
  }
161
161
 
162
- // 浏览器环境适配器:基于原生 fetch + ReadableStream
163
- // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
164
- function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
165
- const { url, method = 'GET', headers = {}, body } = options;
166
-
167
- if (typeof fetch !== 'function') {
168
- onError(new Error('Global fetch is not available in this environment'));
169
- return;
170
- }
171
-
172
- fetch(url, { method, headers, body })
173
- .then(async (res) => {
174
- if (typeof onResponse === 'function') {
175
- onResponse({
176
- status: res.status || 0,
177
- headers: res.headers || {}
178
- });
179
- }
180
-
181
- // 没有 body(例如 204)直接结束
182
- if (!res.body) {
183
- onEnd();
184
- return;
185
- }
186
-
187
- const reader = res.body.getReader();
188
- const decoder = new TextDecoder('utf-8');
189
-
190
- // 循环读取流直到 done
191
- // 用 async IIFE 形式启动,错误统一走 onError
192
- (async () => {
193
- try {
194
- // eslint-disable-next-line no-constant-condition
195
- while (true) {
196
- const { value, done } = await reader.read();
197
- if (done) {
198
- onEnd();
199
- return;
200
- }
201
- // value 是 Uint8Array,解码为字符串
202
- onData(decoder.decode(value, { stream: true }));
203
- }
204
- } catch (err) {
205
- onError(err);
206
- }
207
- })();
208
- })
209
- .catch((err) => onError(err));
162
+ // 浏览器环境适配器:基于原生 fetch + ReadableStream
163
+ // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
164
+ function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
165
+ const { url, method = 'GET', headers = {}, body } = options;
166
+
167
+ if (typeof fetch !== 'function') {
168
+ onError(new Error('Global fetch is not available in this environment'));
169
+ return;
170
+ }
171
+
172
+ fetch(url, { method, headers, body })
173
+ .then(async (res) => {
174
+ if (typeof onResponse === 'function') {
175
+ onResponse({
176
+ status: res.status || 0,
177
+ headers: res.headers || {}
178
+ });
179
+ }
180
+
181
+ // 没有 body(例如 204)直接结束
182
+ if (!res.body) {
183
+ onEnd();
184
+ return;
185
+ }
186
+
187
+ const reader = res.body.getReader();
188
+ const decoder = new TextDecoder('utf-8');
189
+
190
+ // 循环读取流直到 done
191
+ // 用 async IIFE 形式启动,错误统一走 onError
192
+ (async () => {
193
+ try {
194
+ // eslint-disable-next-line no-constant-condition
195
+ while (true) {
196
+ const { value, done } = await reader.read();
197
+ if (done) {
198
+ onEnd();
199
+ return;
200
+ }
201
+ // value 是 Uint8Array,解码为字符串
202
+ onData(decoder.decode(value, { stream: true }));
203
+ }
204
+ } catch (err) {
205
+ onError(err);
206
+ }
207
+ })();
208
+ })
209
+ .catch((err) => onError(err));
210
210
  }
211
211
 
212
- // Node 环境适配器:基于 http / https,天然流式输出
213
- // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
214
- // 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
215
- // 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
216
- async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
217
- const [{ default: http }, { default: https }, { URL }] = await Promise.all([
218
- import('http'),
219
- import('https'),
220
- import('url')
221
- ]);
222
-
223
- const { url, method = 'GET', headers = {}, body } = options;
224
-
225
- let parsed;
226
- try {
227
- parsed = new URL(url);
228
- } catch (e) {
229
- onError(e);
230
- return;
231
- }
232
-
233
- const isHttps = parsed.protocol === 'https:';
234
- const lib = isHttps ? https : http;
235
-
236
- const reqOptions = {
237
- method,
238
- hostname: parsed.hostname,
239
- port: parsed.port || (isHttps ? 443 : 80),
240
- path: parsed.pathname + parsed.search,
241
- headers
242
- };
243
-
244
- const req = lib.request(reqOptions, (res) => {
245
- // 把 status / headers 同步给 Response(若上游关心)
246
- if (typeof onResponse === 'function') {
247
- onResponse({
248
- status: res.statusCode || 0,
249
- headers: res.headers || {}
250
- });
251
- }
252
-
253
- res.setEncoding('utf8');
254
- res.on('data', (chunk) => onData(chunk));
255
- res.on('end', () => onEnd());
256
- res.on('error', (err) => onError(err));
257
- });
258
-
259
- req.on('error', (err) => onError(err));
260
-
261
- if (body != null) {
262
- req.write(body);
263
- }
264
- req.end();
212
+ // Node 环境适配器:基于 http / https,天然流式输出
213
+ // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
214
+ // 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
215
+ // 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
216
+ async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
217
+ const [{ default: http }, { default: https }, { URL }] = await Promise.all([
218
+ import('http'),
219
+ import('https'),
220
+ import('url')
221
+ ]);
222
+
223
+ const { url, method = 'GET', headers = {}, body } = options;
224
+
225
+ let parsed;
226
+ try {
227
+ parsed = new URL(url);
228
+ } catch (e) {
229
+ onError(e);
230
+ return;
231
+ }
232
+
233
+ const isHttps = parsed.protocol === 'https:';
234
+ const lib = isHttps ? https : http;
235
+
236
+ const reqOptions = {
237
+ method,
238
+ hostname: parsed.hostname,
239
+ port: parsed.port || (isHttps ? 443 : 80),
240
+ path: parsed.pathname + parsed.search,
241
+ headers
242
+ };
243
+
244
+ const req = lib.request(reqOptions, (res) => {
245
+ // 把 status / headers 同步给 Response(若上游关心)
246
+ if (typeof onResponse === 'function') {
247
+ onResponse({
248
+ status: res.statusCode || 0,
249
+ headers: res.headers || {}
250
+ });
251
+ }
252
+
253
+ res.setEncoding('utf8');
254
+ res.on('data', (chunk) => onData(chunk));
255
+ res.on('end', () => onEnd());
256
+ res.on('error', (err) => onError(err));
257
+ });
258
+
259
+ req.on('error', (err) => onError(err));
260
+
261
+ if (body != null) {
262
+ req.write(body);
263
+ }
264
+ req.end();
265
265
  }
266
266
 
267
- // 入口:环境判断 + 选择 adapter,构造并导出 fetch
268
-
269
- // 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
270
- const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
271
-
272
- const adapter = isBrowser ? browserAdapter : nodeAdapter;
273
-
267
+ // 入口:环境判断 + 选择 adapter,构造并导出 fetch
268
+
269
+ // 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
270
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
271
+
272
+ const adapter = isBrowser ? browserAdapter : nodeAdapter;
273
+
274
274
  const fetch$1 = createFetch(adapter);
275
275
 
276
- // 字符串转JSON
277
- // 适配LLM返回数据格式
278
- function parseString (value) {
279
- value = value.trim().replace(/^data: /, "").replace(/data: \[DONE\]$/, "");
280
-
281
- if (/\r{0,1}\n\r{0,1}\ndata: /.test(value)) {
282
- return JSON.parse("[" + (value.split(/\r{0,1}\n\r{0,1}\ndata: /)).join(",") + "]");
283
- } else if (value === "[DONE]") {
284
- return [];
285
- }
286
-
287
- let result = JSON.parse(value);
288
- if (result.error) throw result.error;
289
-
290
- return result;
291
- }
292
-
293
- // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
294
- // 将 <think>...</think> 形式的内容从 delta.content 中剥离出来
295
- function parseReasoning(reasoning, content) {
296
- if (!/<\/think>/.test(reasoning)) return reasoning;
297
-
298
- const parts = reasoning.split("</think>");
299
- const thinkPart = parts[0].replace("<think>", "");
300
- return {
301
- reasoning: thinkPart,
302
- content: thinkPart[1] + (content || "")
303
- };
276
+ // 字符串转JSON
277
+ // 适配LLM返回数据格式
278
+ function parseString (value) {
279
+ value = value.trim().replace(/^data: /, "").replace(/data: \[DONE\]$/, "");
280
+
281
+ if (/\r{0,1}\n\r{0,1}\ndata: /.test(value)) {
282
+ return JSON.parse("[" + (value.split(/\r{0,1}\n\r{0,1}\ndata: /)).join(",") + "]");
283
+ } else if (value === "[DONE]") {
284
+ return [];
285
+ }
286
+
287
+ let result = JSON.parse(value);
288
+ if (result.error) throw result.error;
289
+
290
+ return result;
304
291
  }
305
292
 
306
- // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
307
- // 返回累积的 { content, tool_calls }
308
- function handleChoices(choices, { logback, thinkback }, state) {
309
- for (let i = 0; i < choices.length; i++) {
310
- const delta = choices[i].delta;
311
-
312
- // 推理内容
313
- let reasoning = delta.reasoning || delta.reasoning_content;
314
- if (reasoning) {
315
- const parsed = parseReasoning(reasoning, delta.content);
316
- if (typeof parsed === "object") {
317
- reasoning = parsed.reasoning;
318
- delta.content = parsed.content;
319
- }
320
- if (thinkback) thinkback(reasoning);
321
- }
322
-
323
- // 正文内容
324
- if (delta.content) {
325
- if (logback) logback(delta.content);
326
- state.content += delta.content;
327
- }
328
-
329
- // 工具调用
330
- if (delta.tool_calls) {
331
- for (const toolCall of delta.tool_calls) {
332
- if (toolCall.id) {
333
- state.tool_calls.push(toolCall);
334
- } else {
335
- state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
336
- }
337
- }
338
- }
339
- }
293
+ // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
294
+ // 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
295
+ function parseReasoning(reasoning, content) {
296
+ if (!/<\/think>/.test(reasoning)) return reasoning;
297
+
298
+ const parts = reasoning.split("</think>");
299
+ const thinkPart = parts[0].replace("<think>", "");
300
+ return {
301
+ reasoning: thinkPart,
302
+ content: parts[1] + (content || "")
303
+ };
304
+ }
305
+
306
+ const OPEN = "<think>";
307
+ const CLOSE = "</think>";
308
+
309
+ // 计算文本尾部与标签前缀的最长匹配长度
310
+ // 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
311
+ function partialTagLength(text, tag) {
312
+ const max = Math.min(tag.length - 1, text.length);
313
+ for (let len = max; len > 0; len--) {
314
+ if (text.endsWith(tag.slice(0, len))) return len;
315
+ }
316
+ return 0;
317
+ }
318
+
319
+ // 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
320
+ // 这里把它剥离出来:思考片段归 thinkback,其余归正文
321
+ // 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
322
+ // 返回 { thinking, content }
323
+ function extractThink(content, state) {
324
+ const buf = (state.thinkBuf || "") + content;
325
+ state.thinkBuf = "";
326
+
327
+ // 正处于思考块内:寻找 </think>
328
+ if (state.inThink) {
329
+ const end = buf.indexOf(CLOSE);
330
+ if (end === -1) {
331
+ const hold = partialTagLength(buf, CLOSE);
332
+ state.thinkBuf = buf.slice(buf.length - hold);
333
+ return { thinking: buf.slice(0, buf.length - hold), content: "" };
334
+ }
335
+ state.inThink = false;
336
+ const rest = extractThink(buf.slice(end + CLOSE.length), state);
337
+ return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
338
+ }
339
+
340
+ // 正常正文:寻找 <think>
341
+ const start = buf.indexOf(OPEN);
342
+ if (start === -1) {
343
+ const hold = partialTagLength(buf, OPEN);
344
+ state.thinkBuf = buf.slice(buf.length - hold);
345
+ return { thinking: "", content: buf.slice(0, buf.length - hold) };
346
+ }
347
+
348
+ const end = buf.indexOf(CLOSE, start);
349
+ if (end !== -1) {
350
+ const rest = extractThink(buf.slice(end + CLOSE.length), state);
351
+ return {
352
+ thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
353
+ content: buf.slice(0, start) + rest.content
354
+ };
355
+ }
356
+
357
+ // 有 <think> 无 </think>:进入思考态
358
+ state.inThink = true;
359
+ const body = buf.slice(start + OPEN.length);
360
+ const hold = partialTagLength(body, CLOSE);
361
+ state.thinkBuf = body.slice(body.length - hold);
362
+ return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
363
+ }
364
+
365
+ // 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
366
+ function flushThink(state) {
367
+ const buf = state.thinkBuf || "";
368
+ state.thinkBuf = "";
369
+ return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
340
370
  }
341
371
 
342
- function completions(params, logback, thinkback) {
343
- return new Promise((resolve, reject) => {
344
-
345
- const state = { content: "", tool_calls: [] };
346
- const callbacks = { logback, thinkback };
347
-
348
- let buffer = "";
349
-
350
- fetch$1({
351
- url: `${this.baseURL}/chat/completions`,
352
- method: "POST",
353
- headers: {
354
- "Authorization": `Bearer ${this.apiKey}`,
355
- "Content-Type": "application/json",
356
- },
357
- body: JSON.stringify({
358
- model: this.model,
359
- messages: params.messages,
360
- tools: params.tools ? params.tools.map(tool => tool.description) : [],
361
- stream: params.stream,
362
- })
363
- }).then(res => {
364
-
365
- // 数据流
366
- res.on("data", chunk => {
367
- if (params.stream) {
368
- const parsed = parseString(chunk.toString());
369
- if (Array.isArray(parsed)) {
370
- for (const item of parsed) {
371
- handleChoices(item.choices, callbacks, state);
372
- }
373
- } else {
374
- handleChoices(parsed.choices, callbacks, state);
375
- }
376
- } else {
377
- buffer += chunk;
378
- }
379
- });
380
-
381
- // 结束
382
- res.on("end", () => {
383
- if (!params.stream) {
384
- handleChoices(
385
- [{ delta: parseString(buffer).choices[0].message }],
386
- callbacks,
387
- state
388
- );
389
- }
390
- resolve({ content: state.content, tool_calls: state.tool_calls });
391
- });
392
-
393
- res.on("error", err => reject(err));
394
- }).catch(err => reject(err));
395
-
396
- });
372
+ // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
373
+ // 返回累积的 { content, tool_calls }
374
+ function handleChoices(choices, { logback, thinkback }, state) {
375
+ for (let i = 0; i < choices.length; i++) {
376
+ const delta = choices[i].delta;
377
+
378
+ // 推理内容(reasoning / reasoning_content 字段)
379
+ let reasoning = delta.reasoning || delta.reasoning_content;
380
+ if (reasoning) {
381
+ const parsed = parseReasoning(reasoning, delta.content);
382
+ if (typeof parsed === "object") {
383
+ reasoning = parsed.reasoning;
384
+ delta.content = parsed.content;
385
+ }
386
+ if (thinkback) thinkback(reasoning);
387
+ }
388
+
389
+ // 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
390
+ if (delta.content) {
391
+ const extracted = extractThink(delta.content, state);
392
+ if (extracted.thinking && thinkback) thinkback(extracted.thinking);
393
+ if (extracted.content) {
394
+ if (logback) logback(extracted.content);
395
+ state.content += extracted.content;
396
+ }
397
+ }
398
+
399
+ // 工具调用
400
+ if (delta.tool_calls) {
401
+ for (const toolCall of delta.tool_calls) {
402
+ if (toolCall.id) {
403
+ state.tool_calls.push(toolCall);
404
+ } else {
405
+ state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
406
+ }
407
+ }
408
+ }
409
+ }
410
+ }
411
+
412
+ // 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
413
+ function flushThinkBuffer(state, { logback, thinkback }) {
414
+ const flushed = flushThink(state);
415
+ if (flushed.thinking && thinkback) thinkback(flushed.thinking);
416
+ if (flushed.content) {
417
+ if (logback) logback(flushed.content);
418
+ state.content += flushed.content;
419
+ }
397
420
  }
398
421
 
399
- function Model(fields) {
400
- this.model = fields.model;
401
- this.apiKey = fields.apiKey;
402
- this.baseURL = fields.baseURL;
422
+ function completions(params, logback, thinkback) {
423
+ return new Promise((resolve, reject) => {
424
+
425
+ const state = { content: "", tool_calls: [] };
426
+ const callbacks = { logback, thinkback };
427
+
428
+ let buffer = "";
429
+
430
+ fetch$1({
431
+ url: `${this.baseURL}/chat/completions`,
432
+ method: "POST",
433
+ headers: {
434
+ "Authorization": `Bearer ${this.apiKey}`,
435
+ "Content-Type": "application/json",
436
+ },
437
+ body: JSON.stringify({
438
+ model: this.model,
439
+ messages: params.messages,
440
+ tools: params.tools ? params.tools.map(tool => tool.description) : [],
441
+ stream: params.stream,
442
+ })
443
+ }).then(res => {
444
+
445
+ // 数据流
446
+ res.on("data", chunk => {
447
+ if (params.stream) {
448
+ const parsed = parseString(chunk.toString());
449
+ if (Array.isArray(parsed)) {
450
+ for (const item of parsed) {
451
+ handleChoices(item.choices, callbacks, state);
452
+ }
453
+ } else {
454
+ handleChoices(parsed.choices, callbacks, state);
455
+ }
456
+ } else {
457
+ buffer += chunk;
458
+ }
459
+ });
460
+
461
+ // 结束
462
+ res.on("end", () => {
463
+ if (!params.stream) {
464
+ handleChoices(
465
+ [{ delta: parseString(buffer).choices[0].message }],
466
+ callbacks,
467
+ state
468
+ );
469
+ }
470
+ // 冲刷 <think> 标签截断残留
471
+ flushThinkBuffer(state, callbacks);
472
+ resolve({ content: state.content, tool_calls: state.tool_calls });
473
+ });
474
+
475
+ res.on("error", err => reject(err));
476
+ }).catch(err => reject(err));
477
+
478
+ });
403
479
  }
404
480
 
481
+ function Model(fields) {
482
+ this.model = fields.model;
483
+ this.apiKey = fields.apiKey;
484
+ this.baseURL = fields.baseURL;
485
+ }
486
+
405
487
  Model.prototype.completions = completions;
406
488
 
407
489
  exports.Model = Model;