@auipage/model 0.1.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/.mailmap ADDED
@@ -0,0 +1 @@
1
+ zxl20070701 <1904314465@qq.com>
package/AUTHORS.txt ADDED
@@ -0,0 +1,6 @@
1
+ Authors ordered by first contribution.
2
+
3
+ zxl20070701 <1904314465@qq.com> <https://github.com/zxl20070701>
4
+
5
+ -----------------------------------------------------
6
+ We thank all of them for their contributions!
package/CHANGELOG ADDED
@@ -0,0 +1,4 @@
1
+ v0.1.0:
2
+ date:
3
+ changes:
4
+ - 初始化版本
package/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # [@auipage/model](https://github.com/handless-ui/auipage/packages/model/README.md)
2
+ 智能体快速开发框架,用于快速开发智能体网页应用。
3
+
4
+ <p>
5
+ <a href="https://zxl20070701.github.io/toolbox/#/npm-download?packages=@auipage/model&interval=7">
6
+ <img src="https://img.shields.io/npm/dm/@auipage/model.svg" alt="downloads">
7
+ </a>
8
+ <a href="https://www.npmjs.com/package/@auipage/model">
9
+ <img src="https://img.shields.io/npm/v/@auipage/model.svg" alt="npm">
10
+ </a>
11
+ <a href="https://github.com/handless-ui/auipage" target='_blank'>
12
+ <img alt="GitHub repo stars" src="https://img.shields.io/github/stars/handless-ui/auipage?style=social">
13
+ </a>
14
+ </p>
15
+
16
+ <img src="https://nodei.co/npm/@auipage/model.png?downloads=true&amp;downloadRank=true&amp;stars=true" alt="NPM">
17
+
18
+ ## 如何使用?
19
+
20
+ ```
21
+ npm install --save @auipage/model
22
+ ```
23
+
24
+ 安装后,即可在项目中使用。
25
+
26
+ ### 1. 实例化 Model
27
+
28
+ 通过 `new Model(fields)` 创建一个模型实例,其中 `fields` 包含三个必填字段:
29
+
30
+ - `model`:模型名称(例如 `gpt-4o`、`deepseek-chat` 等)
31
+ - `apiKey`:调用接口所需的密钥
32
+ - `baseURL`:接口服务的基础地址(请求时会拼接 `/chat/completions`)
33
+
34
+ ```javascript
35
+ import { Model } from "@auipage/model";
36
+
37
+ const model = new Model({
38
+ model: "deepseek-chat",
39
+ apiKey: "your-api-key",
40
+ baseURL: "https://api.deepseek.com/v1"
41
+ });
42
+ ```
43
+
44
+ ### 2. 调用 completions
45
+
46
+ `model.completions(params, logback, thinkback)` 会向 `${baseURL}/chat/completions` 发起请求,并以流式方式解析返回数据,最终返回一个 `Promise`,其值为 `{ content, tool_calls }`。
47
+
48
+ 参数说明:
49
+
50
+ - `params.messages`:对话消息数组,遵循 OpenAI Chat Completions 的 `messages` 格式。
51
+ - `params.tools`:工具列表,框架会自动取每个工具的 `description` 字段作为 `tools` 参数提交。
52
+ - `params.stream`:是否启用流式输出,`true` 时会逐步回调;`false` 时等待完整响应再统一处理。
53
+ - `logback`(可选):流式输出时,每当接收到一段正文(`delta.content`),便会触发该回调,适合实时把内容渲染到界面上。
54
+ - `thinkback`(可选):当模型返回了推理过程(`delta.reasoning` 或 `delta.reasoning_content`)时会触发该回调;如果内容中带有 `<think>...</think>` 标签,会自动剥离标签并将剩余正文合并到 `content` 中。
55
+
56
+ 返回值:
57
+
58
+ - `content`:累积的全部正文内容。
59
+ - `tool_calls`:解析得到的工具调用数组,会按 `id` 切片并拼接 `function.arguments`。
60
+
61
+ ### 3. 流式输出示例
62
+
63
+ ```javascript
64
+ model.completions({
65
+ messages: [
66
+ { role: "system", content: "你是一个助手。" },
67
+ { role: "user", content: "用一句话介绍 JavaScript。" }
68
+ ],
69
+ tools: [],
70
+ stream: true
71
+ }, (chunk) => {
72
+ // 实时打印每一段正文
73
+ process.stdout.write(chunk);
74
+ }, (reasoning) => {
75
+ // 实时打印模型的思考过程
76
+ console.log("\n[think]", reasoning);
77
+ }).then(({ content, tool_calls }) => {
78
+ console.log("\n完整结果:", { content, tool_calls });
79
+ }).catch(err => {
80
+ console.error(err);
81
+ });
82
+ ```
83
+
84
+ ### 4. 非流式输出示例
85
+
86
+ 将 `params.stream` 置为 `false` 时,`logback` 和 `thinkback` 仍会被调用一次:等到响应结束后,框架会把整段响应解析成一个 `delta` 一次性交给内部 `choices_handler`,所以 `logback` 会收到完整正文,`thinkback` 也只会回调一次(如果响应中包含推理内容的话):
87
+
88
+ ```javascript
89
+ model.completions({
90
+ messages: [
91
+ { role: "user", content: "你好" }
92
+ ],
93
+ tools: [],
94
+ stream: false
95
+ }, (chunk) => {
96
+ // 非流式时这里会一次性收到完整正文
97
+ console.log(chunk);
98
+ }, (reasoning) => {
99
+ // 如果模型返回了 reasoning,这里会回调一次
100
+ console.log("[think]", reasoning);
101
+ }).then(({ content, tool_calls }) => {
102
+ console.log(content, tool_calls);
103
+ });
104
+ ```
105
+
106
+ ### 5. 配合工具调用(tool_calls)
107
+
108
+ 只要在 `params.tools` 中传入工具描述数组,框架就会在请求体中附带 `tools` 字段,并把模型返回的工具调用解析到 `tool_calls` 中:
109
+
110
+ ```javascript
111
+ model.completions({
112
+ messages: [{ role: "user", content: "查一下南京今天的天气" }],
113
+ tools: [
114
+ {
115
+ description: {
116
+ type: "function",
117
+ function: {
118
+ name: "getWeather",
119
+ description: "查询指定城市的天气",
120
+ parameters: {
121
+ type: "object",
122
+ properties: { city: { type: "string" } }
123
+ }
124
+ }
125
+ }
126
+ }
127
+ ],
128
+ stream: false
129
+ }).then(({ content, tool_calls }) => {
130
+ // tool_calls 为模型决定要调用的工具及参数
131
+ console.log(content, tool_calls);
132
+ });
133
+ ```
134
+
135
+ ## 版权
136
+
137
+ MIT License
138
+
139
+ Copyright (c) [zxl20070701](https://zxl20070701.github.io/notebook/home.html) 走一步,再走一步
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@auipage/model",
3
+ "version": "0.1.0-alpha.0",
4
+ "description": "@auipage/model",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "typings": "types/index.d.ts",
8
+ "sideEffects": false,
9
+ "scripts": {
10
+ "prepublishOnly": "node ../../swap-pkg.js --mode=publish",
11
+ "postpublish": "node ../../swap-pkg.js --mode=restore"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/handless-ui/auipage.git",
16
+ "directory": "packages/model"
17
+ },
18
+ "author": {
19
+ "name": "zxl20070701",
20
+ "url": "https://zxl20070701.github.io/notebook/home.html"
21
+ },
22
+ "license": "MIT",
23
+ "bugs": {
24
+ "url": "https://github.com/handless-ui/auipage/issues"
25
+ },
26
+ "homepage": "https://github.com/handless-ui/auipage#readme",
27
+ "dependencies": {
28
+ "@auipage/fetch": "^0.1.0-alpha.0",
29
+ "@auipage/types": "^0.1.0-alpha.0"
30
+ }
31
+ }
@@ -0,0 +1,60 @@
1
+ import { fetch } from "@auipage/fetch";
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.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
+ }
package/src/index.js ADDED
@@ -0,0 +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 };
@@ -0,0 +1,17 @@
1
+ // 字符串转JSON
2
+ // 适配LLM返回数据格式
3
+ export default function (value) {
4
+ try {
5
+ value = value.trim().replace(/^data: /, "").replace(/data: \[DONE\]$/, "");
6
+
7
+ if (/\n\ndata: /.test(value)) {
8
+ return JSON.parse("[" + (value.split(/\n\ndata: /)).join(",") + "]");
9
+ } else if (value === "[DONE]") {
10
+ return [];
11
+ }
12
+
13
+ return JSON.parse(value);
14
+ } catch (e) {
15
+ throw new Error("[转json失败]" + value);
16
+ }
17
+ };
@@ -0,0 +1,12 @@
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
+ }
@@ -0,0 +1,37 @@
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
+ }
File without changes