@auipage/model 0.1.0-alpha.5 → 0.2.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG +26 -1
- package/README.md +46 -56
- package/dist/index.js +383 -54
- package/package.json +3 -3
- package/src/completions.js +112 -25
- package/src/index.js +8 -0
- package/src/parseString.js +52 -11
- package/src/reasoning.js +2 -0
- package/src/streamHandler.js +60 -8
- package/types/completions.d.ts +4 -0
package/CHANGELOG
CHANGED
|
@@ -1,4 +1,29 @@
|
|
|
1
1
|
v0.1.0:
|
|
2
|
-
date:
|
|
2
|
+
date:2026-10-25
|
|
3
3
|
changes:
|
|
4
4
|
- 初始化版本
|
|
5
|
+
v0.2.0:
|
|
6
|
+
date:
|
|
7
|
+
changes:
|
|
8
|
+
- 修复bug:
|
|
9
|
+
1、模型请求 4xx / 网络失败时进程崩溃或请求永久挂起
|
|
10
|
+
2、页面在适配器、前端工具、历史入库任一环节失败后锁死(isExecuting 一直为 true)
|
|
11
|
+
3、工具并行调用分片串味,无参工具的调用直接失败
|
|
12
|
+
4、复用同一 messages 数组时 systemPrompt 重复累积
|
|
13
|
+
5、流式数据含 \r 换行或末尾 [DONE] 时正文被污染、解析提前中断
|
|
14
|
+
6、响应结束后才订阅 error 的监听器收不到终态
|
|
15
|
+
- 优化改造:
|
|
16
|
+
1、请求支持 timeout 与 signal,可主动取消
|
|
17
|
+
2、非 2xx 响应新增 http-error 事件,不再只有 ok=false
|
|
18
|
+
3、页面历史入库失败会明确报错,不再静默丢弃
|
|
19
|
+
4、监听器异常不再抛出为进程级异常
|
|
20
|
+
5、流式生成器取消后清空挂起队列,不再堆积残留
|
|
21
|
+
- 新增功能:
|
|
22
|
+
1、Agent 支持 maxSteps(默认 0,不限制)
|
|
23
|
+
2、新增 toModelMessages,把页面消息转成模型入参
|
|
24
|
+
3、新增 AuiPage.stop():执行中主动结束,内容保留、消息组标记 stopped,sendMessage 正常 resolve
|
|
25
|
+
4、新增 AuiPage.cancel():取消本轮,消息组标记 cancelled,sendMessage 以「已取消」reject
|
|
26
|
+
5、主动结束与取消的那一轮仍入库,存或丢由业务自行决定
|
|
27
|
+
6、task:end 增加 by(user / tool),取消时另带 displayed,列出已显示条目供界面撤销
|
|
28
|
+
7、工具 execute / render 拿到任务控制句柄,可直接 stop() / cancel() 结束整轮
|
|
29
|
+
8、取消信号经 context.signal 透传,Agent / model 均支持中断
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# [@auipage/model](https://github.com/handless-ui/auipage
|
|
1
|
+
# [@auipage/model](https://github.com/handless-ui/auipage)
|
|
2
2
|
|
|
3
|
-
OpenAI 风格 `chat/completions`
|
|
3
|
+
OpenAI 风格 `chat/completions` 的零依赖封装:请求拼装、SSE 增量解析、`tool_calls` 切片拼接、`<think>` 标签剥离,一次给你收好。
|
|
4
4
|
|
|
5
5
|
<p>
|
|
6
6
|
<a href="https://zxl20070701.github.io/toolbox/#/npm-download?packages=@auipage/model&interval=7">
|
|
@@ -14,78 +14,68 @@ OpenAI 风格 `chat/completions` 的流式封装:负责请求拼装、SSE 增
|
|
|
14
14
|
</a>
|
|
15
15
|
</p>
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
## 它解决什么
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
直接对着 `chat/completions` 写流式解析,会卡在这几件事上:
|
|
20
20
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
21
|
+
- `data:` 事件要逐条切,`[DONE]` 要单独认;
|
|
22
|
+
- `delta.content` 是增量,得自己累积才能拿到完整文本;
|
|
23
|
+
- `tool_calls` 按 `index` 分片到达,`arguments` 是半个 JSON,要拼完再 `parse`;
|
|
24
|
+
- DeepSeek 这类模型的 `reasoning_content` 和 `<think>` 标签要单独处理。
|
|
24
25
|
|
|
25
|
-
|
|
26
|
+
这些都不该由业务代码反复实现。
|
|
27
|
+
|
|
28
|
+
## 30 秒例子
|
|
26
29
|
|
|
27
30
|
```javascript
|
|
28
31
|
import { Model } from "@auipage/model";
|
|
29
32
|
|
|
30
33
|
const model = new Model({
|
|
31
|
-
model: "
|
|
32
|
-
apiKey: "
|
|
33
|
-
baseURL: "
|
|
34
|
+
model: "qwen3.5",
|
|
35
|
+
apiKey: "ollama", // 本地 ollama 不校验
|
|
36
|
+
baseURL: "http://localhost:11434/v1" // 请求时拼 /chat/completions
|
|
34
37
|
});
|
|
35
|
-
```
|
|
36
38
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
```typescript
|
|
40
|
-
model.completions(
|
|
39
|
+
const { content, tool_calls } = await model.completions(
|
|
41
40
|
{
|
|
42
|
-
messages:
|
|
43
|
-
|
|
44
|
-
stream?: boolean // 默认 false
|
|
41
|
+
messages: [{ role: "user", content: "用一句话介绍 JavaScript" }],
|
|
42
|
+
stream: true
|
|
45
43
|
},
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
)
|
|
44
|
+
delta => process.stdout.write(delta), // 正文增量
|
|
45
|
+
think => process.stdout.write("[思考] " + think) // 推理增量
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
console.log("\n完整文本:", content);
|
|
49
|
+
console.log("工具调用:", tool_calls);
|
|
49
50
|
```
|
|
50
51
|
|
|
51
|
-
|
|
52
|
-
- `stream: false` 时两个回调仍会调用,只是在响应结束后各触发一次。
|
|
53
|
-
- 返回的 `tool_calls` 已按 `id` 切片、拼好 `function.arguments`。
|
|
52
|
+
换成 DeepSeek、OpenAI 或任何兼容服务,只改构造参数里的三个字段。
|
|
54
53
|
|
|
55
|
-
|
|
54
|
+
安装:
|
|
56
55
|
|
|
57
|
-
```
|
|
58
|
-
model
|
|
59
|
-
messages: [
|
|
60
|
-
{ role: "system", content: "你是一个助手。" },
|
|
61
|
-
{ role: "user", content: "查一下南京今天的天气" }
|
|
62
|
-
],
|
|
63
|
-
tools: [
|
|
64
|
-
{
|
|
65
|
-
description: {
|
|
66
|
-
type: "function",
|
|
67
|
-
function: {
|
|
68
|
-
name: "getWeather",
|
|
69
|
-
description: "查询指定城市的天气",
|
|
70
|
-
parameters: {
|
|
71
|
-
type: "object",
|
|
72
|
-
properties: { city: { type: "string" } },
|
|
73
|
-
required: ["city"]
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
],
|
|
79
|
-
stream: true
|
|
80
|
-
}, (chunk) => {
|
|
81
|
-
process.stdout.write(chunk); // 正文增量
|
|
82
|
-
}, (reasoning) => {
|
|
83
|
-
console.log("[think]", reasoning); // 推理增量
|
|
84
|
-
}).then(({ content, tool_calls }) => {
|
|
85
|
-
console.log(content, tool_calls);
|
|
86
|
-
});
|
|
56
|
+
```bash
|
|
57
|
+
npm install --save @auipage/model
|
|
87
58
|
```
|
|
88
59
|
|
|
60
|
+
## 这个包不是必须的
|
|
61
|
+
|
|
62
|
+
| 你的情况 | 可以换成 | 会失去什么 |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| 只接一家模型,功能简单 | 官方 SDK(`openai`、`@deepseek/sdk`) | 多一个依赖,但维护由官方负责 |
|
|
65
|
+
| 已经用 Vercel AI SDK | `@ai-sdk/openai` + `streamText` | 生态更全,但抽象层更厚 |
|
|
66
|
+
| 想完全掌控 | 原生 `fetch` + 自己解析 SSE | 上面四件脏活得自己写 |
|
|
67
|
+
| 只用非流式 | 原生 `fetch` 一次 POST | 没有增量回调,但代码最短 |
|
|
68
|
+
|
|
69
|
+
它适合“**想零依赖、又要一个能直接跑的 OpenAI 兼容客户端**”的场景。如果你已经在用某家的官方 SDK,没有必要为了统一而换掉。
|
|
70
|
+
|
|
71
|
+
## 它在哪一环
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
fetch ← model ← agent
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`@auipage/agent` 在它之上做工具循环。完整签名与返回结构见 [model 参考](https://handless-ui.github.io/auipage/packages/model.html)。
|
|
78
|
+
|
|
89
79
|
## 版权
|
|
90
80
|
|
|
91
81
|
MIT License
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! @auipage/model v0.
|
|
1
|
+
/*! @auipage/model v0.2.0-alpha.0 */
|
|
2
2
|
(function (global, factory) {
|
|
3
3
|
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
|
|
4
4
|
typeof define === 'function' && define.amd ? define(['exports'], factory) :
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
return this;
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
+
// #doc:emit
|
|
30
31
|
emit(event, ...args) {
|
|
31
32
|
const list = this._events[event];
|
|
32
33
|
if (!list || list.length === 0) return false;
|
|
@@ -35,12 +36,12 @@
|
|
|
35
36
|
try {
|
|
36
37
|
fn.apply(null, args);
|
|
37
38
|
} catch (e) {
|
|
38
|
-
//
|
|
39
|
-
|
|
40
|
-
queueMicrotask(() => { throw e; });
|
|
39
|
+
// 单个监听器异常不影响其它监听器,也不再冒泡成进程级异常
|
|
40
|
+
console.error(e);
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
43
|
return true;
|
|
44
|
+
// #end
|
|
44
45
|
}
|
|
45
46
|
}
|
|
46
47
|
|
|
@@ -49,12 +50,44 @@
|
|
|
49
50
|
class Response extends Emitter {
|
|
50
51
|
constructor() {
|
|
51
52
|
super();
|
|
53
|
+
// #doc:state
|
|
52
54
|
this.status = 0;
|
|
53
55
|
this.headers = {};
|
|
54
56
|
this.ok = false;
|
|
55
57
|
this._done = false; // 标记是否已经 end/error,防止重复触发
|
|
56
58
|
this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
|
|
57
59
|
this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
|
|
60
|
+
this._cancel = null; // 由 createFetch 注入,用于中断底层请求
|
|
61
|
+
this._errorPending = null; // 消费者还没来得及注册时就发生的错误,注册后补发
|
|
62
|
+
// #end
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// 注册监听;error 是一次性终态,注册时若已发生则补发
|
|
66
|
+
// #doc:replay
|
|
67
|
+
on(event, listener) {
|
|
68
|
+
super.on(event, listener);
|
|
69
|
+
if (event === 'error' && this._errorPending) {
|
|
70
|
+
const err = this._errorPending;
|
|
71
|
+
this._errorPending = null;
|
|
72
|
+
// 异步补发,避免在注册栈里同步回调
|
|
73
|
+
queueMicrotask(() => this.emit('error', err));
|
|
74
|
+
}
|
|
75
|
+
return this;
|
|
76
|
+
// #end
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 主动取消请求,失败统一从 error 事件返回
|
|
80
|
+
cancel() {
|
|
81
|
+
if (this._cancel) this._cancel();
|
|
82
|
+
return this;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// 统一读取响应头:浏览器是 Headers 对象,Node 是普通对象
|
|
86
|
+
header(name) {
|
|
87
|
+
const headers = this.headers;
|
|
88
|
+
if (!headers) return undefined;
|
|
89
|
+
if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
|
|
90
|
+
return headers[name];
|
|
58
91
|
}
|
|
59
92
|
|
|
60
93
|
// 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
|
|
@@ -62,6 +95,7 @@
|
|
|
62
95
|
if (this._done && type !== 'error') return;
|
|
63
96
|
|
|
64
97
|
// SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
|
|
98
|
+
// #doc:sse
|
|
65
99
|
if (type === 'data' && this._sseMode) {
|
|
66
100
|
this._sseBuffer += payload;
|
|
67
101
|
|
|
@@ -76,6 +110,7 @@
|
|
|
76
110
|
}
|
|
77
111
|
}
|
|
78
112
|
return;
|
|
113
|
+
// #end
|
|
79
114
|
}
|
|
80
115
|
|
|
81
116
|
if (type === 'end') {
|
|
@@ -89,27 +124,43 @@
|
|
|
89
124
|
}
|
|
90
125
|
this._done = true;
|
|
91
126
|
}
|
|
92
|
-
if (type === 'error')
|
|
127
|
+
if (type === 'error') {
|
|
128
|
+
this._done = true;
|
|
129
|
+
const listeners = this._events && this._events['error'];
|
|
130
|
+
if (!listeners || listeners.length === 0) {
|
|
131
|
+
// 消费者还没注册监听,先缓存,注册时补发
|
|
132
|
+
this._errorPending = payload;
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
93
136
|
|
|
94
137
|
this.emit(type, payload);
|
|
95
138
|
}
|
|
96
139
|
|
|
97
140
|
// 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
|
|
141
|
+
// #doc:extract
|
|
98
142
|
_extractSSEData(raw) {
|
|
99
143
|
const dataLines = [];
|
|
100
144
|
for (const line of raw.split('\n')) {
|
|
101
145
|
if (line.startsWith('data:')) {
|
|
102
|
-
dataLines.push(line.replace(/^data:\s*/, ''));
|
|
146
|
+
dataLines.push(line.replace(/^data:\s*/, '').replace(/\r$/, ''));
|
|
103
147
|
}
|
|
104
148
|
}
|
|
105
149
|
if (dataLines.length === 0) return null;
|
|
106
150
|
return dataLines.join('\n');
|
|
151
|
+
// #end
|
|
107
152
|
}
|
|
108
153
|
}
|
|
109
154
|
|
|
110
155
|
// fetch 工厂:注入 adapter,返回对外的 fetch 函数
|
|
111
156
|
|
|
157
|
+
// 只有普通对象才自动 JSON 序列化,ArrayBufferView / Blob / FormData 等保持原样
|
|
158
|
+
function isPlainBody(body) {
|
|
159
|
+
return Object.prototype.toString.call(body) === '[object Object]';
|
|
160
|
+
}
|
|
161
|
+
|
|
112
162
|
function createFetch(adapter) {
|
|
163
|
+
// #doc:factory
|
|
113
164
|
return function fetch(options) {
|
|
114
165
|
// 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
|
|
115
166
|
return new Promise((resolve, reject) => {
|
|
@@ -118,13 +169,32 @@
|
|
|
118
169
|
return;
|
|
119
170
|
}
|
|
120
171
|
|
|
172
|
+
// 请求体是普通对象时自动序列化,避免 Node 端 req.write(object) 抛 TypeError
|
|
173
|
+
if (isPlainBody(options.body)) {
|
|
174
|
+
options = Object.assign({}, options, { body: JSON.stringify(options.body) });
|
|
175
|
+
}
|
|
176
|
+
|
|
121
177
|
const response = new Response();
|
|
178
|
+
const controller = typeof AbortController === 'function' ? new AbortController() : null;
|
|
179
|
+
let timer = null;
|
|
180
|
+
let failed = false;
|
|
181
|
+
|
|
182
|
+
response._cancel = () => { if (controller) controller.abort(); };
|
|
122
183
|
|
|
123
184
|
// adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
|
|
124
185
|
// 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
|
|
125
186
|
queueMicrotask(() => resolve(response));
|
|
187
|
+
// #end
|
|
188
|
+
|
|
189
|
+
const clearTimer = () => {
|
|
190
|
+
if (timer) {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
timer = null;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
126
195
|
|
|
127
|
-
|
|
196
|
+
// #doc:hooks
|
|
197
|
+
const hooks = {
|
|
128
198
|
onResponse(meta) {
|
|
129
199
|
if (meta && typeof meta.status === 'number') {
|
|
130
200
|
response.status = meta.status;
|
|
@@ -142,19 +212,68 @@
|
|
|
142
212
|
response._sseMode = true;
|
|
143
213
|
}
|
|
144
214
|
}
|
|
215
|
+
|
|
216
|
+
// 非 2xx 单独通知:不占用 error 事件、不锁 _done,错误体照常投递
|
|
217
|
+
if (response.status >= 400) {
|
|
218
|
+
response.emit('http-error', { status: response.status, headers: response.headers });
|
|
219
|
+
}
|
|
145
220
|
},
|
|
146
221
|
onData(chunk) {
|
|
147
222
|
response._push('data', chunk);
|
|
148
223
|
},
|
|
149
224
|
onEnd() {
|
|
225
|
+
clearTimer();
|
|
150
226
|
response._push('end');
|
|
151
227
|
},
|
|
152
228
|
onError(err) {
|
|
229
|
+
if (failed) return;
|
|
230
|
+
failed = true;
|
|
231
|
+
clearTimer();
|
|
153
232
|
// 错误同时通过 error 事件 和 catch 暴露,避免遗漏
|
|
154
233
|
response._push('error', err);
|
|
155
234
|
reject(err);
|
|
156
235
|
}
|
|
157
|
-
}
|
|
236
|
+
};
|
|
237
|
+
// #end
|
|
238
|
+
|
|
239
|
+
// #doc:abort
|
|
240
|
+
const abortWith = (err) => {
|
|
241
|
+
if (controller) controller.abort();
|
|
242
|
+
hooks.onError(err);
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// 超时:到点先中断底层请求,再走统一错误通道
|
|
246
|
+
if (options.timeout > 0) {
|
|
247
|
+
timer = setTimeout(() => {
|
|
248
|
+
timer = null;
|
|
249
|
+
abortWith(new Error('fetch: 请求超时(' + options.timeout + 'ms)'));
|
|
250
|
+
}, options.timeout);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// 外部 signal
|
|
254
|
+
if (options.signal) {
|
|
255
|
+
if (options.signal.aborted) {
|
|
256
|
+
abortWith(new Error('fetch: 请求已取消'));
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
options.signal.addEventListener('abort', () => {
|
|
260
|
+
abortWith(new Error('fetch: 请求已取消'));
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// 把内部 controller 的 signal 交给 adapter,adapter 可据此中断底层请求
|
|
265
|
+
const requestOptions = controller ? Object.assign({}, options, { signal: controller.signal }) : options;
|
|
266
|
+
|
|
267
|
+
let ret;
|
|
268
|
+
try {
|
|
269
|
+
ret = adapter(requestOptions, hooks);
|
|
270
|
+
} catch (err) {
|
|
271
|
+
hooks.onError(err);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
// adapter 允许返回 Promise,失败也要走同一条错误通道
|
|
275
|
+
if (ret && typeof ret.then === 'function') ret.then(null, hooks.onError);
|
|
276
|
+
// #end
|
|
158
277
|
});
|
|
159
278
|
};
|
|
160
279
|
}
|
|
@@ -162,14 +281,14 @@
|
|
|
162
281
|
// 浏览器环境适配器:基于原生 fetch + ReadableStream
|
|
163
282
|
// adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
|
|
164
283
|
function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
165
|
-
const { url, method = 'GET', headers = {}, body } = options;
|
|
284
|
+
const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
166
285
|
|
|
167
286
|
if (typeof fetch !== 'function') {
|
|
168
287
|
onError(new Error('Global fetch is not available in this environment'));
|
|
169
288
|
return;
|
|
170
289
|
}
|
|
171
290
|
|
|
172
|
-
fetch(url, { method, headers, body })
|
|
291
|
+
fetch(url, { method, headers, body, signal })
|
|
173
292
|
.then(async (res) => {
|
|
174
293
|
if (typeof onResponse === 'function') {
|
|
175
294
|
onResponse({
|
|
@@ -184,6 +303,7 @@
|
|
|
184
303
|
return;
|
|
185
304
|
}
|
|
186
305
|
|
|
306
|
+
// #doc:read
|
|
187
307
|
const reader = res.body.getReader();
|
|
188
308
|
const decoder = new TextDecoder('utf-8');
|
|
189
309
|
|
|
@@ -200,6 +320,7 @@
|
|
|
200
320
|
}
|
|
201
321
|
// value 是 Uint8Array,解码为字符串
|
|
202
322
|
onData(decoder.decode(value, { stream: true }));
|
|
323
|
+
// #end
|
|
203
324
|
}
|
|
204
325
|
} catch (err) {
|
|
205
326
|
onError(err);
|
|
@@ -214,13 +335,15 @@
|
|
|
214
335
|
// 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
|
|
215
336
|
// 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
|
|
216
337
|
async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
338
|
+
// #doc:lazy
|
|
217
339
|
const [{ default: http }, { default: https }, { URL }] = await Promise.all([
|
|
218
340
|
import('http'),
|
|
219
341
|
import('https'),
|
|
220
342
|
import('url')
|
|
221
343
|
]);
|
|
344
|
+
// #end
|
|
222
345
|
|
|
223
|
-
const { url, method = 'GET', headers = {}, body } = options;
|
|
346
|
+
const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
224
347
|
|
|
225
348
|
let parsed;
|
|
226
349
|
try {
|
|
@@ -241,6 +364,7 @@
|
|
|
241
364
|
headers
|
|
242
365
|
};
|
|
243
366
|
|
|
367
|
+
// #doc:req
|
|
244
368
|
const req = lib.request(reqOptions, (res) => {
|
|
245
369
|
// 把 status / headers 同步给 Response(若上游关心)
|
|
246
370
|
if (typeof onResponse === 'function') {
|
|
@@ -257,6 +381,20 @@
|
|
|
257
381
|
});
|
|
258
382
|
|
|
259
383
|
req.on('error', (err) => onError(err));
|
|
384
|
+
// #end
|
|
385
|
+
|
|
386
|
+
// 取消 / 超时:直接中断底层请求,错误从 req 的 error 事件返回
|
|
387
|
+
// #doc:abort
|
|
388
|
+
if (signal) {
|
|
389
|
+
if (signal.aborted) {
|
|
390
|
+
onError(new Error('请求已取消'));
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
signal.addEventListener('abort', () => {
|
|
394
|
+
req.destroy(new Error('请求已取消'));
|
|
395
|
+
// #end
|
|
396
|
+
});
|
|
397
|
+
}
|
|
260
398
|
|
|
261
399
|
if (body != null) {
|
|
262
400
|
req.write(body);
|
|
@@ -267,29 +405,71 @@
|
|
|
267
405
|
// 入口:环境判断 + 选择 adapter,构造并导出 fetch
|
|
268
406
|
|
|
269
407
|
// 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
|
|
408
|
+
// #doc:pick
|
|
270
409
|
const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
|
|
271
410
|
|
|
272
411
|
const adapter = isBrowser ? browserAdapter : nodeAdapter;
|
|
273
412
|
|
|
274
413
|
const fetch$1 = createFetch(adapter);
|
|
275
414
|
|
|
276
|
-
// 字符串转JSON
|
|
277
|
-
//
|
|
278
|
-
function
|
|
279
|
-
|
|
415
|
+
// 字符串转 JSON,适配 LLM 返回的各种流式格式:
|
|
416
|
+
// 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
|
|
417
|
+
function stripDataPrefix(text) {
|
|
418
|
+
return text.replace(/^data:\s*/, "");
|
|
419
|
+
}
|
|
280
420
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
421
|
+
function tryParse(text) {
|
|
422
|
+
try {
|
|
423
|
+
return { value: JSON.parse(text) };
|
|
424
|
+
} catch (e) {
|
|
425
|
+
return null;
|
|
285
426
|
}
|
|
427
|
+
}
|
|
286
428
|
|
|
287
|
-
|
|
288
|
-
|
|
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;
|
|
433
|
+
}
|
|
289
434
|
|
|
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;
|
|
290
444
|
return result;
|
|
291
445
|
}
|
|
292
446
|
|
|
447
|
+
function parseString (value) {
|
|
448
|
+
let text = String(value == null ? "" : value).trim();
|
|
449
|
+
|
|
450
|
+
// 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
|
|
451
|
+
// #doc:done
|
|
452
|
+
text = text.replace(/data:\s*\[DONE\]$/, "").trim();
|
|
453
|
+
if (text === "" || text === "[DONE]") return [];
|
|
454
|
+
// #end
|
|
455
|
+
|
|
456
|
+
// 单条:带 data: 前缀或裸 JSON
|
|
457
|
+
let single = tryParse(stripDataPrefix(text)) || tryParse(text);
|
|
458
|
+
if (single) return checkError(single.value);
|
|
459
|
+
|
|
460
|
+
// 多条 SSE 事件,以 "\n\ndata: " 分隔
|
|
461
|
+
// #doc:multi
|
|
462
|
+
const parts = text.split(/\r?\n\r?\ndata: /);
|
|
463
|
+
if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
|
|
464
|
+
// #end
|
|
465
|
+
|
|
466
|
+
// NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
|
|
467
|
+
const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
|
|
468
|
+
if (lines.length > 1) return checkError(lines.map(line => parseOne(line, text)));
|
|
469
|
+
|
|
470
|
+
throw new SyntaxError("模型返回无法解析:" + text.slice(0, 120));
|
|
471
|
+
}
|
|
472
|
+
|
|
293
473
|
// 解析 LLM 返回的推理内容(reasoning / reasoning_content)
|
|
294
474
|
// 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
|
|
295
475
|
function parseReasoning(reasoning, content) {
|
|
@@ -308,12 +488,14 @@
|
|
|
308
488
|
|
|
309
489
|
// 计算文本尾部与标签前缀的最长匹配长度
|
|
310
490
|
// 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
|
|
491
|
+
// #doc:partial
|
|
311
492
|
function partialTagLength(text, tag) {
|
|
312
493
|
const max = Math.min(tag.length - 1, text.length);
|
|
313
494
|
for (let len = max; len > 0; len--) {
|
|
314
495
|
if (text.endsWith(tag.slice(0, len))) return len;
|
|
315
496
|
}
|
|
316
497
|
return 0;
|
|
498
|
+
// #end
|
|
317
499
|
}
|
|
318
500
|
|
|
319
501
|
// 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
|
|
@@ -369,9 +551,65 @@
|
|
|
369
551
|
return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
|
|
370
552
|
}
|
|
371
553
|
|
|
554
|
+
// 新调用的槽位:保留原始字段形状,只保证 function.arguments 是字符串
|
|
555
|
+
function normalizeCall(toolCall) {
|
|
556
|
+
const fn = toolCall.function || {};
|
|
557
|
+
return {
|
|
558
|
+
...toolCall,
|
|
559
|
+
function: {
|
|
560
|
+
...fn,
|
|
561
|
+
arguments: typeof fn.arguments === "string" ? fn.arguments : ""
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
// 续片:按 index 优先归并,否则追加到最后一个槽位
|
|
567
|
+
// #doc:merge
|
|
568
|
+
function mergeToolCall(state, toolCall) {
|
|
569
|
+
if (!state._toolSlots) state._toolSlots = new Map();
|
|
570
|
+
|
|
571
|
+
const calls = state.tool_calls;
|
|
572
|
+
const index = typeof toolCall.index === "number" ? toolCall.index : null;
|
|
573
|
+
const hasId = typeof toolCall.id === "string" && toolCall.id !== "";
|
|
574
|
+
|
|
575
|
+
// 带 id 视为新调用;同 id 重复下发时复用已有槽位
|
|
576
|
+
if (hasId) {
|
|
577
|
+
const exist = calls.find(call => call.id === toolCall.id);
|
|
578
|
+
if (exist) {
|
|
579
|
+
appendArguments(exist, toolCall);
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
const slot = normalizeCall(toolCall);
|
|
583
|
+
calls.push(slot);
|
|
584
|
+
if (index !== null) state._toolSlots.set(index, slot);
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
let slot = index !== null ? state._toolSlots.get(index) : null;
|
|
589
|
+
if (!slot && calls.length) slot = calls[calls.length - 1];
|
|
590
|
+
|
|
591
|
+
// 首片就没有 id:建占位槽位,后续分片补齐参数
|
|
592
|
+
if (!slot) {
|
|
593
|
+
slot = normalizeCall(toolCall);
|
|
594
|
+
calls.push(slot);
|
|
595
|
+
if (index !== null) state._toolSlots.set(index, slot);
|
|
596
|
+
return;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
appendArguments(slot, toolCall);
|
|
600
|
+
// #end
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function appendArguments(slot, toolCall) {
|
|
604
|
+
const fn = toolCall.function || {};
|
|
605
|
+
if (fn.name && !slot.function.name) slot.function.name = fn.name;
|
|
606
|
+
if (typeof fn.arguments === "string") slot.function.arguments += fn.arguments;
|
|
607
|
+
}
|
|
608
|
+
|
|
372
609
|
// 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
|
|
373
|
-
// 返回累积的 { content, tool_calls }
|
|
374
610
|
function handleChoices(choices, { logback, thinkback }, state) {
|
|
611
|
+
if (!Array.isArray(choices)) return;
|
|
612
|
+
|
|
375
613
|
for (let i = 0; i < choices.length; i++) {
|
|
376
614
|
const delta = choices[i].delta;
|
|
377
615
|
|
|
@@ -396,14 +634,10 @@
|
|
|
396
634
|
}
|
|
397
635
|
}
|
|
398
636
|
|
|
399
|
-
//
|
|
400
|
-
if (delta.tool_calls) {
|
|
637
|
+
// 工具调用分片
|
|
638
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
401
639
|
for (const toolCall of delta.tool_calls) {
|
|
402
|
-
|
|
403
|
-
state.tool_calls.push(toolCall);
|
|
404
|
-
} else {
|
|
405
|
-
state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
|
|
406
|
-
}
|
|
640
|
+
mergeToolCall(state, toolCall);
|
|
407
641
|
}
|
|
408
642
|
}
|
|
409
643
|
}
|
|
@@ -419,69 +653,164 @@
|
|
|
419
653
|
}
|
|
420
654
|
}
|
|
421
655
|
|
|
656
|
+
// 统一把各种错误形态收敛成 Error,保证 Promise 一定 settle
|
|
657
|
+
function toError(value, fallback) {
|
|
658
|
+
if (value instanceof Error) return value;
|
|
659
|
+
if (value && typeof value.message === "string") return new Error(value.message);
|
|
660
|
+
try {
|
|
661
|
+
return new Error(String(value));
|
|
662
|
+
} catch (e) {
|
|
663
|
+
return new Error(fallback || "模型请求失败");
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// HTTP 错误:尽量带出响应体里的 error.message,方便定位
|
|
668
|
+
function errorFromHttp(meta, body) {
|
|
669
|
+
const status = meta && meta.status;
|
|
670
|
+
let detail = "";
|
|
671
|
+
|
|
672
|
+
if (body) {
|
|
673
|
+
try {
|
|
674
|
+
const parsed = JSON.parse(body);
|
|
675
|
+
const raw = parsed && parsed.error;
|
|
676
|
+
detail = (raw && (raw.message || raw)) || "";
|
|
677
|
+
} catch (e) {
|
|
678
|
+
detail = String(body).slice(0, 200);
|
|
679
|
+
}
|
|
680
|
+
if (detail && typeof detail !== "string") detail = JSON.stringify(detail);
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
|
|
684
|
+
}
|
|
685
|
+
|
|
422
686
|
function completions(params, logback, thinkback) {
|
|
423
687
|
return new Promise((resolve, reject) => {
|
|
424
688
|
|
|
689
|
+
// #doc:state
|
|
425
690
|
const state = { content: "", tool_calls: [] };
|
|
426
691
|
const callbacks = { logback, thinkback };
|
|
427
692
|
|
|
428
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
|
|
429
720
|
|
|
430
721
|
fetch$1({
|
|
431
|
-
url: `${this.baseURL}/chat/completions`,
|
|
722
|
+
url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
|
|
432
723
|
method: "POST",
|
|
433
724
|
headers: {
|
|
434
725
|
"Authorization": `Bearer ${this.apiKey}`,
|
|
435
726
|
"Content-Type": "application/json",
|
|
436
727
|
},
|
|
437
|
-
body: JSON.stringify(
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
stream: params.stream,
|
|
442
|
-
})
|
|
728
|
+
body: JSON.stringify(body),
|
|
729
|
+
timeout: params.timeout != null ? params.timeout : this.timeout,
|
|
730
|
+
signal: params.signal
|
|
731
|
+
// #end
|
|
443
732
|
}).then(res => {
|
|
444
733
|
|
|
734
|
+
// 非 2xx:非流式等错误体读完再判,流式直接中断
|
|
735
|
+
res.on("http-error", meta => {
|
|
736
|
+
httpError = meta;
|
|
737
|
+
if (params.stream) fail(errorFromHttp(meta));
|
|
738
|
+
});
|
|
739
|
+
|
|
445
740
|
// 数据流
|
|
741
|
+
// #doc:stream
|
|
446
742
|
res.on("data", chunk => {
|
|
447
|
-
if (
|
|
448
|
-
|
|
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 {
|
|
743
|
+
if (settled) return;
|
|
744
|
+
if (!params.stream) {
|
|
457
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);
|
|
458
762
|
}
|
|
459
763
|
});
|
|
460
764
|
|
|
461
765
|
// 结束
|
|
462
766
|
res.on("end", () => {
|
|
463
767
|
if (!params.stream) {
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
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;
|
|
469
789
|
}
|
|
790
|
+
|
|
470
791
|
// 冲刷 <think> 标签截断残留
|
|
471
792
|
flushThinkBuffer(state, callbacks);
|
|
472
|
-
resolve
|
|
793
|
+
finish(resolve, { content: state.content, tool_calls: state.tool_calls });
|
|
473
794
|
});
|
|
474
795
|
|
|
475
|
-
res.on("error", err =>
|
|
476
|
-
}).catch(err =>
|
|
796
|
+
res.on("error", err => fail(err));
|
|
797
|
+
}).catch(err => fail(err));
|
|
477
798
|
|
|
478
799
|
});
|
|
479
800
|
}
|
|
480
801
|
|
|
802
|
+
// #doc:ctor
|
|
481
803
|
function Model(fields) {
|
|
482
804
|
this.model = fields.model;
|
|
483
805
|
this.apiKey = fields.apiKey;
|
|
484
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
|
|
485
814
|
}
|
|
486
815
|
|
|
487
816
|
Model.prototype.completions = completions;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auipage/model",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-alpha.0",
|
|
4
4
|
"description": "@auipage/model",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
},
|
|
31
31
|
"homepage": "https://github.com/handless-ui/auipage#readme",
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@auipage/fetch": "^0.
|
|
34
|
-
"@auipage/types": "^0.
|
|
33
|
+
"@auipage/fetch": "^0.2.0-alpha.0",
|
|
34
|
+
"@auipage/types": "^0.2.0-alpha.0"
|
|
35
35
|
}
|
|
36
36
|
}
|
package/src/completions.js
CHANGED
|
@@ -2,61 +2,148 @@ import { fetch } from "@auipage/fetch/src/index.js";
|
|
|
2
2
|
import parseString from "./parseString.js";
|
|
3
3
|
import handleChoices, { flushThinkBuffer } from "./streamHandler.js";
|
|
4
4
|
|
|
5
|
+
// 统一把各种错误形态收敛成 Error,保证 Promise 一定 settle
|
|
6
|
+
function toError(value, fallback) {
|
|
7
|
+
if (value instanceof Error) return value;
|
|
8
|
+
if (value && typeof value.message === "string") return new Error(value.message);
|
|
9
|
+
try {
|
|
10
|
+
return new Error(String(value));
|
|
11
|
+
} catch (e) {
|
|
12
|
+
return new Error(fallback || "模型请求失败");
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// HTTP 错误:尽量带出响应体里的 error.message,方便定位
|
|
17
|
+
function errorFromHttp(meta, body) {
|
|
18
|
+
const status = meta && meta.status;
|
|
19
|
+
let detail = "";
|
|
20
|
+
|
|
21
|
+
if (body) {
|
|
22
|
+
try {
|
|
23
|
+
const parsed = JSON.parse(body);
|
|
24
|
+
const raw = parsed && parsed.error;
|
|
25
|
+
detail = (raw && (raw.message || raw)) || "";
|
|
26
|
+
} catch (e) {
|
|
27
|
+
detail = String(body).slice(0, 200);
|
|
28
|
+
}
|
|
29
|
+
if (detail && typeof detail !== "string") detail = JSON.stringify(detail);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
|
|
33
|
+
}
|
|
34
|
+
|
|
5
35
|
export default function completions(params, logback, thinkback) {
|
|
6
36
|
return new Promise((resolve, reject) => {
|
|
7
37
|
|
|
38
|
+
// #doc:state
|
|
8
39
|
const state = { content: "", tool_calls: [] };
|
|
9
40
|
const callbacks = { logback, thinkback };
|
|
10
41
|
|
|
11
42
|
let buffer = "";
|
|
43
|
+
let httpError = null;
|
|
44
|
+
let streamError = null;
|
|
45
|
+
let settled = false;
|
|
46
|
+
|
|
47
|
+
const finish = (fn, value) => {
|
|
48
|
+
if (settled) return;
|
|
49
|
+
settled = true;
|
|
50
|
+
fn(value);
|
|
51
|
+
};
|
|
52
|
+
const fail = value => finish(reject, toError(value, "模型请求失败"));
|
|
53
|
+
// #end
|
|
54
|
+
|
|
55
|
+
// #doc:body
|
|
56
|
+
const body = {
|
|
57
|
+
model: this.model,
|
|
58
|
+
messages: params.messages,
|
|
59
|
+
tools: params.tools ? params.tools.map(tool => tool.description) : [],
|
|
60
|
+
stream: params.stream,
|
|
61
|
+
};
|
|
62
|
+
const temperature = params.temperature != null ? params.temperature : this.temperature;
|
|
63
|
+
const topP = params.topP != null ? params.topP : this.topP;
|
|
64
|
+
const maxTokens = params.maxTokens != null ? params.maxTokens : this.maxTokens;
|
|
65
|
+
if (temperature != null) body.temperature = temperature;
|
|
66
|
+
if (topP != null) body.top_p = topP;
|
|
67
|
+
if (maxTokens != null) body.max_tokens = maxTokens;
|
|
68
|
+
// #end
|
|
12
69
|
|
|
13
70
|
fetch({
|
|
14
|
-
url: `${this.baseURL}/chat/completions`,
|
|
71
|
+
url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
|
|
15
72
|
method: "POST",
|
|
16
73
|
headers: {
|
|
17
74
|
"Authorization": `Bearer ${this.apiKey}`,
|
|
18
75
|
"Content-Type": "application/json",
|
|
19
76
|
},
|
|
20
|
-
body: JSON.stringify(
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
stream: params.stream,
|
|
25
|
-
})
|
|
77
|
+
body: JSON.stringify(body),
|
|
78
|
+
timeout: params.timeout != null ? params.timeout : this.timeout,
|
|
79
|
+
signal: params.signal
|
|
80
|
+
// #end
|
|
26
81
|
}).then(res => {
|
|
27
82
|
|
|
83
|
+
// 非 2xx:非流式等错误体读完再判,流式直接中断
|
|
84
|
+
res.on("http-error", meta => {
|
|
85
|
+
httpError = meta;
|
|
86
|
+
if (params.stream) fail(errorFromHttp(meta));
|
|
87
|
+
});
|
|
88
|
+
|
|
28
89
|
// 数据流
|
|
90
|
+
// #doc:stream
|
|
29
91
|
res.on("data", chunk => {
|
|
30
|
-
if (
|
|
31
|
-
|
|
32
|
-
if (Array.isArray(parsed)) {
|
|
33
|
-
for (const item of parsed) {
|
|
34
|
-
handleChoices(item.choices, callbacks, state);
|
|
35
|
-
}
|
|
36
|
-
} else {
|
|
37
|
-
handleChoices(parsed.choices, callbacks, state);
|
|
38
|
-
}
|
|
39
|
-
} else {
|
|
92
|
+
if (settled) return;
|
|
93
|
+
if (!params.stream) {
|
|
40
94
|
buffer += chunk;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
let parsed;
|
|
98
|
+
try {
|
|
99
|
+
parsed = parseString(chunk.toString());
|
|
100
|
+
} catch (e) {
|
|
101
|
+
streamError = e;
|
|
102
|
+
fail(e);
|
|
103
|
+
// #end
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
const items = Array.isArray(parsed) ? parsed : [parsed];
|
|
108
|
+
for (const item of items) handleChoices(item.choices, callbacks, state);
|
|
109
|
+
} catch (e) {
|
|
110
|
+
fail(e);
|
|
41
111
|
}
|
|
42
112
|
});
|
|
43
113
|
|
|
44
114
|
// 结束
|
|
45
115
|
res.on("end", () => {
|
|
46
116
|
if (!params.stream) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
117
|
+
if (httpError) {
|
|
118
|
+
fail(errorFromHttp(httpError, buffer));
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const parsed = parseString(buffer);
|
|
123
|
+
const choices = parsed && parsed.choices;
|
|
124
|
+
if (!choices || !choices[0] || !choices[0].message) {
|
|
125
|
+
throw new Error("模型响应缺少 choices[0].message");
|
|
126
|
+
}
|
|
127
|
+
handleChoices([{ delta: choices[0].message }], callbacks, state);
|
|
128
|
+
} catch (e) {
|
|
129
|
+
fail(e);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
} else if (streamError) {
|
|
133
|
+
fail(streamError);
|
|
134
|
+
return;
|
|
135
|
+
} else if (httpError) {
|
|
136
|
+
fail(errorFromHttp(httpError));
|
|
137
|
+
return;
|
|
52
138
|
}
|
|
139
|
+
|
|
53
140
|
// 冲刷 <think> 标签截断残留
|
|
54
141
|
flushThinkBuffer(state, callbacks);
|
|
55
|
-
resolve
|
|
142
|
+
finish(resolve, { content: state.content, tool_calls: state.tool_calls });
|
|
56
143
|
});
|
|
57
144
|
|
|
58
|
-
res.on("error", err =>
|
|
59
|
-
}).catch(err =>
|
|
145
|
+
res.on("error", err => fail(err));
|
|
146
|
+
}).catch(err => fail(err));
|
|
60
147
|
|
|
61
148
|
});
|
|
62
149
|
}
|
package/src/index.js
CHANGED
|
@@ -1,9 +1,17 @@
|
|
|
1
1
|
import completions from "./completions.js";
|
|
2
2
|
|
|
3
|
+
// #doc:ctor
|
|
3
4
|
function Model(fields) {
|
|
4
5
|
this.model = fields.model;
|
|
5
6
|
this.apiKey = fields.apiKey;
|
|
6
7
|
this.baseURL = fields.baseURL;
|
|
8
|
+
|
|
9
|
+
// 可选请求参数:显式传入才写进请求体,保持旧行为不变
|
|
10
|
+
this.temperature = fields.temperature;
|
|
11
|
+
this.topP = fields.topP;
|
|
12
|
+
this.maxTokens = fields.maxTokens;
|
|
13
|
+
this.timeout = fields.timeout;
|
|
14
|
+
// #end
|
|
7
15
|
}
|
|
8
16
|
|
|
9
17
|
Model.prototype.completions = completions;
|
package/src/parseString.js
CHANGED
|
@@ -1,16 +1,57 @@
|
|
|
1
|
-
// 字符串转JSON
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
// 字符串转 JSON,适配 LLM 返回的各种流式格式:
|
|
2
|
+
// 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
|
|
3
|
+
function stripDataPrefix(text) {
|
|
4
|
+
return text.replace(/^data:\s*/, "");
|
|
5
|
+
}
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
7
|
+
function tryParse(text) {
|
|
8
|
+
try {
|
|
9
|
+
return { value: JSON.parse(text) };
|
|
10
|
+
} catch (e) {
|
|
11
|
+
return null;
|
|
10
12
|
}
|
|
13
|
+
}
|
|
11
14
|
|
|
12
|
-
|
|
13
|
-
|
|
15
|
+
function parseOne(text, origin) {
|
|
16
|
+
const parsed = tryParse(stripDataPrefix(text.trim()));
|
|
17
|
+
if (!parsed) throw new SyntaxError("模型返回无法解析:" + String(origin).slice(0, 120));
|
|
18
|
+
return parsed.value;
|
|
19
|
+
}
|
|
14
20
|
|
|
21
|
+
// 错误响应体({"error":{...}})直接抛出,交给调用方转成 reject
|
|
22
|
+
function checkError(result) {
|
|
23
|
+
if (Array.isArray(result)) {
|
|
24
|
+
for (const item of result) {
|
|
25
|
+
if (item && item.error) throw item.error;
|
|
26
|
+
}
|
|
27
|
+
return result;
|
|
28
|
+
}
|
|
29
|
+
if (result && result.error) throw result.error;
|
|
15
30
|
return result;
|
|
16
|
-
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export default function (value) {
|
|
34
|
+
let text = String(value == null ? "" : value).trim();
|
|
35
|
+
|
|
36
|
+
// 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
|
|
37
|
+
// #doc:done
|
|
38
|
+
text = text.replace(/data:\s*\[DONE\]$/, "").trim();
|
|
39
|
+
if (text === "" || text === "[DONE]") return [];
|
|
40
|
+
// #end
|
|
41
|
+
|
|
42
|
+
// 单条:带 data: 前缀或裸 JSON
|
|
43
|
+
let single = tryParse(stripDataPrefix(text)) || tryParse(text);
|
|
44
|
+
if (single) return checkError(single.value);
|
|
45
|
+
|
|
46
|
+
// 多条 SSE 事件,以 "\n\ndata: " 分隔
|
|
47
|
+
// #doc:multi
|
|
48
|
+
const parts = text.split(/\r?\n\r?\ndata: /);
|
|
49
|
+
if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
|
|
50
|
+
// #end
|
|
51
|
+
|
|
52
|
+
// NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
|
|
53
|
+
const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
|
|
54
|
+
if (lines.length > 1) return checkError(lines.map(line => parseOne(line, text)));
|
|
55
|
+
|
|
56
|
+
throw new SyntaxError("模型返回无法解析:" + text.slice(0, 120));
|
|
57
|
+
}
|
package/src/reasoning.js
CHANGED
|
@@ -16,12 +16,14 @@ const CLOSE = "</think>";
|
|
|
16
16
|
|
|
17
17
|
// 计算文本尾部与标签前缀的最长匹配长度
|
|
18
18
|
// 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
|
|
19
|
+
// #doc:partial
|
|
19
20
|
function partialTagLength(text, tag) {
|
|
20
21
|
const max = Math.min(tag.length - 1, text.length);
|
|
21
22
|
for (let len = max; len > 0; len--) {
|
|
22
23
|
if (text.endsWith(tag.slice(0, len))) return len;
|
|
23
24
|
}
|
|
24
25
|
return 0;
|
|
26
|
+
// #end
|
|
25
27
|
}
|
|
26
28
|
|
|
27
29
|
// 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
|
package/src/streamHandler.js
CHANGED
|
@@ -1,8 +1,64 @@
|
|
|
1
1
|
import parseReasoning, { extractThink, flushThink } from "./reasoning.js";
|
|
2
2
|
|
|
3
|
+
// 新调用的槽位:保留原始字段形状,只保证 function.arguments 是字符串
|
|
4
|
+
function normalizeCall(toolCall) {
|
|
5
|
+
const fn = toolCall.function || {};
|
|
6
|
+
return {
|
|
7
|
+
...toolCall,
|
|
8
|
+
function: {
|
|
9
|
+
...fn,
|
|
10
|
+
arguments: typeof fn.arguments === "string" ? fn.arguments : ""
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// 续片:按 index 优先归并,否则追加到最后一个槽位
|
|
16
|
+
// #doc:merge
|
|
17
|
+
function mergeToolCall(state, toolCall) {
|
|
18
|
+
if (!state._toolSlots) state._toolSlots = new Map();
|
|
19
|
+
|
|
20
|
+
const calls = state.tool_calls;
|
|
21
|
+
const index = typeof toolCall.index === "number" ? toolCall.index : null;
|
|
22
|
+
const hasId = typeof toolCall.id === "string" && toolCall.id !== "";
|
|
23
|
+
|
|
24
|
+
// 带 id 视为新调用;同 id 重复下发时复用已有槽位
|
|
25
|
+
if (hasId) {
|
|
26
|
+
const exist = calls.find(call => call.id === toolCall.id);
|
|
27
|
+
if (exist) {
|
|
28
|
+
appendArguments(exist, toolCall);
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
const slot = normalizeCall(toolCall);
|
|
32
|
+
calls.push(slot);
|
|
33
|
+
if (index !== null) state._toolSlots.set(index, slot);
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
let slot = index !== null ? state._toolSlots.get(index) : null;
|
|
38
|
+
if (!slot && calls.length) slot = calls[calls.length - 1];
|
|
39
|
+
|
|
40
|
+
// 首片就没有 id:建占位槽位,后续分片补齐参数
|
|
41
|
+
if (!slot) {
|
|
42
|
+
slot = normalizeCall(toolCall);
|
|
43
|
+
calls.push(slot);
|
|
44
|
+
if (index !== null) state._toolSlots.set(index, slot);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
appendArguments(slot, toolCall);
|
|
49
|
+
// #end
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function appendArguments(slot, toolCall) {
|
|
53
|
+
const fn = toolCall.function || {};
|
|
54
|
+
if (fn.name && !slot.function.name) slot.function.name = fn.name;
|
|
55
|
+
if (typeof fn.arguments === "string") slot.function.arguments += fn.arguments;
|
|
56
|
+
}
|
|
57
|
+
|
|
3
58
|
// 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
|
|
4
|
-
// 返回累积的 { content, tool_calls }
|
|
5
59
|
export default function handleChoices(choices, { logback, thinkback }, state) {
|
|
60
|
+
if (!Array.isArray(choices)) return;
|
|
61
|
+
|
|
6
62
|
for (let i = 0; i < choices.length; i++) {
|
|
7
63
|
const delta = choices[i].delta;
|
|
8
64
|
|
|
@@ -27,14 +83,10 @@ export default function handleChoices(choices, { logback, thinkback }, state) {
|
|
|
27
83
|
}
|
|
28
84
|
}
|
|
29
85
|
|
|
30
|
-
//
|
|
31
|
-
if (delta.tool_calls) {
|
|
86
|
+
// 工具调用分片
|
|
87
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
32
88
|
for (const toolCall of delta.tool_calls) {
|
|
33
|
-
|
|
34
|
-
state.tool_calls.push(toolCall);
|
|
35
|
-
} else {
|
|
36
|
-
state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
|
|
37
|
-
}
|
|
89
|
+
mergeToolCall(state, toolCall);
|
|
38
90
|
}
|
|
39
91
|
}
|
|
40
92
|
}
|
package/types/completions.d.ts
CHANGED