@auipage/agent 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/dist/index.cjs +1 -1
- package/dist/index.js +36 -24
- package/dist/index.min.js +1 -1
- package/package.json +3 -3
- package/src/callFuns.js +1 -1
- package/src/createTool.js +1 -1
- package/src/runConversation.js +1 -1
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/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @auipage/agent v0.2.
|
|
1
|
+
/*! @auipage/agent v0.2.1 */
|
|
2
2
|
"use strict";class t{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 e 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,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 n=function(t){return function(n){return new Promise((r,o)=>{if(!n||!n.url)return void o(new Error("fetch: options.url is required"));var s;s=n.body,"[object Object]"===Object.prototype.toString.call(s)&&(n=Object.assign({},n,{body:JSON.stringify(n.body)}));const i=new e,c="function"==typeof AbortController?new AbortController:null;let a=null,l=!1;i._cancel=()=>{c&&c.abort()},queueMicrotask(()=>r(i));const u=()=>{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(){u(),i._push("end")},onError(t){l||(l=!0,u(),i._push("error",t),o(t))}},f=t=>{c&&c.abort(),h.onError(t)};if(n.timeout>0&&(a=setTimeout(()=>{a=null,f(new Error("fetch: 请求超时("+n.timeout+"ms)"))},n.timeout)),n.signal){if(n.signal.aborted)return void f(new Error("fetch: 请求已取消"));n.signal.addEventListener("abort",()=>{f(new Error("fetch: 请求已取消"))})}const d=c?Object.assign({},n,{signal:c.signal}):n;let m;try{m=t(d,h)}catch(t){return void h.onError(t)}m&&"function"==typeof m.then&&m.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:l}=t;"function"==typeof fetch?fetch(s,{method:i,headers:c,body:a,signal:l}).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:l="GET",headers:u={},body:h,signal:f}=t;let d;try{d=new c(a)}catch(t){return void r(t)}const m="https:"===d.protocol,p=m?i:s,g={method:l,hostname:d.hostname,port:d.port||(m?443:80),path:d.pathname+d.search,headers:u},y=p.request(g,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 r(t){return t.replace(/^data:\s*/,"")}function o(t){try{return{value:JSON.parse(t)}}catch(t){return null}}function s(t,e){const n=o(r(t.trim()));if(!n)throw new SyntaxError("模型返回无法解析:"+String(e).slice(0,120));return n.value}function i(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 c(t){let e=String(null==t?"":t).trim();if(e=e.replace(/data:\s*\[DONE\]$/,"").trim(),""===e||"[DONE]"===e)return[];let n=o(r(e))||o(e);if(n)return i(n.value);const c=e.split(/\r?\n\r?\ndata: /);if(c.length>1)return i(c.map(t=>s(t,e)));const a=e.split(/\r?\n/).filter(t=>t.trim()&&!t.trim().startsWith(":"));if(a.length>1)return i(a.map(t=>s(t,e)));throw new SyntaxError("模型返回无法解析:"+e.slice(0,120))}function a(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>",u="</think>";function h(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 f(t,e){const n=(e.thinkBuf||"")+t;if(e.thinkBuf="",e.inThink){const t=n.indexOf(u);if(-1===t){const t=h(n,u);return e.thinkBuf=n.slice(n.length-t),{thinking:n.slice(0,n.length-t),content:""}}e.inThink=!1;const r=f(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=h(n,l);return e.thinkBuf=n.slice(n.length-t),{thinking:"",content:n.slice(0,n.length-t)}}const o=n.indexOf(u,r);if(-1!==o){const t=f(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=h(s,u);return e.thinkBuf=s.slice(s.length-i),{thinking:s.slice(0,s.length-i),content:n.slice(0,r)}}function d(t){const e=t.function||{};return{...t,function:{...e,arguments:"string"==typeof e.arguments?e.arguments:""}}}function m(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 p(o,e);const s=d(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=d(e),n.push(o),void(null!==r&&t._toolSlots.set(r,o));p(o,e)}function p(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 g(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=a(i,s.content);"object"==typeof t&&(i=t.reasoning,s.content=t.content),n&&n(i)}if(s.content){const t=f(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)m(r,t)}}function y(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 _(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}function k(t,e){const n=(e||[]).map(e=>{const n=e&&e.function||{},r=(t.tools||[]).find(t=>t.description.function.name===n.name);if(!r)return Promise.resolve("工具"+n.name+"不存在");if("function"!=typeof r.execute)return Promise.resolve("工具"+n.name+"缺少 execute");let o;try{o="string"==typeof n.arguments&&n.arguments.trim()?JSON.parse(n.arguments):{}}catch(t){return Promise.resolve("参数解析失败:"+t)}try{return Promise.resolve(r.execute(o)).catch(t=>"运行出错:"+t)}catch(t){return Promise.resolve("运行出错:"+t)}});return Promise.all(n)}function v(t,e){return{role:"tool",tool_call_id:t.id,tool_name:t.function.name,content:"string"==typeof e?e:JSON.stringify(e)+""}}function w(t,e){return e.content&&t.push({role:"assistant",content:e.content}),!!(e.tool_calls&&e.tool_calls.length>0)&&(t.push({role:"assistant",tool_calls:e.tool_calls}),!0)}function b(t){this.ms=t}function E(t){t=t||{},this.model=new _(t.model),this.tools=t.tools||[],this.systemPrompt=t.systemPrompt||"",this.stream=t.stream||!1,this.maxSteps=t.maxSteps>0?t.maxSteps:0,this.signal=t.signal||null}_.prototype.completions=function(t,e,r){return new Promise((o,s)=>{const i={content:"",tool_calls:[]},a={logback:e,thinkback:r};let l="",u=null,h=null,f=!1;const d=(t,e)=>{f||(f=!0,t(e))},m=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,"模型请求失败")),p={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,v=null!=t.maxTokens?t.maxTokens:this.maxTokens;null!=_&&(p.temperature=_),null!=k&&(p.top_p=k),null!=v&&(p.max_tokens=v),n({url:`${this.baseURL.replace(/\/+$/,"")}/chat/completions`,method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(p),timeout:null!=t.timeout?t.timeout:this.timeout,signal:t.signal}).then(e=>{e.on("http-error",e=>{u=e,t.stream&&m(y(e))}),e.on("data",e=>{if(f)return;if(!t.stream)return void(l+=e);let n;try{n=c(e.toString())}catch(t){return h=t,void m(t)}try{const t=Array.isArray(n)?n:[n];for(const e of t)g(e.choices,a,i)}catch(t){m(t)}}),e.on("end",()=>{if(t.stream){if(h)return void m(h);if(u)return void m(y(u))}else{if(u)return void m(y(u,l));try{const t=c(l),e=t&&t.choices;if(!e||!e[0]||!e[0].message)throw new Error("模型响应缺少 choices[0].message");g([{delta:e[0].message}],a,i)}catch(t){return void m(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,a),d(o,{content:i.content,tool_calls:i.tool_calls})}),e.on("error",t=>m(t))}).catch(t=>m(t))})},b.prototype.create=function({description:t,execute:e},n){let r=this;const o=n&&n.timeout>0?n.timeout:0;return{description:t,execute:async function(n){let s={type:"tool-call",status:"pending",id:Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),name:t.function.name,caller:e?"backend":"frontend",args:n};if(e){let t,o;r.ms.send(s);try{t=await e(n),o="success"}catch(e){t=e,o="error"}if(r.ms.send(function(t,e){for(const n in t)e[n]=t[n];return e}({status:o,result:t},s)),"error"===o)throw t;return t}let i=null,c=null;const a=()=>{c&&(clearTimeout(c),c=null),delete globalThis[s.id]},l=new Promise((t,e)=>{i={resolve:t,reject:e}});globalThis[s.id]=function(t,e){if(!i)return;const n=i;i=null,a(),"error"===e?n.reject(t):n.resolve(t)},o>0&&(c=setTimeout(()=>{if(!i)return;const e=i;i=null,a(),e.reject(new Error("前端工具调用超时:"+t.function.name))},o));try{r.ms.send(s)}catch(t){throw i=null,a(),t}return l}}},E.prototype.generate=function(t,e,n){if(Array.isArray(t)||(t=[]),this.systemPrompt){let e=t[0];e&&"system"===e.role&&e.content===this.systemPrompt||t.unshift({role:"system",content:this.systemPrompt})}return async function(t,e,n,r){const o=t.maxSteps>0?t.maxSteps:1/0;for(let s=1;s<=o;s++){const o=await t.model.completions({messages:e,tools:t.tools,stream:t.stream,signal:t.signal||void 0},n,r);if(!w(e,o))return o.content;const s=await k(t,o.tool_calls);o.tool_calls.forEach((t,n)=>{e.push(v(t,s[n]))})}throw new Error("工具调用步骤超过 maxSteps 上限:"+t.maxSteps)}(this,t,e,n)},exports.Agent=E,exports.CreateTool=b;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/*! @auipage/agent v0.2.
|
|
1
|
+
/*! @auipage/agent 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];
|
|
@@ -790,7 +803,7 @@ function callFuns(_this, tool_calls) {
|
|
|
790
803
|
return Promise.resolve(tool.execute(args)).catch(e => "运行出错:" + e);
|
|
791
804
|
} catch (e) {
|
|
792
805
|
return Promise.resolve("运行出错:" + e);
|
|
793
|
-
}
|
|
806
|
+
}
|
|
794
807
|
});
|
|
795
808
|
|
|
796
809
|
return Promise.all(tasks);
|
|
@@ -853,7 +866,7 @@ async function runConversation(_this, messages, logback, thinkback) {
|
|
|
853
866
|
result.tool_calls.forEach((call, i) => {
|
|
854
867
|
messages.push(toToolMessage(call, toolResults[i]));
|
|
855
868
|
});
|
|
856
|
-
}
|
|
869
|
+
}
|
|
857
870
|
|
|
858
871
|
throw new Error("工具调用步骤超过 maxSteps 上限:" + _this.maxSteps);
|
|
859
872
|
}
|
|
@@ -914,9 +927,8 @@ CreateTool.prototype.create = function ({ description, execute }, options) {
|
|
|
914
927
|
if (status === "error") throw result;
|
|
915
928
|
|
|
916
929
|
return result;
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
// 前端工具调用
|
|
930
|
+
}
|
|
931
|
+
// 前端工具调用
|
|
920
932
|
let settle = null;
|
|
921
933
|
let timer = null;
|
|
922
934
|
|
package/dist/index.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! @auipage/agent v0.2.
|
|
1
|
+
/*! @auipage/agent 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_agent={})}(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,l=!1;i._cancel=()=>{c&&c.abort()},queueMicrotask(()=>r(i));const u=()=>{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(){u(),i._push("end")},onError(t){l||(l=!0,u(),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 m;try{m=t(d,h)}catch(t){return void h.onError(t)}m&&"function"==typeof m.then&&m.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:l}=t;"function"==typeof fetch?fetch(s,{method:i,headers:c,body:a,signal:l}).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:l="GET",headers:u={},body:h,signal:f}=t;let d;try{d=new c(a)}catch(t){return void r(t)}const m="https:"===d.protocol,p=m?i:s,g={method:l,hostname:d.hostname,port:d.port||(m?443:80),path:d.pathname+d.search,headers:u},y=p.request(g,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 l(t,e){if(!/<\/think>/.test(t))return t;const n=t.split("</think>");return{reasoning:n[0].replace("<think>",""),content:n[1]+(e||"")}}const u="<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(u);if(-1===r){const t=f(n,u);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 m(t){const e=t.function||{};return{...t,function:{...e,arguments:"string"==typeof e.arguments?e.arguments:""}}}function p(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 g(o,e);const s=m(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=m(e),n.push(o),void(null!==r&&t._toolSlots.set(r,o));g(o,e)}function g(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=l(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)p(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}function v(t,e){const n=(e||[]).map(e=>{const n=e&&e.function||{},r=(t.tools||[]).find(t=>t.description.function.name===n.name);if(!r)return Promise.resolve("工具"+n.name+"不存在");if("function"!=typeof r.execute)return Promise.resolve("工具"+n.name+"缺少 execute");let o;try{o="string"==typeof n.arguments&&n.arguments.trim()?JSON.parse(n.arguments):{}}catch(t){return Promise.resolve("参数解析失败:"+t)}try{return Promise.resolve(r.execute(o)).catch(t=>"运行出错:"+t)}catch(t){return Promise.resolve("运行出错:"+t)}});return Promise.all(n)}function b(t,e){return{role:"tool",tool_call_id:t.id,tool_name:t.function.name,content:"string"==typeof e?e:JSON.stringify(e)+""}}function w(t,e){return e.content&&t.push({role:"assistant",content:e.content}),!!(e.tool_calls&&e.tool_calls.length>0)&&(t.push({role:"assistant",tool_calls:e.tool_calls}),!0)}function E(t){this.ms=t}function S(t){t=t||{},this.model=new k(t.model),this.tools=t.tools||[],this.systemPrompt=t.systemPrompt||"",this.stream=t.stream||!1,this.maxSteps=t.maxSteps>0?t.maxSteps:0,this.signal=t.signal||null}k.prototype.completions=function(t,e,n){return new Promise((o,s)=>{const i={content:"",tool_calls:[]},c={logback:e,thinkback:n};let l="",u=null,h=null,f=!1;const d=(t,e)=>{f||(f=!0,t(e))},m=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,"模型请求失败")),p={model:this.model,messages:t.messages,tools:t.tools?t.tools.map(t=>t.description):[],stream:t.stream},g=null!=t.temperature?t.temperature:this.temperature,k=null!=t.topP?t.topP:this.topP,v=null!=t.maxTokens?t.maxTokens:this.maxTokens;null!=g&&(p.temperature=g),null!=k&&(p.top_p=k),null!=v&&(p.max_tokens=v),r({url:`${this.baseURL.replace(/\/+$/,"")}/chat/completions`,method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(p),timeout:null!=t.timeout?t.timeout:this.timeout,signal:t.signal}).then(e=>{e.on("http-error",e=>{u=e,t.stream&&m(_(e))}),e.on("data",e=>{if(f)return;if(!t.stream)return void(l+=e);let n;try{n=a(e.toString())}catch(t){return h=t,void m(t)}try{const t=Array.isArray(n)?n:[n];for(const e of t)y(e.choices,c,i)}catch(t){m(t)}}),e.on("end",()=>{if(t.stream){if(h)return void m(h);if(u)return void m(_(u))}else{if(u)return void m(_(u,l));try{const t=a(l),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 m(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=>m(t))}).catch(t=>m(t))})},E.prototype.create=function({description:t,execute:e},n){let r=this;const o=n&&n.timeout>0?n.timeout:0;return{description:t,execute:async function(n){let s={type:"tool-call",status:"pending",id:Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),name:t.function.name,caller:e?"backend":"frontend",args:n};if(e){let t,o;r.ms.send(s);try{t=await e(n),o="success"}catch(e){t=e,o="error"}if(r.ms.send(function(t,e){for(const n in t)e[n]=t[n];return e}({status:o,result:t},s)),"error"===o)throw t;return t}let i=null,c=null;const a=()=>{c&&(clearTimeout(c),c=null),delete globalThis[s.id]},l=new Promise((t,e)=>{i={resolve:t,reject:e}});globalThis[s.id]=function(t,e){if(!i)return;const n=i;i=null,a(),"error"===e?n.reject(t):n.resolve(t)},o>0&&(c=setTimeout(()=>{if(!i)return;const e=i;i=null,a(),e.reject(new Error("前端工具调用超时:"+t.function.name))},o));try{r.ms.send(s)}catch(t){throw i=null,a(),t}return l}}},S.prototype.generate=function(t,e,n){if(Array.isArray(t)||(t=[]),this.systemPrompt){let e=t[0];e&&"system"===e.role&&e.content===this.systemPrompt||t.unshift({role:"system",content:this.systemPrompt})}return async function(t,e,n,r){const o=t.maxSteps>0?t.maxSteps:1/0;for(let s=1;s<=o;s++){const o=await t.model.completions({messages:e,tools:t.tools,stream:t.stream,signal:t.signal||void 0},n,r);if(!w(e,o))return o.content;const s=await v(t,o.tool_calls);o.tool_calls.forEach((t,n)=>{e.push(b(t,s[n]))})}throw new Error("工具调用步骤超过 maxSteps 上限:"+t.maxSteps)}(this,t,e,n)},t.Agent=S,t.CreateTool=E});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auipage/agent",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "@auipage/agent",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"types": "./types/index.d.ts",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
},
|
|
52
52
|
"homepage": "https://github.com/handless-ui/auipage#readme",
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@auipage/model": "^0.2.
|
|
55
|
-
"@auipage/types": "^0.2.
|
|
54
|
+
"@auipage/model": "^0.2.1",
|
|
55
|
+
"@auipage/types": "^0.2.1",
|
|
56
56
|
"oipage": "^2.1.0"
|
|
57
57
|
}
|
|
58
58
|
}
|
package/src/callFuns.js
CHANGED
|
@@ -36,9 +36,9 @@ export default function callFuns(_this, tool_calls) {
|
|
|
36
36
|
return Promise.resolve(tool.execute(args)).catch(e => "运行出错:" + e);
|
|
37
37
|
} catch (e) {
|
|
38
38
|
return Promise.resolve("运行出错:" + e);
|
|
39
|
-
// #end
|
|
40
39
|
}
|
|
41
40
|
});
|
|
42
41
|
|
|
43
42
|
return Promise.all(tasks);
|
|
43
|
+
// #end
|
|
44
44
|
};
|
package/src/createTool.js
CHANGED
package/src/runConversation.js
CHANGED
|
@@ -58,8 +58,8 @@ export default async function runConversation(_this, messages, logback, thinkbac
|
|
|
58
58
|
result.tool_calls.forEach((call, i) => {
|
|
59
59
|
messages.push(toToolMessage(call, toolResults[i]));
|
|
60
60
|
});
|
|
61
|
-
// #end
|
|
62
61
|
}
|
|
63
62
|
|
|
64
63
|
throw new Error("工具调用步骤超过 maxSteps 上限:" + _this.maxSteps);
|
|
64
|
+
// #end
|
|
65
65
|
}
|