@auipage/model 0.2.0-beta.0 → 0.2.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/CHANGELOG +9 -1
- package/README.md +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +32 -19
- package/dist/index.min.js +1 -1
- package/package.json +3 -3
- package/src/completions.js +0 -7
- package/src/index.js +0 -2
- package/src/parseString.js +0 -4
- package/src/reasoning.js +0 -2
- package/src/streamHandler.js +0 -2
- package/types/completions.d.ts +3 -2
package/CHANGELOG
CHANGED
|
@@ -3,7 +3,7 @@ v0.1.0:
|
|
|
3
3
|
changes:
|
|
4
4
|
- 初始化版本
|
|
5
5
|
v0.2.0:
|
|
6
|
-
date:
|
|
6
|
+
date:2026-12-01
|
|
7
7
|
changes:
|
|
8
8
|
- 修复bug:
|
|
9
9
|
1、模型请求 4xx / 网络失败时进程崩溃或请求永久挂起
|
|
@@ -28,3 +28,11 @@ v0.2.0:
|
|
|
28
28
|
6、task:end 增加 by(user / tool),取消时另带 displayed,列出已显示条目供界面撤销
|
|
29
29
|
7、工具 execute / render 拿到任务控制句柄,可直接 stop() / cancel() 结束整轮
|
|
30
30
|
8、取消信号经 context.signal 透传,Agent / model 均支持中断
|
|
31
|
+
v0.2.1:
|
|
32
|
+
date:2026-12-02
|
|
33
|
+
changes:
|
|
34
|
+
- 修复bug:
|
|
35
|
+
1、修复 @auipage/model 的 CompletionsParams 类型声明错误
|
|
36
|
+
( 缺少 temperature/topP/maxTokens 字段,运行时已读取但 TS 无法单次传入错误 )
|
|
37
|
+
- 优化改造:
|
|
38
|
+
1、@auipage/types 新增 ModelSamplingParams,ModelConfig 与 CompletionsParams 共用采样字段定义
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
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">
|
|
@@ -66,7 +66,7 @@ npm install --save @auipage/model
|
|
|
66
66
|
| 想完全掌控 | 原生 `fetch` + 自己解析 SSE | 上面四件脏活得自己写 |
|
|
67
67
|
| 只用非流式 | 原生 `fetch` 一次 POST | 没有增量回调,但代码最短 |
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
它适合“**不引第三方依赖、又要一个能直接跑的 OpenAI 兼容客户端**”的场景。如果你已经在用某家的官方 SDK,没有必要为了统一而换掉。
|
|
70
70
|
|
|
71
71
|
## 它在哪一环
|
|
72
72
|
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @auipage/model v0.2.
|
|
1
|
+
/*! @auipage/model v0.2.1 */
|
|
2
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=_;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! @auipage/model v0.2.
|
|
1
|
+
/*! @auipage/model v0.2.1 */
|
|
2
2
|
// 极简 EventEmitter:on / off / emit,供 Response 复用
|
|
3
3
|
class Emitter {
|
|
4
4
|
constructor() {
|
|
@@ -20,6 +20,7 @@ class Emitter {
|
|
|
20
20
|
if (list.length === 0) delete this._events[event];
|
|
21
21
|
return this;
|
|
22
22
|
}
|
|
23
|
+
|
|
23
24
|
emit(event, ...args) {
|
|
24
25
|
const list = this._events[event];
|
|
25
26
|
if (!list || list.length === 0) return false;
|
|
@@ -33,7 +34,7 @@ class Emitter {
|
|
|
33
34
|
}
|
|
34
35
|
}
|
|
35
36
|
return true;
|
|
36
|
-
}
|
|
37
|
+
}
|
|
37
38
|
}
|
|
38
39
|
|
|
39
40
|
// Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
|
|
@@ -49,7 +50,7 @@ class Response extends Emitter {
|
|
|
49
50
|
this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
|
|
50
51
|
this._cancel = null; // 由 createFetch 注入,用于中断底层请求
|
|
51
52
|
this._errorPending = null; // 消费者还没来得及注册时就发生的错误,注册后补发
|
|
52
|
-
}
|
|
53
|
+
}
|
|
53
54
|
|
|
54
55
|
// 注册监听;error 是一次性终态,注册时若已发生则补发
|
|
55
56
|
on(event, listener) {
|
|
@@ -61,7 +62,7 @@ class Response extends Emitter {
|
|
|
61
62
|
queueMicrotask(() => this.emit('error', err));
|
|
62
63
|
}
|
|
63
64
|
return this;
|
|
64
|
-
}
|
|
65
|
+
}
|
|
65
66
|
|
|
66
67
|
// 主动取消请求,失败统一从 error 事件返回
|
|
67
68
|
cancel() {
|
|
@@ -96,7 +97,7 @@ class Response extends Emitter {
|
|
|
96
97
|
}
|
|
97
98
|
}
|
|
98
99
|
return;
|
|
99
|
-
}
|
|
100
|
+
}
|
|
100
101
|
|
|
101
102
|
if (type === 'end') {
|
|
102
103
|
// SSE 模式下,flush 缓冲区残留
|
|
@@ -132,7 +133,7 @@ class Response extends Emitter {
|
|
|
132
133
|
}
|
|
133
134
|
if (dataLines.length === 0) return null;
|
|
134
135
|
return dataLines.join('\n');
|
|
135
|
-
}
|
|
136
|
+
}
|
|
136
137
|
}
|
|
137
138
|
|
|
138
139
|
// fetch 工厂:注入 adapter,返回对外的 fetch 函数
|
|
@@ -166,12 +167,14 @@ function createFetch(adapter) {
|
|
|
166
167
|
// adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
|
|
167
168
|
// 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
|
|
168
169
|
queueMicrotask(() => resolve(response));
|
|
169
|
-
|
|
170
|
+
|
|
171
|
+
const clearTimer = () => {
|
|
170
172
|
if (timer) {
|
|
171
173
|
clearTimeout(timer);
|
|
172
174
|
timer = null;
|
|
173
175
|
}
|
|
174
176
|
};
|
|
177
|
+
|
|
175
178
|
const hooks = {
|
|
176
179
|
onResponse(meta) {
|
|
177
180
|
if (meta && typeof meta.status === 'number') {
|
|
@@ -212,7 +215,8 @@ const clearTimer = () => {
|
|
|
212
215
|
reject(err);
|
|
213
216
|
}
|
|
214
217
|
};
|
|
215
|
-
|
|
218
|
+
|
|
219
|
+
const abortWith = (err) => {
|
|
216
220
|
if (controller) controller.abort();
|
|
217
221
|
hooks.onError(err);
|
|
218
222
|
};
|
|
@@ -248,7 +252,7 @@ const abortWith = (err) => {
|
|
|
248
252
|
}
|
|
249
253
|
// adapter 允许返回 Promise,失败也要走同一条错误通道
|
|
250
254
|
if (ret && typeof ret.then === 'function') ret.then(null, hooks.onError);
|
|
251
|
-
});
|
|
255
|
+
});
|
|
252
256
|
};
|
|
253
257
|
}
|
|
254
258
|
|
|
@@ -276,6 +280,7 @@ function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
|
276
280
|
onEnd();
|
|
277
281
|
return;
|
|
278
282
|
}
|
|
283
|
+
|
|
279
284
|
const reader = res.body.getReader();
|
|
280
285
|
const decoder = new TextDecoder('utf-8');
|
|
281
286
|
|
|
@@ -292,7 +297,7 @@ function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
|
292
297
|
}
|
|
293
298
|
// value 是 Uint8Array,解码为字符串
|
|
294
299
|
onData(decoder.decode(value, { stream: true }));
|
|
295
|
-
}
|
|
300
|
+
}
|
|
296
301
|
} catch (err) {
|
|
297
302
|
onError(err);
|
|
298
303
|
}
|
|
@@ -311,7 +316,8 @@ async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
|
|
|
311
316
|
import('https'),
|
|
312
317
|
import('url')
|
|
313
318
|
]);
|
|
314
|
-
|
|
319
|
+
|
|
320
|
+
const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
315
321
|
|
|
316
322
|
let parsed;
|
|
317
323
|
try {
|
|
@@ -331,6 +337,7 @@ const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
|
331
337
|
path: parsed.pathname + parsed.search,
|
|
332
338
|
headers
|
|
333
339
|
};
|
|
340
|
+
|
|
334
341
|
const req = lib.request(reqOptions, (res) => {
|
|
335
342
|
// 把 status / headers 同步给 Response(若上游关心)
|
|
336
343
|
if (typeof onResponse === 'function') {
|
|
@@ -347,7 +354,8 @@ const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
|
347
354
|
});
|
|
348
355
|
|
|
349
356
|
req.on('error', (err) => onError(err));
|
|
350
|
-
|
|
357
|
+
|
|
358
|
+
// 取消 / 超时:直接中断底层请求,错误从 req 的 error 事件返回
|
|
351
359
|
if (signal) {
|
|
352
360
|
if (signal.aborted) {
|
|
353
361
|
onError(new Error('请求已取消'));
|
|
@@ -355,7 +363,7 @@ const { url, method = 'GET', headers = {}, body, signal } = options;
|
|
|
355
363
|
}
|
|
356
364
|
signal.addEventListener('abort', () => {
|
|
357
365
|
req.destroy(new Error('请求已取消'));
|
|
358
|
-
});
|
|
366
|
+
});
|
|
359
367
|
}
|
|
360
368
|
|
|
361
369
|
if (body != null) {
|
|
@@ -411,14 +419,16 @@ function parseString (value) {
|
|
|
411
419
|
// 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
|
|
412
420
|
text = text.replace(/data:\s*\[DONE\]$/, "").trim();
|
|
413
421
|
if (text === "" || text === "[DONE]") return [];
|
|
414
|
-
|
|
422
|
+
|
|
423
|
+
// 单条:带 data: 前缀或裸 JSON
|
|
415
424
|
let single = tryParse(stripDataPrefix(text)) || tryParse(text);
|
|
416
425
|
if (single) return checkError(single.value);
|
|
417
426
|
|
|
418
427
|
// 多条 SSE 事件,以 "\n\ndata: " 分隔
|
|
419
428
|
const parts = text.split(/\r?\n\r?\ndata: /);
|
|
420
429
|
if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
|
|
421
|
-
|
|
430
|
+
|
|
431
|
+
// NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
|
|
422
432
|
const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
|
|
423
433
|
if (lines.length > 1) return checkError(lines.map(line => parseOne(line, text)));
|
|
424
434
|
|
|
@@ -636,6 +646,7 @@ function errorFromHttp(meta, body) {
|
|
|
636
646
|
|
|
637
647
|
function completions(params, logback, thinkback) {
|
|
638
648
|
return new Promise((resolve, reject) => {
|
|
649
|
+
|
|
639
650
|
const state = { content: "", tool_calls: [] };
|
|
640
651
|
const callbacks = { logback, thinkback };
|
|
641
652
|
|
|
@@ -650,7 +661,8 @@ function completions(params, logback, thinkback) {
|
|
|
650
661
|
fn(value);
|
|
651
662
|
};
|
|
652
663
|
const fail = value => finish(reject, toError(value, "模型请求失败"));
|
|
653
|
-
|
|
664
|
+
|
|
665
|
+
const body = {
|
|
654
666
|
model: this.model,
|
|
655
667
|
messages: params.messages,
|
|
656
668
|
tools: params.tools ? params.tools.map(tool => tool.description) : [],
|
|
@@ -662,7 +674,8 @@ const body = {
|
|
|
662
674
|
if (temperature != null) body.temperature = temperature;
|
|
663
675
|
if (topP != null) body.top_p = topP;
|
|
664
676
|
if (maxTokens != null) body.max_tokens = maxTokens;
|
|
665
|
-
|
|
677
|
+
|
|
678
|
+
fetch$1({
|
|
666
679
|
url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
|
|
667
680
|
method: "POST",
|
|
668
681
|
headers: {
|
|
@@ -672,7 +685,7 @@ fetch$1({
|
|
|
672
685
|
body: JSON.stringify(body),
|
|
673
686
|
timeout: params.timeout != null ? params.timeout : this.timeout,
|
|
674
687
|
signal: params.signal
|
|
675
|
-
}).then(res => {
|
|
688
|
+
}).then(res => {
|
|
676
689
|
|
|
677
690
|
// 非 2xx:非流式等错误体读完再判,流式直接中断
|
|
678
691
|
res.on("http-error", meta => {
|
|
@@ -693,7 +706,7 @@ fetch$1({
|
|
|
693
706
|
} catch (e) {
|
|
694
707
|
streamError = e;
|
|
695
708
|
fail(e);
|
|
696
|
-
return;
|
|
709
|
+
return;
|
|
697
710
|
}
|
|
698
711
|
try {
|
|
699
712
|
const items = Array.isArray(parsed) ? parsed : [parsed];
|
package/dist/index.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @auipage/model v0.2.
|
|
1
|
+
/*! @auipage/model v0.2.1 */
|
|
2
2
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).auipage_model={})}(this,function(t){"use strict";class e{constructor(){this._events=Object.create(null)}on(t,e){if("function"!=typeof e)return this;return(this._events[t]||(this._events[t]=[])).push(e),this}off(t,e){const n=this._events[t];if(!n)return this;const r=n.indexOf(e);return r>=0&&n.splice(r,1),0===n.length&&delete this._events[t],this}emit(t,...e){const n=this._events[t];if(!n||0===n.length)return!1;for(const t of n.slice())try{t.apply(null,e)}catch(t){console.error(t)}return!0}}class n extends e{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,e){if(super.on(t,e),"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 e=this.headers;if(e)return"function"==typeof e.get?e.get(t)??void 0:e[t]}_push(t,e){if(!this._done||"error"===t){if("data"===t&&this._sseMode){this._sseBuffer+=e;const t=this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);this._sseBuffer=t.pop();for(const e of t){const t=this._extractSSEData(e);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=e)}this.emit(t,e)}}_extractSSEData(t){const e=[];for(const n of t.split("\n"))n.startsWith("data:")&&e.push(n.replace(/^data:\s*/,"").replace(/\r$/,""));return 0===e.length?null:e.join("\n")}}const r=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:e,onEnd:n,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 n();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 n();e(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:e,onEnd:n,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=>e(t)),t.on("end",()=>n()),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 o(t){return t.replace(/^data:\s*/,"")}function s(t){try{return{value:JSON.parse(t)}}catch(t){return null}}function i(t,e){const n=s(o(t.trim()));if(!n)throw new SyntaxError("模型返回无法解析:"+String(e).slice(0,120));return n.value}function c(t){if(Array.isArray(t)){for(const e of t)if(e&&e.error)throw e.error;return t}if(t&&t.error)throw t.error;return t}function a(t){let e=String(null==t?"":t).trim();if(e=e.replace(/data:\s*\[DONE\]$/,"").trim(),""===e||"[DONE]"===e)return[];let n=s(o(e))||s(e);if(n)return c(n.value);const r=e.split(/\r?\n\r?\ndata: /);if(r.length>1)return c(r.map(t=>i(t,e)));const a=e.split(/\r?\n/).filter(t=>t.trim()&&!t.trim().startsWith(":"));if(a.length>1)return c(a.map(t=>i(t,e)));throw new SyntaxError("模型返回无法解析:"+e.slice(0,120))}function u(t,e){if(!/<\/think>/.test(t))return t;const n=t.split("</think>");return{reasoning:n[0].replace("<think>",""),content:n[1]+(e||"")}}const l="<think>",h="</think>";function f(t,e){for(let n=Math.min(e.length-1,t.length);n>0;n--)if(t.endsWith(e.slice(0,n)))return n;return 0}function d(t,e){const n=(e.thinkBuf||"")+t;if(e.thinkBuf="",e.inThink){const t=n.indexOf(h);if(-1===t){const t=f(n,h);return e.thinkBuf=n.slice(n.length-t),{thinking:n.slice(0,n.length-t),content:""}}e.inThink=!1;const r=d(n.slice(t+8),e);return{thinking:n.slice(0,t)+r.thinking,content:r.content}}const r=n.indexOf(l);if(-1===r){const t=f(n,l);return e.thinkBuf=n.slice(n.length-t),{thinking:"",content:n.slice(0,n.length-t)}}const o=n.indexOf(h,r);if(-1!==o){const t=d(n.slice(o+8),e);return{thinking:n.slice(r+7,o)+t.thinking,content:n.slice(0,r)+t.content}}e.inThink=!0;const s=n.slice(r+7),i=f(s,h);return e.thinkBuf=s.slice(s.length-i),{thinking:s.slice(0,s.length-i),content:n.slice(0,r)}}function p(t){const e=t.function||{};return{...t,function:{...e,arguments:"string"==typeof e.arguments?e.arguments:""}}}function g(t,e){t._toolSlots||(t._toolSlots=new Map);const n=t.tool_calls,r="number"==typeof e.index?e.index:null;if("string"==typeof e.id&&""!==e.id){const o=n.find(t=>t.id===e.id);if(o)return void m(o,e);const s=p(e);return n.push(s),void(null!==r&&t._toolSlots.set(r,s))}let o=null!==r?t._toolSlots.get(r):null;if(!o&&n.length&&(o=n[n.length-1]),!o)return o=p(e),n.push(o),void(null!==r&&t._toolSlots.set(r,o));m(o,e)}function m(t,e){const n=e.function||{};n.name&&!t.function.name&&(t.function.name=n.name),"string"==typeof n.arguments&&(t.function.arguments+=n.arguments)}function y(t,{logback:e,thinkback:n},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=u(i,s.content);"object"==typeof t&&(i=t.reasoning,s.content=t.content),n&&n(i)}if(s.content){const t=d(s.content,r);t.thinking&&n&&n(t.thinking),t.content&&(e&&e(t.content),r.content+=t.content)}if(Array.isArray(s.tool_calls))for(const t of s.tool_calls)g(r,t)}}function _(t,e){const n=t&&t.status;let r="";if(e){try{const t=JSON.parse(e),n=t&&t.error;r=n&&(n.message||n)||""}catch(t){r=String(e).slice(0,200)}r&&"string"!=typeof r&&(r=JSON.stringify(r))}return new Error("模型服务返回 HTTP "+n+(r?":"+r:""))}function k(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}k.prototype.completions=function(t,e,n){return new Promise((o,s)=>{const i={content:"",tool_calls:[]},c={logback:e,thinkback:n};let u="",l=null,h=null,f=!1;const d=(t,e)=>{f||(f=!0,t(e))},p=t=>d(s,function(t,e){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(e||"模型请求失败")}}(t,"模型请求失败")),g={model:this.model,messages:t.messages,tools:t.tools?t.tools.map(t=>t.description):[],stream:t.stream},m=null!=t.temperature?t.temperature:this.temperature,k=null!=t.topP?t.topP:this.topP,b=null!=t.maxTokens?t.maxTokens:this.maxTokens;null!=m&&(g.temperature=m),null!=k&&(g.top_p=k),null!=b&&(g.max_tokens=b),r({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(e=>{e.on("http-error",e=>{l=e,t.stream&&p(_(e))}),e.on("data",e=>{if(f)return;if(!t.stream)return void(u+=e);let n;try{n=a(e.toString())}catch(t){return h=t,void p(t)}try{const t=Array.isArray(n)?n:[n];for(const e of t)y(e.choices,c,i)}catch(t){p(t)}}),e.on("end",()=>{if(t.stream){if(h)return void p(h);if(l)return void p(_(l))}else{if(l)return void p(_(l,u));try{const t=a(u),e=t&&t.choices;if(!e||!e[0]||!e[0].message)throw new Error("模型响应缺少 choices[0].message");y([{delta:e[0].message}],c,i)}catch(t){return void p(t)}}!function(t,{logback:e,thinkback:n}){const r=function(t){const e=t.thinkBuf||"";return t.thinkBuf="",t.inThink?{thinking:e,content:""}:{thinking:"",content:e}}(t);r.thinking&&n&&n(r.thinking),r.content&&(e&&e(r.content),t.content+=r.content)}(i,c),d(o,{content:i.content,tool_calls:i.tool_calls})}),e.on("error",t=>p(t))}).catch(t=>p(t))})},t.Model=k});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auipage/model",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "@auipage/model",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "./types/index.d.ts",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"homepage": "https://github.com/handless-ui/auipage#readme",
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@auipage/fetch": "^0.2.
|
|
55
|
-
"@auipage/types": "^0.2.
|
|
54
|
+
"@auipage/fetch": "^0.2.1",
|
|
55
|
+
"@auipage/types": "^0.2.1"
|
|
56
56
|
}
|
|
57
57
|
}
|
package/src/completions.js
CHANGED
|
@@ -35,7 +35,6 @@ function errorFromHttp(meta, body) {
|
|
|
35
35
|
export default function completions(params, logback, thinkback) {
|
|
36
36
|
return new Promise((resolve, reject) => {
|
|
37
37
|
|
|
38
|
-
// #doc:state
|
|
39
38
|
const state = { content: "", tool_calls: [] };
|
|
40
39
|
const callbacks = { logback, thinkback };
|
|
41
40
|
|
|
@@ -50,9 +49,7 @@ export default function completions(params, logback, thinkback) {
|
|
|
50
49
|
fn(value);
|
|
51
50
|
};
|
|
52
51
|
const fail = value => finish(reject, toError(value, "模型请求失败"));
|
|
53
|
-
// #end
|
|
54
52
|
|
|
55
|
-
// #doc:body
|
|
56
53
|
const body = {
|
|
57
54
|
model: this.model,
|
|
58
55
|
messages: params.messages,
|
|
@@ -65,7 +62,6 @@ export default function completions(params, logback, thinkback) {
|
|
|
65
62
|
if (temperature != null) body.temperature = temperature;
|
|
66
63
|
if (topP != null) body.top_p = topP;
|
|
67
64
|
if (maxTokens != null) body.max_tokens = maxTokens;
|
|
68
|
-
// #end
|
|
69
65
|
|
|
70
66
|
fetch({
|
|
71
67
|
url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
|
|
@@ -77,7 +73,6 @@ export default function completions(params, logback, thinkback) {
|
|
|
77
73
|
body: JSON.stringify(body),
|
|
78
74
|
timeout: params.timeout != null ? params.timeout : this.timeout,
|
|
79
75
|
signal: params.signal
|
|
80
|
-
// #end
|
|
81
76
|
}).then(res => {
|
|
82
77
|
|
|
83
78
|
// 非 2xx:非流式等错误体读完再判,流式直接中断
|
|
@@ -87,7 +82,6 @@ export default function completions(params, logback, thinkback) {
|
|
|
87
82
|
});
|
|
88
83
|
|
|
89
84
|
// 数据流
|
|
90
|
-
// #doc:stream
|
|
91
85
|
res.on("data", chunk => {
|
|
92
86
|
if (settled) return;
|
|
93
87
|
if (!params.stream) {
|
|
@@ -100,7 +94,6 @@ export default function completions(params, logback, thinkback) {
|
|
|
100
94
|
} catch (e) {
|
|
101
95
|
streamError = e;
|
|
102
96
|
fail(e);
|
|
103
|
-
// #end
|
|
104
97
|
return;
|
|
105
98
|
}
|
|
106
99
|
try {
|
package/src/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import completions from "./completions.js";
|
|
2
2
|
|
|
3
|
-
// #doc:ctor
|
|
4
3
|
function Model(fields) {
|
|
5
4
|
this.model = fields.model;
|
|
6
5
|
this.apiKey = fields.apiKey;
|
|
@@ -11,7 +10,6 @@ function Model(fields) {
|
|
|
11
10
|
this.topP = fields.topP;
|
|
12
11
|
this.maxTokens = fields.maxTokens;
|
|
13
12
|
this.timeout = fields.timeout;
|
|
14
|
-
// #end
|
|
15
13
|
}
|
|
16
14
|
|
|
17
15
|
Model.prototype.completions = completions;
|
package/src/parseString.js
CHANGED
|
@@ -34,20 +34,16 @@ export default function (value) {
|
|
|
34
34
|
let text = String(value == null ? "" : value).trim();
|
|
35
35
|
|
|
36
36
|
// 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
|
|
37
|
-
// #doc:done
|
|
38
37
|
text = text.replace(/data:\s*\[DONE\]$/, "").trim();
|
|
39
38
|
if (text === "" || text === "[DONE]") return [];
|
|
40
|
-
// #end
|
|
41
39
|
|
|
42
40
|
// 单条:带 data: 前缀或裸 JSON
|
|
43
41
|
let single = tryParse(stripDataPrefix(text)) || tryParse(text);
|
|
44
42
|
if (single) return checkError(single.value);
|
|
45
43
|
|
|
46
44
|
// 多条 SSE 事件,以 "\n\ndata: " 分隔
|
|
47
|
-
// #doc:multi
|
|
48
45
|
const parts = text.split(/\r?\n\r?\ndata: /);
|
|
49
46
|
if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
|
|
50
|
-
// #end
|
|
51
47
|
|
|
52
48
|
// NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
|
|
53
49
|
const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
|
package/src/reasoning.js
CHANGED
|
@@ -16,14 +16,12 @@ const CLOSE = "</think>";
|
|
|
16
16
|
|
|
17
17
|
// 计算文本尾部与标签前缀的最长匹配长度
|
|
18
18
|
// 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
|
|
19
|
-
// #doc:partial
|
|
20
19
|
function partialTagLength(text, tag) {
|
|
21
20
|
const max = Math.min(tag.length - 1, text.length);
|
|
22
21
|
for (let len = max; len > 0; len--) {
|
|
23
22
|
if (text.endsWith(tag.slice(0, len))) return len;
|
|
24
23
|
}
|
|
25
24
|
return 0;
|
|
26
|
-
// #end
|
|
27
25
|
}
|
|
28
26
|
|
|
29
27
|
// 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
|
package/src/streamHandler.js
CHANGED
|
@@ -13,7 +13,6 @@ function normalizeCall(toolCall) {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
// 续片:按 index 优先归并,否则追加到最后一个槽位
|
|
16
|
-
// #doc:merge
|
|
17
16
|
function mergeToolCall(state, toolCall) {
|
|
18
17
|
if (!state._toolSlots) state._toolSlots = new Map();
|
|
19
18
|
|
|
@@ -46,7 +45,6 @@ function mergeToolCall(state, toolCall) {
|
|
|
46
45
|
}
|
|
47
46
|
|
|
48
47
|
appendArguments(slot, toolCall);
|
|
49
|
-
// #end
|
|
50
48
|
}
|
|
51
49
|
|
|
52
50
|
function appendArguments(slot, toolCall) {
|
package/types/completions.d.ts
CHANGED
|
@@ -3,18 +3,19 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import type {
|
|
5
5
|
ChatMessage,
|
|
6
|
+
ModelSamplingParams,
|
|
6
7
|
ModelToolCall,
|
|
7
8
|
ToolDescription
|
|
8
9
|
} from "@auipage/types";
|
|
9
10
|
|
|
10
11
|
/** completions 入参(对应底层请求体中本包负责拼装的部分) */
|
|
11
|
-
export interface CompletionsParams {
|
|
12
|
+
export interface CompletionsParams extends ModelSamplingParams {
|
|
12
13
|
messages: ChatMessage[];
|
|
13
14
|
/** 工具列表,每项携带一个标准 description,发请求时自动取 .description */
|
|
14
15
|
tools?: Array<{ description: ToolDescription }>;
|
|
15
16
|
/** 是否流式请求,默认 false */
|
|
16
17
|
stream?: boolean;
|
|
17
|
-
/**
|
|
18
|
+
/** 请求超时毫秒数,缺省表示不限制;显式传入时覆盖构造器默认值 */
|
|
18
19
|
timeout?: number;
|
|
19
20
|
/** 外部取消信号 */
|
|
20
21
|
signal?: AbortSignal | null;
|