@auipage/model 0.1.0 → 0.2.0-alpha.1

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/README.md CHANGED
@@ -1,93 +1,83 @@
1
- # [@auipage/model](https://github.com/handless-ui/auipage/packages/model/README.md)
2
-
3
- OpenAI 风格 `chat/completions` 的流式封装:负责请求拼装、SSE 增量解析、工具调用切片拼接,兼容同协议的其他模型服务(DeepSeek 等)。
4
-
5
- <p>
6
- <a href="https://zxl20070701.github.io/toolbox/#/npm-download?packages=@auipage/model&interval=7">
7
- <img src="https://img.shields.io/npm/dm/@auipage/model.svg" alt="downloads">
8
- </a>
9
- <a href="https://www.npmjs.com/package/@auipage/model">
10
- <img src="https://img.shields.io/npm/v/@auipage/model.svg" alt="npm">
11
- </a>
12
- <a href="https://github.com/handless-ui/auipage" target='_blank'>
13
- <img alt="GitHub repo stars" src="https://img.shields.io/github/stars/handless-ui/auipage?style=social">
14
- </a>
15
- </p>
16
-
17
- <img src="https://nodei.co/npm/@auipage/model.png?downloads=true&amp;downloadRank=true&amp;stars=true" alt="NPM">
18
-
19
- ## 安装
20
-
21
- ```
22
- npm install --save @auipage/model
23
- ```
24
-
25
- ## 创建实例
26
-
27
- ```javascript
28
- import { Model } from "@auipage/model";
29
-
30
- const model = new Model({
31
- model: "deepseek-chat", // 模型名
32
- apiKey: "your-api-key",
33
- baseURL: "https://api.deepseek.com/v1" // 请求时拼接 /chat/completions
34
- });
35
- ```
36
-
37
- ## completions
38
-
39
- ```typescript
40
- model.completions(
41
- {
42
- messages: ChatMessage[], // OpenAI 格式消息
43
- tools?: Tool[], // 可选,默认 [];自动取每项的 description 作为 tools 提交
44
- stream?: boolean // 默认 false
45
- },
46
- logback?, // (delta: string) => void,正文增量回调
47
- thinkback? // (reasoning: string) => void,推理过程回调
48
- ): Promise<{ content: string, tool_calls: ModelToolCall[] }>
49
- ```
50
-
51
- - `thinkback` 接收 `delta.reasoning` / `delta.reasoning_content`;正文中的 `<think>...</think>` 标签会被剥除,剩余内容并入 `content`。
52
- - `stream: false` 时两个回调仍会调用,只是在响应结束后各触发一次。
53
- - 返回的 `tool_calls` 已按 `id` 切片、拼好 `function.arguments`。
54
-
55
- ## 示例
56
-
57
- ```javascript
58
- model.completions({
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
- });
87
- ```
88
-
89
- ## 版权
90
-
91
- MIT License
92
-
93
- Copyright (c) [zxl20070701](https://zxl20070701.github.io/notebook/home.html) 走一步,再走一步
1
+ # [@auipage/model](https://github.com/handless-ui/auipage)
2
+
3
+ OpenAI 风格 `chat/completions` 的零依赖封装:请求拼装、SSE 增量解析、`tool_calls` 切片拼接、`<think>` 标签剥离,一次给你收好。
4
+
5
+ <p>
6
+ <a href="https://zxl20070701.github.io/toolbox/#/npm-download?packages=@auipage/model&interval=7">
7
+ <img src="https://img.shields.io/npm/dm/@auipage/model.svg" alt="downloads">
8
+ </a>
9
+ <a href="https://www.npmjs.com/package/@auipage/model">
10
+ <img src="https://img.shields.io/npm/v/@auipage/model.svg" alt="npm">
11
+ </a>
12
+ <a href="https://github.com/handless-ui/auipage" target='_blank'>
13
+ <img alt="GitHub repo stars" src="https://img.shields.io/github/stars/handless-ui/auipage?style=social">
14
+ </a>
15
+ </p>
16
+
17
+ ## 它解决什么
18
+
19
+ 直接对着 `chat/completions` 写流式解析,会卡在这几件事上:
20
+
21
+ - `data:` 事件要逐条切,`[DONE]` 要单独认;
22
+ - `delta.content` 是增量,得自己累积才能拿到完整文本;
23
+ - `tool_calls` 按 `index` 分片到达,`arguments` 是半个 JSON,要拼完再 `parse`;
24
+ - DeepSeek 这类模型的 `reasoning_content` 和 `<think>` 标签要单独处理。
25
+
26
+ 这些都不该由业务代码反复实现。
27
+
28
+ ## 30 秒例子
29
+
30
+ ```javascript
31
+ import { Model } from "@auipage/model";
32
+
33
+ const model = new Model({
34
+ model: "qwen3.5",
35
+ apiKey: "ollama", // 本地 ollama 不校验
36
+ baseURL: "http://localhost:11434/v1" // 请求时拼 /chat/completions
37
+ });
38
+
39
+ const { content, tool_calls } = await model.completions(
40
+ {
41
+ messages: [{ role: "user", content: "用一句话介绍 JavaScript" }],
42
+ stream: true
43
+ },
44
+ delta => process.stdout.write(delta), // 正文增量
45
+ think => process.stdout.write("[思考] " + think) // 推理增量
46
+ );
47
+
48
+ console.log("\n完整文本:", content);
49
+ console.log("工具调用:", tool_calls);
50
+ ```
51
+
52
+ 换成 DeepSeek、OpenAI 或任何兼容服务,只改构造参数里的三个字段。
53
+
54
+ 安装:
55
+
56
+ ```bash
57
+ npm install --save @auipage/model
58
+ ```
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
+
79
+ ## 版权
80
+
81
+ MIT License
82
+
83
+ Copyright (c) [zxl20070701](https://zxl20070701.github.io/notebook/home.html) 走一步,再走一步
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ /*! @auipage/model v0.2.0-alpha.1 */
2
+ "use strict";class t{constructor(){this._events=Object.create(null)}on(t,n){if("function"!=typeof n)return this;return(this._events[t]||(this._events[t]=[])).push(n),this}off(t,n){const e=this._events[t];if(!e)return this;const r=e.indexOf(n);return r>=0&&e.splice(r,1),0===e.length&&delete this._events[t],this}emit(t,...n){const e=this._events[t];if(!e||0===e.length)return!1;for(const t of e.slice())try{t.apply(null,n)}catch(t){console.error(t)}return!0}}class n extends t{constructor(){super(),this.status=0,this.headers={},this.ok=!1,this._done=!1,this._sseMode=!1,this._sseBuffer="",this._cancel=null,this._errorPending=null}on(t,n){if(super.on(t,n),"error"===t&&this._errorPending){const t=this._errorPending;this._errorPending=null,queueMicrotask(()=>this.emit("error",t))}return this}cancel(){return this._cancel&&this._cancel(),this}header(t){const n=this.headers;if(n)return"function"==typeof n.get?n.get(t)??void 0:n[t]}_push(t,n){if(!this._done||"error"===t){if("data"===t&&this._sseMode){this._sseBuffer+=n;const t=this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);this._sseBuffer=t.pop();for(const n of t){const t=this._extractSSEData(n);null!==t&&this.emit("data",t)}return}if("end"===t){if(this._sseMode&&this._sseBuffer.trim()){const t=this._extractSSEData(this._sseBuffer);null!==t&&this.emit("data",t),this._sseBuffer=""}this._done=!0}if("error"===t){this._done=!0;const t=this._events&&this._events.error;if(!t||0===t.length)return void(this._errorPending=n)}this.emit(t,n)}}_extractSSEData(t){const n=[];for(const e of t.split("\n"))e.startsWith("data:")&&n.push(e.replace(/^data:\s*/,"").replace(/\r$/,""));return 0===n.length?null:n.join("\n")}}const e=function(t){return function(e){return new Promise((r,o)=>{if(!e||!e.url)return void o(new Error("fetch: options.url is required"));var s;s=e.body,"[object Object]"===Object.prototype.toString.call(s)&&(e=Object.assign({},e,{body:JSON.stringify(e.body)}));const i=new n,c="function"==typeof AbortController?new AbortController:null;let a=null,u=!1;i._cancel=()=>{c&&c.abort()},queueMicrotask(()=>r(i));const l=()=>{a&&(clearTimeout(a),a=null)},h={onResponse(t){if(t&&"number"==typeof t.status&&(i.status=t.status,i.ok=t.status>=200&&t.status<300),t&&t.headers){i.headers=t.headers;("function"==typeof t.headers.get&&t.headers.get("content-type")||t.headers["content-type"]||"").includes("text/event-stream")&&(i._sseMode=!0)}i.status>=400&&i.emit("http-error",{status:i.status,headers:i.headers})},onData(t){i._push("data",t)},onEnd(){l(),i._push("end")},onError(t){u||(u=!0,l(),i._push("error",t),o(t))}},f=t=>{c&&c.abort(),h.onError(t)};if(e.timeout>0&&(a=setTimeout(()=>{a=null,f(new Error("fetch: 请求超时("+e.timeout+"ms)"))},e.timeout)),e.signal){if(e.signal.aborted)return void f(new Error("fetch: 请求已取消"));e.signal.addEventListener("abort",()=>{f(new Error("fetch: 请求已取消"))})}const d=c?Object.assign({},e,{signal:c.signal}):e;let p;try{p=t(d,h)}catch(t){return void h.onError(t)}p&&"function"==typeof p.then&&p.then(null,h.onError)})}}("undefined"!=typeof window&&void 0!==window.document?function(t,{onData:n,onEnd:e,onError:r,onResponse:o}){const{url:s,method:i="GET",headers:c={},body:a,signal:u}=t;"function"==typeof fetch?fetch(s,{method:i,headers:c,body:a,signal:u}).then(async t=>{if("function"==typeof o&&o({status:t.status||0,headers:t.headers||{}}),!t.body)return void e();const s=t.body.getReader(),i=new TextDecoder("utf-8");(async()=>{try{for(;;){const{value:t,done:r}=await s.read();if(r)return void e();n(i.decode(t,{stream:!0}))}}catch(t){r(t)}})()}).catch(t=>r(t)):r(new Error("Global fetch is not available in this environment"))}:async function(t,{onData:n,onEnd:e,onError:r,onResponse:o}){const[{default:s},{default:i},{URL:c}]=await Promise.all([import("http"),import("https"),import("url")]),{url:a,method:u="GET",headers:l={},body:h,signal:f}=t;let d;try{d=new c(a)}catch(t){return void r(t)}const p="https:"===d.protocol,g=p?i:s,m={method:u,hostname:d.hostname,port:d.port||(p?443:80),path:d.pathname+d.search,headers:l},y=g.request(m,t=>{"function"==typeof o&&o({status:t.statusCode||0,headers:t.headers||{}}),t.setEncoding("utf8"),t.on("data",t=>n(t)),t.on("end",()=>e()),t.on("error",t=>r(t))});if(y.on("error",t=>r(t)),f){if(f.aborted)return void r(new Error("请求已取消"));f.addEventListener("abort",()=>{y.destroy(new Error("请求已取消"))})}null!=h&&y.write(h),y.end()});function r(t){return t.replace(/^data:\s*/,"")}function o(t){try{return{value:JSON.parse(t)}}catch(t){return null}}function s(t,n){const e=o(r(t.trim()));if(!e)throw new SyntaxError("模型返回无法解析:"+String(n).slice(0,120));return e.value}function i(t){if(Array.isArray(t)){for(const n of t)if(n&&n.error)throw n.error;return t}if(t&&t.error)throw t.error;return t}function c(t){let n=String(null==t?"":t).trim();if(n=n.replace(/data:\s*\[DONE\]$/,"").trim(),""===n||"[DONE]"===n)return[];let e=o(r(n))||o(n);if(e)return i(e.value);const c=n.split(/\r?\n\r?\ndata: /);if(c.length>1)return i(c.map(t=>s(t,n)));const a=n.split(/\r?\n/).filter(t=>t.trim()&&!t.trim().startsWith(":"));if(a.length>1)return i(a.map(t=>s(t,n)));throw new SyntaxError("模型返回无法解析:"+n.slice(0,120))}function a(t,n){if(!/<\/think>/.test(t))return t;const e=t.split("</think>");return{reasoning:e[0].replace("<think>",""),content:e[1]+(n||"")}}const u="<think>",l="</think>";function h(t,n){for(let e=Math.min(n.length-1,t.length);e>0;e--)if(t.endsWith(n.slice(0,e)))return e;return 0}function f(t,n){const e=(n.thinkBuf||"")+t;if(n.thinkBuf="",n.inThink){const t=e.indexOf(l);if(-1===t){const t=h(e,l);return n.thinkBuf=e.slice(e.length-t),{thinking:e.slice(0,e.length-t),content:""}}n.inThink=!1;const r=f(e.slice(t+8),n);return{thinking:e.slice(0,t)+r.thinking,content:r.content}}const r=e.indexOf(u);if(-1===r){const t=h(e,u);return n.thinkBuf=e.slice(e.length-t),{thinking:"",content:e.slice(0,e.length-t)}}const o=e.indexOf(l,r);if(-1!==o){const t=f(e.slice(o+8),n);return{thinking:e.slice(r+7,o)+t.thinking,content:e.slice(0,r)+t.content}}n.inThink=!0;const s=e.slice(r+7),i=h(s,l);return n.thinkBuf=s.slice(s.length-i),{thinking:s.slice(0,s.length-i),content:e.slice(0,r)}}function d(t){const n=t.function||{};return{...t,function:{...n,arguments:"string"==typeof n.arguments?n.arguments:""}}}function p(t,n){t._toolSlots||(t._toolSlots=new Map);const e=t.tool_calls,r="number"==typeof n.index?n.index:null;if("string"==typeof n.id&&""!==n.id){const o=e.find(t=>t.id===n.id);if(o)return void g(o,n);const s=d(n);return e.push(s),void(null!==r&&t._toolSlots.set(r,s))}let o=null!==r?t._toolSlots.get(r):null;if(!o&&e.length&&(o=e[e.length-1]),!o)return o=d(n),e.push(o),void(null!==r&&t._toolSlots.set(r,o));g(o,n)}function g(t,n){const e=n.function||{};e.name&&!t.function.name&&(t.function.name=e.name),"string"==typeof e.arguments&&(t.function.arguments+=e.arguments)}function m(t,{logback:n,thinkback:e},r){if(Array.isArray(t))for(let o=0;o<t.length;o++){const s=t[o].delta;let i=s.reasoning||s.reasoning_content;if(i){const t=a(i,s.content);"object"==typeof t&&(i=t.reasoning,s.content=t.content),e&&e(i)}if(s.content){const t=f(s.content,r);t.thinking&&e&&e(t.thinking),t.content&&(n&&n(t.content),r.content+=t.content)}if(Array.isArray(s.tool_calls))for(const t of s.tool_calls)p(r,t)}}function y(t,n){const e=t&&t.status;let r="";if(n){try{const t=JSON.parse(n),e=t&&t.error;r=e&&(e.message||e)||""}catch(t){r=String(n).slice(0,200)}r&&"string"!=typeof r&&(r=JSON.stringify(r))}return new Error("模型服务返回 HTTP "+e+(r?":"+r:""))}function _(t){this.model=t.model,this.apiKey=t.apiKey,this.baseURL=t.baseURL,this.temperature=t.temperature,this.topP=t.topP,this.maxTokens=t.maxTokens,this.timeout=t.timeout}_.prototype.completions=function(t,n,r){return new Promise((o,s)=>{const i={content:"",tool_calls:[]},a={logback:n,thinkback:r};let u="",l=null,h=null,f=!1;const d=(t,n)=>{f||(f=!0,t(n))},p=t=>d(s,function(t,n){if(t instanceof Error)return t;if(t&&"string"==typeof t.message)return new Error(t.message);try{return new Error(String(t))}catch(t){return new Error(n||"模型请求失败")}}(t,"模型请求失败")),g={model:this.model,messages:t.messages,tools:t.tools?t.tools.map(t=>t.description):[],stream:t.stream},_=null!=t.temperature?t.temperature:this.temperature,k=null!=t.topP?t.topP:this.topP,b=null!=t.maxTokens?t.maxTokens:this.maxTokens;null!=_&&(g.temperature=_),null!=k&&(g.top_p=k),null!=b&&(g.max_tokens=b),e({url:`${this.baseURL.replace(/\/+$/,"")}/chat/completions`,method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(g),timeout:null!=t.timeout?t.timeout:this.timeout,signal:t.signal}).then(n=>{n.on("http-error",n=>{l=n,t.stream&&p(y(n))}),n.on("data",n=>{if(f)return;if(!t.stream)return void(u+=n);let e;try{e=c(n.toString())}catch(t){return h=t,void p(t)}try{const t=Array.isArray(e)?e:[e];for(const n of t)m(n.choices,a,i)}catch(t){p(t)}}),n.on("end",()=>{if(t.stream){if(h)return void p(h);if(l)return void p(y(l))}else{if(l)return void p(y(l,u));try{const t=c(u),n=t&&t.choices;if(!n||!n[0]||!n[0].message)throw new Error("模型响应缺少 choices[0].message");m([{delta:n[0].message}],a,i)}catch(t){return void p(t)}}!function(t,{logback:n,thinkback:e}){const r=function(t){const n=t.thinkBuf||"";return t.thinkBuf="",t.inThink?{thinking:n,content:""}:{thinking:"",content:n}}(t);r.thinking&&e&&e(r.thinking),r.content&&(n&&n(r.content),t.content+=r.content)}(i,a),d(o,{content:i.content,tool_calls:i.tool_calls})}),n.on("error",t=>p(t))}).catch(t=>p(t))})},exports.Model=_;