@auipage/model 0.1.0 → 0.2.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AUTHORS.txt +6 -6
- package/CHANGELOG +29 -4
- package/README.md +83 -93
- package/dist/index.js +789 -460
- package/package.json +3 -3
- package/src/completions.js +149 -62
- package/src/index.js +19 -11
- package/src/parseString.js +57 -16
- package/src/reasoning.js +80 -78
- package/src/streamHandler.js +103 -51
- package/types/completions.d.ts +35 -31
- package/types/index.d.ts +13 -13
- package/types/model.d.ts +33 -33
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
|
@@ -1,62 +1,149 @@
|
|
|
1
|
-
import { fetch } from "@auipage/fetch/src/index.js";
|
|
2
|
-
import parseString from "./parseString.js";
|
|
3
|
-
import handleChoices, { flushThinkBuffer } from "./streamHandler.js";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
})
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
1
|
+
import { fetch } from "@auipage/fetch/src/index.js";
|
|
2
|
+
import parseString from "./parseString.js";
|
|
3
|
+
import handleChoices, { flushThinkBuffer } from "./streamHandler.js";
|
|
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
|
+
|
|
35
|
+
export default function completions(params, logback, thinkback) {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
|
|
38
|
+
// #doc:state
|
|
39
|
+
const state = { content: "", tool_calls: [] };
|
|
40
|
+
const callbacks = { logback, thinkback };
|
|
41
|
+
|
|
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
|
|
69
|
+
|
|
70
|
+
fetch({
|
|
71
|
+
url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
|
|
72
|
+
method: "POST",
|
|
73
|
+
headers: {
|
|
74
|
+
"Authorization": `Bearer ${this.apiKey}`,
|
|
75
|
+
"Content-Type": "application/json",
|
|
76
|
+
},
|
|
77
|
+
body: JSON.stringify(body),
|
|
78
|
+
timeout: params.timeout != null ? params.timeout : this.timeout,
|
|
79
|
+
signal: params.signal
|
|
80
|
+
// #end
|
|
81
|
+
}).then(res => {
|
|
82
|
+
|
|
83
|
+
// 非 2xx:非流式等错误体读完再判,流式直接中断
|
|
84
|
+
res.on("http-error", meta => {
|
|
85
|
+
httpError = meta;
|
|
86
|
+
if (params.stream) fail(errorFromHttp(meta));
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// 数据流
|
|
90
|
+
// #doc:stream
|
|
91
|
+
res.on("data", chunk => {
|
|
92
|
+
if (settled) return;
|
|
93
|
+
if (!params.stream) {
|
|
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);
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// 结束
|
|
115
|
+
res.on("end", () => {
|
|
116
|
+
if (!params.stream) {
|
|
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;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// 冲刷 <think> 标签截断残留
|
|
141
|
+
flushThinkBuffer(state, callbacks);
|
|
142
|
+
finish(resolve, { content: state.content, tool_calls: state.tool_calls });
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
res.on("error", err => fail(err));
|
|
146
|
+
}).catch(err => fail(err));
|
|
147
|
+
|
|
148
|
+
});
|
|
149
|
+
}
|
package/src/index.js
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
|
-
import completions from "./completions.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
this.
|
|
6
|
-
this.
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
1
|
+
import completions from "./completions.js";
|
|
2
|
+
|
|
3
|
+
// #doc:ctor
|
|
4
|
+
function Model(fields) {
|
|
5
|
+
this.model = fields.model;
|
|
6
|
+
this.apiKey = fields.apiKey;
|
|
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
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
Model.prototype.completions = completions;
|
|
18
|
+
|
|
19
|
+
export { Model };
|
package/src/parseString.js
CHANGED
|
@@ -1,16 +1,57 @@
|
|
|
1
|
-
// 字符串转JSON
|
|
2
|
-
//
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
return
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
1
|
+
// 字符串转 JSON,适配 LLM 返回的各种流式格式:
|
|
2
|
+
// 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
|
|
3
|
+
function stripDataPrefix(text) {
|
|
4
|
+
return text.replace(/^data:\s*/, "");
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
function tryParse(text) {
|
|
8
|
+
try {
|
|
9
|
+
return { value: JSON.parse(text) };
|
|
10
|
+
} catch (e) {
|
|
11
|
+
return null;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
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
|
+
}
|
|
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;
|
|
30
|
+
return result;
|
|
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
|
@@ -1,78 +1,80 @@
|
|
|
1
|
-
// 解析 LLM 返回的推理内容(reasoning / reasoning_content)
|
|
2
|
-
// 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
|
|
3
|
-
export default function parseReasoning(reasoning, content) {
|
|
4
|
-
if (!/<\/think>/.test(reasoning)) return reasoning;
|
|
5
|
-
|
|
6
|
-
const parts = reasoning.split("</think>");
|
|
7
|
-
const thinkPart = parts[0].replace("<think>", "");
|
|
8
|
-
return {
|
|
9
|
-
reasoning: thinkPart,
|
|
10
|
-
content: parts[1] + (content || "")
|
|
11
|
-
};
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
const OPEN = "<think>";
|
|
15
|
-
const CLOSE = "</think>";
|
|
16
|
-
|
|
17
|
-
// 计算文本尾部与标签前缀的最长匹配长度
|
|
18
|
-
// 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
1
|
+
// 解析 LLM 返回的推理内容(reasoning / reasoning_content)
|
|
2
|
+
// 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
|
|
3
|
+
export default function parseReasoning(reasoning, content) {
|
|
4
|
+
if (!/<\/think>/.test(reasoning)) return reasoning;
|
|
5
|
+
|
|
6
|
+
const parts = reasoning.split("</think>");
|
|
7
|
+
const thinkPart = parts[0].replace("<think>", "");
|
|
8
|
+
return {
|
|
9
|
+
reasoning: thinkPart,
|
|
10
|
+
content: parts[1] + (content || "")
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const OPEN = "<think>";
|
|
15
|
+
const CLOSE = "</think>";
|
|
16
|
+
|
|
17
|
+
// 计算文本尾部与标签前缀的最长匹配长度
|
|
18
|
+
// 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
|
|
19
|
+
// #doc:partial
|
|
20
|
+
function partialTagLength(text, tag) {
|
|
21
|
+
const max = Math.min(tag.length - 1, text.length);
|
|
22
|
+
for (let len = max; len > 0; len--) {
|
|
23
|
+
if (text.endsWith(tag.slice(0, len))) return len;
|
|
24
|
+
}
|
|
25
|
+
return 0;
|
|
26
|
+
// #end
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
|
|
30
|
+
// 这里把它剥离出来:思考片段归 thinkback,其余归正文
|
|
31
|
+
// 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
|
|
32
|
+
// 返回 { thinking, content }
|
|
33
|
+
export function extractThink(content, state) {
|
|
34
|
+
const buf = (state.thinkBuf || "") + content;
|
|
35
|
+
state.thinkBuf = "";
|
|
36
|
+
|
|
37
|
+
// 正处于思考块内:寻找 </think>
|
|
38
|
+
if (state.inThink) {
|
|
39
|
+
const end = buf.indexOf(CLOSE);
|
|
40
|
+
if (end === -1) {
|
|
41
|
+
const hold = partialTagLength(buf, CLOSE);
|
|
42
|
+
state.thinkBuf = buf.slice(buf.length - hold);
|
|
43
|
+
return { thinking: buf.slice(0, buf.length - hold), content: "" };
|
|
44
|
+
}
|
|
45
|
+
state.inThink = false;
|
|
46
|
+
const rest = extractThink(buf.slice(end + CLOSE.length), state);
|
|
47
|
+
return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 正常正文:寻找 <think>
|
|
51
|
+
const start = buf.indexOf(OPEN);
|
|
52
|
+
if (start === -1) {
|
|
53
|
+
const hold = partialTagLength(buf, OPEN);
|
|
54
|
+
state.thinkBuf = buf.slice(buf.length - hold);
|
|
55
|
+
return { thinking: "", content: buf.slice(0, buf.length - hold) };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const end = buf.indexOf(CLOSE, start);
|
|
59
|
+
if (end !== -1) {
|
|
60
|
+
const rest = extractThink(buf.slice(end + CLOSE.length), state);
|
|
61
|
+
return {
|
|
62
|
+
thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
|
|
63
|
+
content: buf.slice(0, start) + rest.content
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 有 <think> 无 </think>:进入思考态
|
|
68
|
+
state.inThink = true;
|
|
69
|
+
const body = buf.slice(start + OPEN.length);
|
|
70
|
+
const hold = partialTagLength(body, CLOSE);
|
|
71
|
+
state.thinkBuf = body.slice(body.length - hold);
|
|
72
|
+
return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
|
|
76
|
+
export function flushThink(state) {
|
|
77
|
+
const buf = state.thinkBuf || "";
|
|
78
|
+
state.thinkBuf = "";
|
|
79
|
+
return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
|
|
80
|
+
}
|
package/src/streamHandler.js
CHANGED
|
@@ -1,51 +1,103 @@
|
|
|
1
|
-
import parseReasoning, { extractThink, flushThink } from "./reasoning.js";
|
|
2
|
-
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
1
|
+
import parseReasoning, { extractThink, flushThink } from "./reasoning.js";
|
|
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
|
+
|
|
58
|
+
// 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
|
|
59
|
+
export default function handleChoices(choices, { logback, thinkback }, state) {
|
|
60
|
+
if (!Array.isArray(choices)) return;
|
|
61
|
+
|
|
62
|
+
for (let i = 0; i < choices.length; i++) {
|
|
63
|
+
const delta = choices[i].delta;
|
|
64
|
+
|
|
65
|
+
// 推理内容(reasoning / reasoning_content 字段)
|
|
66
|
+
let reasoning = delta.reasoning || delta.reasoning_content;
|
|
67
|
+
if (reasoning) {
|
|
68
|
+
const parsed = parseReasoning(reasoning, delta.content);
|
|
69
|
+
if (typeof parsed === "object") {
|
|
70
|
+
reasoning = parsed.reasoning;
|
|
71
|
+
delta.content = parsed.content;
|
|
72
|
+
}
|
|
73
|
+
if (thinkback) thinkback(reasoning);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
|
|
77
|
+
if (delta.content) {
|
|
78
|
+
const extracted = extractThink(delta.content, state);
|
|
79
|
+
if (extracted.thinking && thinkback) thinkback(extracted.thinking);
|
|
80
|
+
if (extracted.content) {
|
|
81
|
+
if (logback) logback(extracted.content);
|
|
82
|
+
state.content += extracted.content;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// 工具调用分片
|
|
87
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
88
|
+
for (const toolCall of delta.tool_calls) {
|
|
89
|
+
mergeToolCall(state, toolCall);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
|
|
96
|
+
export function flushThinkBuffer(state, { logback, thinkback }) {
|
|
97
|
+
const flushed = flushThink(state);
|
|
98
|
+
if (flushed.thinking && thinkback) thinkback(flushed.thinking);
|
|
99
|
+
if (flushed.content) {
|
|
100
|
+
if (logback) logback(flushed.content);
|
|
101
|
+
state.content += flushed.content;
|
|
102
|
+
}
|
|
103
|
+
}
|