@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auipage/model",
3
- "version": "0.1.0-alpha.4",
3
+ "version": "0.1.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.1.0-alpha.4",
34
- "@auipage/types": "^0.1.0-alpha.4"
33
+ "@auipage/fetch": "^0.1.0",
34
+ "@auipage/types": "^0.1.0"
35
35
  }
36
36
  }
@@ -1,60 +1,62 @@
1
- import { fetch } from "@auipage/fetch/src/index.js";
2
- import parseString from "./parseString.js";
3
- import handleChoices from "./streamHandler.js";
4
-
5
- export default function completions(params, logback, thinkback) {
6
- return new Promise((resolve, reject) => {
7
-
8
- const state = { content: "", tool_calls: [] };
9
- const callbacks = { logback, thinkback };
10
-
11
- let buffer = "";
12
-
13
- fetch({
14
- url: `${this.baseURL}/chat/completions`,
15
- method: "POST",
16
- headers: {
17
- "Authorization": `Bearer ${this.apiKey}`,
18
- "Content-Type": "application/json",
19
- },
20
- body: JSON.stringify({
21
- model: this.model,
22
- messages: params.messages,
23
- tools: params.tools ? params.tools.map(tool => tool.description) : [],
24
- stream: params.stream,
25
- })
26
- }).then(res => {
27
-
28
- // 数据流
29
- res.on("data", chunk => {
30
- if (params.stream) {
31
- const parsed = parseString(chunk.toString());
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 {
40
- buffer += chunk;
41
- }
42
- });
43
-
44
- // 结束
45
- res.on("end", () => {
46
- if (!params.stream) {
47
- handleChoices(
48
- [{ delta: parseString(buffer).choices[0].message }],
49
- callbacks,
50
- state
51
- );
52
- }
53
- resolve({ content: state.content, tool_calls: state.tool_calls });
54
- });
55
-
56
- res.on("error", err => reject(err));
57
- }).catch(err => reject(err));
58
-
59
- });
60
- }
1
+ import { fetch } from "@auipage/fetch/src/index.js";
2
+ import parseString from "./parseString.js";
3
+ import handleChoices, { flushThinkBuffer } from "./streamHandler.js";
4
+
5
+ export default function completions(params, logback, thinkback) {
6
+ return new Promise((resolve, reject) => {
7
+
8
+ const state = { content: "", tool_calls: [] };
9
+ const callbacks = { logback, thinkback };
10
+
11
+ let buffer = "";
12
+
13
+ fetch({
14
+ url: `${this.baseURL}/chat/completions`,
15
+ method: "POST",
16
+ headers: {
17
+ "Authorization": `Bearer ${this.apiKey}`,
18
+ "Content-Type": "application/json",
19
+ },
20
+ body: JSON.stringify({
21
+ model: this.model,
22
+ messages: params.messages,
23
+ tools: params.tools ? params.tools.map(tool => tool.description) : [],
24
+ stream: params.stream,
25
+ })
26
+ }).then(res => {
27
+
28
+ // 数据流
29
+ res.on("data", chunk => {
30
+ if (params.stream) {
31
+ const parsed = parseString(chunk.toString());
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 {
40
+ buffer += chunk;
41
+ }
42
+ });
43
+
44
+ // 结束
45
+ res.on("end", () => {
46
+ if (!params.stream) {
47
+ handleChoices(
48
+ [{ delta: parseString(buffer).choices[0].message }],
49
+ callbacks,
50
+ state
51
+ );
52
+ }
53
+ // 冲刷 <think> 标签截断残留
54
+ flushThinkBuffer(state, callbacks);
55
+ resolve({ content: state.content, tool_calls: state.tool_calls });
56
+ });
57
+
58
+ res.on("error", err => reject(err));
59
+ }).catch(err => reject(err));
60
+
61
+ });
62
+ }
package/src/index.js CHANGED
@@ -1,11 +1,11 @@
1
- import completions from "./completions.js";
2
-
3
- function Model(fields) {
4
- this.model = fields.model;
5
- this.apiKey = fields.apiKey;
6
- this.baseURL = fields.baseURL;
7
- }
8
-
9
- Model.prototype.completions = completions;
10
-
11
- export { Model };
1
+ import completions from "./completions.js";
2
+
3
+ function Model(fields) {
4
+ this.model = fields.model;
5
+ this.apiKey = fields.apiKey;
6
+ this.baseURL = fields.baseURL;
7
+ }
8
+
9
+ Model.prototype.completions = completions;
10
+
11
+ export { Model };
@@ -1,16 +1,16 @@
1
- // 字符串转JSON
2
- // 适配LLM返回数据格式
3
- export default function (value) {
4
- value = value.trim().replace(/^data: /, "").replace(/data: \[DONE\]$/, "");
5
-
6
- if (/\r{0,1}\n\r{0,1}\ndata: /.test(value)) {
7
- return JSON.parse("[" + (value.split(/\r{0,1}\n\r{0,1}\ndata: /)).join(",") + "]");
8
- } else if (value === "[DONE]") {
9
- return [];
10
- }
11
-
12
- let result = JSON.parse(value);
13
- if (result.error) throw result.error;
14
-
15
- return result;
1
+ // 字符串转JSON
2
+ // 适配LLM返回数据格式
3
+ export default function (value) {
4
+ value = value.trim().replace(/^data: /, "").replace(/data: \[DONE\]$/, "");
5
+
6
+ if (/\r{0,1}\n\r{0,1}\ndata: /.test(value)) {
7
+ return JSON.parse("[" + (value.split(/\r{0,1}\n\r{0,1}\ndata: /)).join(",") + "]");
8
+ } else if (value === "[DONE]") {
9
+ return [];
10
+ }
11
+
12
+ let result = JSON.parse(value);
13
+ if (result.error) throw result.error;
14
+
15
+ return result;
16
16
  };
package/src/reasoning.js CHANGED
@@ -1,12 +1,78 @@
1
- // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
2
- // 将 <think>...</think> 形式的内容从 delta.content 中剥离出来
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: thinkPart[1] + (content || "")
11
- };
12
- }
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
+ function partialTagLength(text, tag) {
20
+ const max = Math.min(tag.length - 1, text.length);
21
+ for (let len = max; len > 0; len--) {
22
+ if (text.endsWith(tag.slice(0, len))) return len;
23
+ }
24
+ return 0;
25
+ }
26
+
27
+ // 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
28
+ // 这里把它剥离出来:思考片段归 thinkback,其余归正文
29
+ // 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
30
+ // 返回 { thinking, content }
31
+ export function extractThink(content, state) {
32
+ const buf = (state.thinkBuf || "") + content;
33
+ state.thinkBuf = "";
34
+
35
+ // 正处于思考块内:寻找 </think>
36
+ if (state.inThink) {
37
+ const end = buf.indexOf(CLOSE);
38
+ if (end === -1) {
39
+ const hold = partialTagLength(buf, CLOSE);
40
+ state.thinkBuf = buf.slice(buf.length - hold);
41
+ return { thinking: buf.slice(0, buf.length - hold), content: "" };
42
+ }
43
+ state.inThink = false;
44
+ const rest = extractThink(buf.slice(end + CLOSE.length), state);
45
+ return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
46
+ }
47
+
48
+ // 正常正文:寻找 <think>
49
+ const start = buf.indexOf(OPEN);
50
+ if (start === -1) {
51
+ const hold = partialTagLength(buf, OPEN);
52
+ state.thinkBuf = buf.slice(buf.length - hold);
53
+ return { thinking: "", content: buf.slice(0, buf.length - hold) };
54
+ }
55
+
56
+ const end = buf.indexOf(CLOSE, start);
57
+ if (end !== -1) {
58
+ const rest = extractThink(buf.slice(end + CLOSE.length), state);
59
+ return {
60
+ thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
61
+ content: buf.slice(0, start) + rest.content
62
+ };
63
+ }
64
+
65
+ // 有 <think> 无 </think>:进入思考态
66
+ state.inThink = true;
67
+ const body = buf.slice(start + OPEN.length);
68
+ const hold = partialTagLength(body, CLOSE);
69
+ state.thinkBuf = body.slice(body.length - hold);
70
+ return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
71
+ }
72
+
73
+ // 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
74
+ export function flushThink(state) {
75
+ const buf = state.thinkBuf || "";
76
+ state.thinkBuf = "";
77
+ return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
78
+ }
@@ -1,37 +1,51 @@
1
- import parseReasoning from "./reasoning.js";
2
-
3
- // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
4
- // 返回累积的 { content, tool_calls }
5
- export default function handleChoices(choices, { logback, thinkback }, state) {
6
- for (let i = 0; i < choices.length; i++) {
7
- const delta = choices[i].delta;
8
-
9
- // 推理内容
10
- let reasoning = delta.reasoning || delta.reasoning_content;
11
- if (reasoning) {
12
- const parsed = parseReasoning(reasoning, delta.content);
13
- if (typeof parsed === "object") {
14
- reasoning = parsed.reasoning;
15
- delta.content = parsed.content;
16
- }
17
- if (thinkback) thinkback(reasoning);
18
- }
19
-
20
- // 正文内容
21
- if (delta.content) {
22
- if (logback) logback(delta.content);
23
- state.content += delta.content;
24
- }
25
-
26
- // 工具调用
27
- if (delta.tool_calls) {
28
- for (const toolCall of delta.tool_calls) {
29
- if (toolCall.id) {
30
- state.tool_calls.push(toolCall);
31
- } else {
32
- state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
33
- }
34
- }
35
- }
36
- }
37
- }
1
+ import parseReasoning, { extractThink, flushThink } from "./reasoning.js";
2
+
3
+ // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
4
+ // 返回累积的 { content, tool_calls }
5
+ export default function handleChoices(choices, { logback, thinkback }, state) {
6
+ for (let i = 0; i < choices.length; i++) {
7
+ const delta = choices[i].delta;
8
+
9
+ // 推理内容(reasoning / reasoning_content 字段)
10
+ let reasoning = delta.reasoning || delta.reasoning_content;
11
+ if (reasoning) {
12
+ const parsed = parseReasoning(reasoning, delta.content);
13
+ if (typeof parsed === "object") {
14
+ reasoning = parsed.reasoning;
15
+ delta.content = parsed.content;
16
+ }
17
+ if (thinkback) thinkback(reasoning);
18
+ }
19
+
20
+ // 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
21
+ if (delta.content) {
22
+ const extracted = extractThink(delta.content, state);
23
+ if (extracted.thinking && thinkback) thinkback(extracted.thinking);
24
+ if (extracted.content) {
25
+ if (logback) logback(extracted.content);
26
+ state.content += extracted.content;
27
+ }
28
+ }
29
+
30
+ // 工具调用
31
+ if (delta.tool_calls) {
32
+ for (const toolCall of delta.tool_calls) {
33
+ if (toolCall.id) {
34
+ state.tool_calls.push(toolCall);
35
+ } else {
36
+ state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
37
+ }
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ // 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
44
+ export function flushThinkBuffer(state, { logback, thinkback }) {
45
+ const flushed = flushThink(state);
46
+ if (flushed.thinking && thinkback) thinkback(flushed.thinking);
47
+ if (flushed.content) {
48
+ if (logback) logback(flushed.content);
49
+ state.content += flushed.content;
50
+ }
51
+ }
@@ -1,31 +1,31 @@
1
- /**
2
- * chat/completions 请求与响应类型
3
- */
4
- import type {
5
- ChatMessage,
6
- ModelToolCall,
7
- ToolDescription
8
- } from "@auipage/types";
9
-
10
- /** completions 入参(对应底层请求体中本包负责拼装的部分) */
11
- export interface CompletionsParams {
12
- messages: ChatMessage[];
13
- /** 工具列表,每项携带一个标准 description,发请求时自动取 .description */
14
- tools?: Array<{ description: ToolDescription }>;
15
- /** 是否流式请求,默认 false */
16
- stream?: boolean;
17
- }
18
-
19
- /**
20
- * 流式回调:每收到一个增量分片调用一次,参数是本次增量文本
21
- * (不是累计文本,拼接由调用方完成)。
22
- */
23
- export type StreamCallback = (delta: string) => void;
24
-
25
- /** completions 最终结果 */
26
- export interface CompletionsResult {
27
- /** 完整的正文内容 */
28
- content: string;
29
- /** 模型产生的工具调用(流式分片已自动拼装) */
30
- tool_calls: ModelToolCall[];
31
- }
1
+ /**
2
+ * chat/completions 请求与响应类型
3
+ */
4
+ import type {
5
+ ChatMessage,
6
+ ModelToolCall,
7
+ ToolDescription
8
+ } from "@auipage/types";
9
+
10
+ /** completions 入参(对应底层请求体中本包负责拼装的部分) */
11
+ export interface CompletionsParams {
12
+ messages: ChatMessage[];
13
+ /** 工具列表,每项携带一个标准 description,发请求时自动取 .description */
14
+ tools?: Array<{ description: ToolDescription }>;
15
+ /** 是否流式请求,默认 false */
16
+ stream?: boolean;
17
+ }
18
+
19
+ /**
20
+ * 流式回调:每收到一个增量分片调用一次,参数是本次增量文本
21
+ * (不是累计文本,拼接由调用方完成)。
22
+ */
23
+ export type StreamCallback = (delta: string) => void;
24
+
25
+ /** completions 最终结果 */
26
+ export interface CompletionsResult {
27
+ /** 完整的正文内容 */
28
+ content: string;
29
+ /** 模型产生的工具调用(流式分片已自动拼装) */
30
+ tool_calls: ModelToolCall[];
31
+ }
package/types/index.d.ts CHANGED
@@ -1,13 +1,13 @@
1
- /**
2
- * @auipage/model 类型入口
3
- *
4
- * 对 OpenAI 风格 chat/completions 的跨端请求封装,支持流式输出与工具调用。
5
- */
6
-
7
- export { Model } from "./model.js";
8
-
9
- export type {
10
- CompletionsParams,
11
- CompletionsResult,
12
- StreamCallback
13
- } from "./completions.js";
1
+ /**
2
+ * @auipage/model 类型入口
3
+ *
4
+ * 对 OpenAI 风格 chat/completions 的跨端请求封装,支持流式输出与工具调用。
5
+ */
6
+
7
+ export { Model } from "./model.js";
8
+
9
+ export type {
10
+ CompletionsParams,
11
+ CompletionsResult,
12
+ StreamCallback
13
+ } from "./completions.js";
package/types/model.d.ts CHANGED
@@ -1,33 +1,33 @@
1
- /**
2
- * Model 构造器:对 OpenAI 风格 /chat/completions 接口的薄封装
3
- */
4
- import type { ModelConfig } from "@auipage/types";
5
- import type {
6
- CompletionsParams,
7
- CompletionsResult,
8
- StreamCallback
9
- } from "./completions.js";
10
-
11
- export declare class Model {
12
- constructor(fields: ModelConfig);
13
-
14
- /** 模型名称 */
15
- model: string;
16
- /** 模型服务 API Key */
17
- apiKey: string;
18
- /** 模型服务 baseURL */
19
- baseURL: string;
20
-
21
- /**
22
- * 发起一次 chat/completions 请求。
23
- *
24
- * @param params 消息、工具、是否流式
25
- * @param logback 流式正文增量回调
26
- * @param thinkback 流式思维链增量回调
27
- */
28
- completions(
29
- params: CompletionsParams,
30
- logback?: StreamCallback,
31
- thinkback?: StreamCallback
32
- ): Promise<CompletionsResult>;
33
- }
1
+ /**
2
+ * Model 构造器:对 OpenAI 风格 /chat/completions 接口的薄封装
3
+ */
4
+ import type { ModelConfig } from "@auipage/types";
5
+ import type {
6
+ CompletionsParams,
7
+ CompletionsResult,
8
+ StreamCallback
9
+ } from "./completions.js";
10
+
11
+ export declare class Model {
12
+ constructor(fields: ModelConfig);
13
+
14
+ /** 模型名称 */
15
+ model: string;
16
+ /** 模型服务 API Key */
17
+ apiKey: string;
18
+ /** 模型服务 baseURL */
19
+ baseURL: string;
20
+
21
+ /**
22
+ * 发起一次 chat/completions 请求。
23
+ *
24
+ * @param params 消息、工具、是否流式
25
+ * @param logback 流式正文增量回调
26
+ * @param thinkback 流式思维链增量回调
27
+ */
28
+ completions(
29
+ params: CompletionsParams,
30
+ logback?: StreamCallback,
31
+ thinkback?: StreamCallback
32
+ ): Promise<CompletionsResult>;
33
+ }