@auipage/model 0.2.0-alpha.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/dist/index.cjs +2 -0
- package/dist/index.js +671 -734
- package/dist/index.min.js +2 -0
- package/package.json +19 -5
- package/.mailmap +0 -1
- package/AUTHORS.txt +0 -6
- package/CHANGELOG +0 -29
- package/dist/package.json +0 -3
- package/src/completions.js +0 -149
- package/src/index.js +0 -19
- package/src/parseString.js +0 -57
- package/src/reasoning.js +0 -80
- package/src/streamHandler.js +0 -103
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @auipage/model v0.2.0-alpha.1 */
|
|
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,11 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auipage/model",
|
|
3
|
-
"version": "0.2.0-alpha.
|
|
3
|
+
"version": "0.2.0-alpha.1",
|
|
4
4
|
"description": "@auipage/model",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"
|
|
7
|
-
"
|
|
6
|
+
"types": "./types/index.d.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"development": "./src/index.js",
|
|
10
|
+
"types": "./types/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js",
|
|
12
|
+
"require": "./dist/index.cjs",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./src/*": "./src/*",
|
|
16
|
+
"./dist/*": "./dist/*"
|
|
17
|
+
},
|
|
8
18
|
"sideEffects": false,
|
|
19
|
+
"files": [
|
|
20
|
+
"dist/",
|
|
21
|
+
"types/"
|
|
22
|
+
],
|
|
9
23
|
"scripts": {
|
|
10
24
|
"prepublishOnly": "node ../../scripts/swap-pkg.js --mode=publish",
|
|
11
25
|
"postpublish": "node ../../scripts/swap-pkg.js --mode=restore"
|
|
@@ -30,7 +44,7 @@
|
|
|
30
44
|
},
|
|
31
45
|
"homepage": "https://github.com/handless-ui/auipage#readme",
|
|
32
46
|
"dependencies": {
|
|
33
|
-
"@auipage/fetch": "^0.2.0-alpha.
|
|
34
|
-
"@auipage/types": "^0.2.0-alpha.
|
|
47
|
+
"@auipage/fetch": "^0.2.0-alpha.1",
|
|
48
|
+
"@auipage/types": "^0.2.0-alpha.1"
|
|
35
49
|
}
|
|
36
50
|
}
|
package/.mailmap
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
zxl20070701 <1904314465@qq.com>
|
package/AUTHORS.txt
DELETED
package/CHANGELOG
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
v0.1.0:
|
|
2
|
-
date:2026-10-25
|
|
3
|
-
changes:
|
|
4
|
-
- 初始化版本
|
|
5
|
-
v0.2.0:
|
|
6
|
-
date:
|
|
7
|
-
changes:
|
|
8
|
-
- 修复bug:
|
|
9
|
-
1、模型请求 4xx / 网络失败时进程崩溃或请求永久挂起
|
|
10
|
-
2、页面在适配器、前端工具、历史入库任一环节失败后锁死(isExecuting 一直为 true)
|
|
11
|
-
3、工具并行调用分片串味,无参工具的调用直接失败
|
|
12
|
-
4、复用同一 messages 数组时 systemPrompt 重复累积
|
|
13
|
-
5、流式数据含 \r 换行或末尾 [DONE] 时正文被污染、解析提前中断
|
|
14
|
-
6、响应结束后才订阅 error 的监听器收不到终态
|
|
15
|
-
- 优化改造:
|
|
16
|
-
1、请求支持 timeout 与 signal,可主动取消
|
|
17
|
-
2、非 2xx 响应新增 http-error 事件,不再只有 ok=false
|
|
18
|
-
3、页面历史入库失败会明确报错,不再静默丢弃
|
|
19
|
-
4、监听器异常不再抛出为进程级异常
|
|
20
|
-
5、流式生成器取消后清空挂起队列,不再堆积残留
|
|
21
|
-
- 新增功能:
|
|
22
|
-
1、Agent 支持 maxSteps(默认 0,不限制)
|
|
23
|
-
2、新增 toModelMessages,把页面消息转成模型入参
|
|
24
|
-
3、新增 AuiPage.stop():执行中主动结束,内容保留、消息组标记 stopped,sendMessage 正常 resolve
|
|
25
|
-
4、新增 AuiPage.cancel():取消本轮,消息组标记 cancelled,sendMessage 以「已取消」reject
|
|
26
|
-
5、主动结束与取消的那一轮仍入库,存或丢由业务自行决定
|
|
27
|
-
6、task:end 增加 by(user / tool),取消时另带 displayed,列出已显示条目供界面撤销
|
|
28
|
-
7、工具 execute / render 拿到任务控制句柄,可直接 stop() / cancel() 结束整轮
|
|
29
|
-
8、取消信号经 context.signal 透传,Agent / model 均支持中断
|
package/dist/package.json
DELETED
package/src/completions.js
DELETED
|
@@ -1,149 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,57 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,80 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
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
|
-
}
|