@auipage/model 0.2.0-alpha.2 → 0.2.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/AUTHORS.txt +6 -6
- package/CHANGELOG +30 -30
- package/README.md +83 -83
- package/dist/index.cjs +1 -1
- package/dist/index.js +734 -734
- package/dist/index.min.js +1 -1
- package/package.json +7 -4
- package/src/completions.js +149 -149
- package/src/index.js +19 -19
- package/src/parseString.js +57 -57
- package/src/reasoning.js +80 -80
- package/src/streamHandler.js +103 -103
- package/types/completions.d.ts +35 -35
- package/types/index.d.ts +13 -13
- package/types/model.d.ts +33 -33
package/dist/index.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @auipage/model v0.2.0
|
|
1
|
+
/*! @auipage/model v0.2.0 */
|
|
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.0
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "@auipage/model",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "./types/index.d.ts",
|
|
@@ -22,7 +22,10 @@
|
|
|
22
22
|
"types/",
|
|
23
23
|
"CHANGELOG",
|
|
24
24
|
"AUTHORS.txt",
|
|
25
|
-
".mailmap"
|
|
25
|
+
".mailmap",
|
|
26
|
+
"LICENSE",
|
|
27
|
+
"README.md",
|
|
28
|
+
"package.json"
|
|
26
29
|
],
|
|
27
30
|
"scripts": {
|
|
28
31
|
"prepublishOnly": "node ../../scripts/swap-pkg.js --mode=publish",
|
|
@@ -48,7 +51,7 @@
|
|
|
48
51
|
},
|
|
49
52
|
"homepage": "https://github.com/handless-ui/auipage#readme",
|
|
50
53
|
"dependencies": {
|
|
51
|
-
"@auipage/fetch": "^0.2.0
|
|
52
|
-
"@auipage/types": "^0.2.0
|
|
54
|
+
"@auipage/fetch": "^0.2.0",
|
|
55
|
+
"@auipage/types": "^0.2.0"
|
|
53
56
|
}
|
|
54
57
|
}
|
package/src/completions.js
CHANGED
|
@@ -1,149 +1,149 @@
|
|
|
1
|
-
import { fetch } from "@auipage/fetch";
|
|
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
|
-
}
|
|
1
|
+
import { fetch } from "@auipage/fetch";
|
|
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
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
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 };
|
|
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
CHANGED
|
@@ -1,57 +1,57 @@
|
|
|
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
|
-
}
|
|
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
|
+
}
|