@auipage/agent 0.1.0 → 0.2.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +136 -154
- package/dist/index.cjs +2 -0
- package/dist/index.js +968 -637
- package/dist/index.min.js +2 -0
- package/package.json +19 -5
- package/types/agent.d.ts +58 -47
- package/types/create-tool.d.ts +44 -38
- package/types/index.d.ts +20 -20
- package/types/tool.d.ts +15 -15
- package/.mailmap +0 -1
- package/AUTHORS.txt +0 -6
- package/CHANGELOG +0 -4
- package/dist/package.json +0 -3
- package/src/callFuns.js +0 -35
- package/src/createTool.js +0 -60
- package/src/index.js +0 -21
- package/src/runConversation.js +0 -56
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @auipage/agent 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_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,11 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@auipage/agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0-alpha.1",
|
|
4
4
|
"description": "@auipage/agent",
|
|
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,8 +44,8 @@
|
|
|
30
44
|
},
|
|
31
45
|
"homepage": "https://github.com/handless-ui/auipage#readme",
|
|
32
46
|
"dependencies": {
|
|
33
|
-
"@auipage/model": "^0.
|
|
34
|
-
"@auipage/types": "^0.
|
|
47
|
+
"@auipage/model": "^0.2.0-alpha.1",
|
|
48
|
+
"@auipage/types": "^0.2.0-alpha.1",
|
|
35
49
|
"oipage": "^2.1.0"
|
|
36
50
|
}
|
|
37
51
|
}
|
package/types/agent.d.ts
CHANGED
|
@@ -1,47 +1,58 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Agent 构造器:模型对话循环 + 工具调用编排
|
|
3
|
-
*/
|
|
4
|
-
import type { ChatMessage, ModelConfig } from "@auipage/types";
|
|
5
|
-
import type { Model } from "@auipage/model";
|
|
6
|
-
import type { AgentTool } from "./tool.js";
|
|
7
|
-
|
|
8
|
-
/** 流式正文回调,参数为模型本次给出的文本(增量) */
|
|
9
|
-
export type Logback = (text: string) => void;
|
|
10
|
-
|
|
11
|
-
/** 流式思维链 / 推理过程回调,参数为本次增量文本 */
|
|
12
|
-
export type Thinkback = (text: string) => void;
|
|
13
|
-
|
|
14
|
-
export interface AgentOptions {
|
|
15
|
-
/** 透传给 @auipage/model 的模型配置 */
|
|
16
|
-
model: ModelConfig;
|
|
17
|
-
/** 系统提示词,会作为首条 system 消息发送,默认 "" */
|
|
18
|
-
systemPrompt?: string;
|
|
19
|
-
/** 工具列表,默认 [] */
|
|
20
|
-
tools?: AgentTool[];
|
|
21
|
-
/** 是否开启流式输出,默认 false */
|
|
22
|
-
stream?: boolean;
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Agent 构造器:模型对话循环 + 工具调用编排
|
|
3
|
+
*/
|
|
4
|
+
import type { ChatMessage, ModelConfig } from "@auipage/types";
|
|
5
|
+
import type { Model } from "@auipage/model";
|
|
6
|
+
import type { AgentTool } from "./tool.js";
|
|
7
|
+
|
|
8
|
+
/** 流式正文回调,参数为模型本次给出的文本(增量) */
|
|
9
|
+
export type Logback = (text: string) => void;
|
|
10
|
+
|
|
11
|
+
/** 流式思维链 / 推理过程回调,参数为本次增量文本 */
|
|
12
|
+
export type Thinkback = (text: string) => void;
|
|
13
|
+
|
|
14
|
+
export interface AgentOptions {
|
|
15
|
+
/** 透传给 @auipage/model 的模型配置 */
|
|
16
|
+
model: ModelConfig;
|
|
17
|
+
/** 系统提示词,会作为首条 system 消息发送,默认 "" */
|
|
18
|
+
systemPrompt?: string;
|
|
19
|
+
/** 工具列表,默认 [] */
|
|
20
|
+
tools?: AgentTool[];
|
|
21
|
+
/** 是否开启流式输出,默认 false */
|
|
22
|
+
stream?: boolean;
|
|
23
|
+
/** 工具调用循环上限,默认 0(不限制);超过上限以 error reject */
|
|
24
|
+
maxSteps?: number;
|
|
25
|
+
/**
|
|
26
|
+
* 取消信号(0.2.0 起提供),会透传给每次模型请求;
|
|
27
|
+
* abort 后本轮以错误 reject,可配合 AuiPage.stop() 的 context.signal 使用。
|
|
28
|
+
*/
|
|
29
|
+
signal?: AbortSignal | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export declare class Agent {
|
|
33
|
+
constructor(options: AgentOptions);
|
|
34
|
+
|
|
35
|
+
/** 底层模型实例 */
|
|
36
|
+
model: Model;
|
|
37
|
+
tools: AgentTool[];
|
|
38
|
+
systemPrompt: string;
|
|
39
|
+
stream: boolean;
|
|
40
|
+
/** 工具调用循环上限,0 表示不限制 */
|
|
41
|
+
maxSteps: number;
|
|
42
|
+
/** 取消信号,未设置时为 null */
|
|
43
|
+
signal: AbortSignal | null;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 执行对话循环:模型请求 → 工具调用 → 结果回传 → 继续请求,直至拿到最终文本。
|
|
47
|
+
*
|
|
48
|
+
* @param messages 本轮对话消息数组;配置了非空 systemPrompt 时会自动插到最前(原地修改)
|
|
49
|
+
* @param logback 流式正文增量回调
|
|
50
|
+
* @param thinkback 流式思维链增量回调
|
|
51
|
+
* @returns 模型最终回复;只产出工具调用而无文本时可能为 undefined
|
|
52
|
+
*/
|
|
53
|
+
generate(
|
|
54
|
+
messages: ChatMessage[],
|
|
55
|
+
logback?: Logback,
|
|
56
|
+
thinkback?: Thinkback
|
|
57
|
+
): Promise<string | undefined>;
|
|
58
|
+
}
|
package/types/create-tool.d.ts
CHANGED
|
@@ -1,38 +1,44 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* CreateTool:前后端工具桥接器
|
|
3
|
-
*
|
|
4
|
-
* 运行在服务端的 Agent 通过消息流把工具调用状态推送给页面,
|
|
5
|
-
* 页面执行完“前端工具”后再把结果回传,唤醒挂起的调用。
|
|
6
|
-
*/
|
|
7
|
-
import type {
|
|
8
|
-
StreamEvent,
|
|
9
|
-
ToolDescription,
|
|
10
|
-
ToolExecutor
|
|
11
|
-
} from "@auipage/types";
|
|
12
|
-
import type { AgentTool } from "./tool.js";
|
|
13
|
-
|
|
14
|
-
/** 消息流发送端(结构与 @auipage/core 的 MessageStream 兼容) */
|
|
15
|
-
export interface MessageSender {
|
|
16
|
-
send(event: StreamEvent): void;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/** ct.create 的入参:execute 缺省即“前端工具”,调用会挂起等待页面回传 */
|
|
20
|
-
export interface CreateToolInput {
|
|
21
|
-
description: ToolDescription;
|
|
22
|
-
/** 后端工具:在 Agent 所在服务端执行;缺省则为前端工具 */
|
|
23
|
-
execute?: ToolExecutor;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
1
|
+
/**
|
|
2
|
+
* CreateTool:前后端工具桥接器
|
|
3
|
+
*
|
|
4
|
+
* 运行在服务端的 Agent 通过消息流把工具调用状态推送给页面,
|
|
5
|
+
* 页面执行完“前端工具”后再把结果回传,唤醒挂起的调用。
|
|
6
|
+
*/
|
|
7
|
+
import type {
|
|
8
|
+
StreamEvent,
|
|
9
|
+
ToolDescription,
|
|
10
|
+
ToolExecutor
|
|
11
|
+
} from "@auipage/types";
|
|
12
|
+
import type { AgentTool } from "./tool.js";
|
|
13
|
+
|
|
14
|
+
/** 消息流发送端(结构与 @auipage/core 的 MessageStream 兼容) */
|
|
15
|
+
export interface MessageSender {
|
|
16
|
+
send(event: StreamEvent): void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** ct.create 的入参:execute 缺省即“前端工具”,调用会挂起等待页面回传 */
|
|
20
|
+
export interface CreateToolInput {
|
|
21
|
+
description: ToolDescription;
|
|
22
|
+
/** 后端工具:在 Agent 所在服务端执行;缺省则为前端工具 */
|
|
23
|
+
execute?: ToolExecutor;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** ct.create 的可选配置 */
|
|
27
|
+
export interface CreateToolOptions {
|
|
28
|
+
/** 前端工具等待页面回传的超时毫秒数,0 / 缺省表示不限制;超时以 error reject */
|
|
29
|
+
timeout?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export declare class CreateTool {
|
|
33
|
+
constructor(ms: MessageSender);
|
|
34
|
+
|
|
35
|
+
/** 构造时传入的消息流发送端 */
|
|
36
|
+
ms: MessageSender;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 包装一个工具为标准 AgentTool:
|
|
40
|
+
* - 有 execute:执行前后通过消息流推送 pending / success / error;失败时抛错由 callFuns 转成文本;
|
|
41
|
+
* - 无 execute:只推送 pending,随后挂起,等待 globalThis[id](result, status?) 唤醒。
|
|
42
|
+
*/
|
|
43
|
+
create(input: CreateToolInput, options?: CreateToolOptions): AgentTool;
|
|
44
|
+
}
|
package/types/index.d.ts
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @auipage/agent 类型入口
|
|
3
|
-
*
|
|
4
|
-
* 智能体对话循环:工具调用编排、思维链回调,以及前后端工具桥接。
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
export {
|
|
8
|
-
Agent,
|
|
9
|
-
type AgentOptions,
|
|
10
|
-
type Logback,
|
|
11
|
-
type Thinkback
|
|
12
|
-
} from "./agent.js";
|
|
13
|
-
|
|
14
|
-
export type { AgentTool } from "./tool.js";
|
|
15
|
-
|
|
16
|
-
export {
|
|
17
|
-
CreateTool,
|
|
18
|
-
type MessageSender,
|
|
19
|
-
type CreateToolInput
|
|
20
|
-
} from "./create-tool.js";
|
|
1
|
+
/**
|
|
2
|
+
* @auipage/agent 类型入口
|
|
3
|
+
*
|
|
4
|
+
* 智能体对话循环:工具调用编排、思维链回调,以及前后端工具桥接。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export {
|
|
8
|
+
Agent,
|
|
9
|
+
type AgentOptions,
|
|
10
|
+
type Logback,
|
|
11
|
+
type Thinkback
|
|
12
|
+
} from "./agent.js";
|
|
13
|
+
|
|
14
|
+
export type { AgentTool } from "./tool.js";
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
CreateTool,
|
|
18
|
+
type MessageSender,
|
|
19
|
+
type CreateToolInput
|
|
20
|
+
} from "./create-tool.js";
|
package/types/tool.d.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Agent 直接执行的工具形态
|
|
3
|
-
*/
|
|
4
|
-
import type { ToolDescription, ToolExecutor } from "@auipage/types";
|
|
5
|
-
|
|
6
|
-
export interface AgentTool {
|
|
7
|
-
/** 符合模型 tools 规范的描述对象 */
|
|
8
|
-
description: ToolDescription;
|
|
9
|
-
/**
|
|
10
|
-
* 工具执行函数。
|
|
11
|
-
* 注意:普通工具必须提供;只有经 CreateTool 桥接的“前端工具”
|
|
12
|
-
* 才允许在创建时缺省(由 CreateTool.create 补齐 execute)。
|
|
13
|
-
*/
|
|
14
|
-
execute: ToolExecutor;
|
|
15
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Agent 直接执行的工具形态
|
|
3
|
+
*/
|
|
4
|
+
import type { ToolDescription, ToolExecutor } from "@auipage/types";
|
|
5
|
+
|
|
6
|
+
export interface AgentTool {
|
|
7
|
+
/** 符合模型 tools 规范的描述对象 */
|
|
8
|
+
description: ToolDescription;
|
|
9
|
+
/**
|
|
10
|
+
* 工具执行函数。
|
|
11
|
+
* 注意:普通工具必须提供;只有经 CreateTool 桥接的“前端工具”
|
|
12
|
+
* 才允许在创建时缺省(由 CreateTool.create 补齐 execute)。
|
|
13
|
+
*/
|
|
14
|
+
execute: ToolExecutor;
|
|
15
|
+
}
|
package/.mailmap
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
zxl20070701 <1904314465@qq.com>
|
package/AUTHORS.txt
DELETED
package/CHANGELOG
DELETED
package/dist/package.json
DELETED
package/src/callFuns.js
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 根据模型返回的 tool_calls,依次在 _this.tools 中查找匹配的工具并执行,
|
|
3
|
-
* 返回与 tool_calls 等长的结果数组(同步值/异步值都会被规范化)。
|
|
4
|
-
*
|
|
5
|
-
* @param {Object} _this Agent 实例
|
|
6
|
-
* @param {Array} tool_calls 模型返回的工具调用列表
|
|
7
|
-
* @returns {Promise<Array>} 每个工具的执行结果,未匹配到的槽位会被填入错误说明字符串
|
|
8
|
-
*/
|
|
9
|
-
export default function callFuns(_this, tool_calls) {
|
|
10
|
-
|
|
11
|
-
const tasks = tool_calls.map(call => {
|
|
12
|
-
const tool = _this.tools.find(
|
|
13
|
-
t => t.description.function.name === call.function.name
|
|
14
|
-
);
|
|
15
|
-
|
|
16
|
-
if (!tool) {
|
|
17
|
-
return Promise.resolve("工具" + call.function.name + "不存在");
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
let result;
|
|
21
|
-
try {
|
|
22
|
-
result = tool.execute(JSON.parse(call.function.arguments));
|
|
23
|
-
} catch (e) {
|
|
24
|
-
return Promise.resolve("参数解析失败:" + e);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
if (result instanceof Promise) {
|
|
28
|
-
// 工具内部报错也不要阻断对话,转成字符串继续往下走
|
|
29
|
-
return result.catch(e => "运行出错:" + e);
|
|
30
|
-
}
|
|
31
|
-
return Promise.resolve(result);
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
return Promise.all(tasks);
|
|
35
|
-
};
|
package/src/createTool.js
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import { initOption } from "oipage/web/option/index.js";
|
|
2
|
-
|
|
3
|
-
function CreateTool(ms) {
|
|
4
|
-
this.ms = ms;
|
|
5
|
-
}
|
|
6
|
-
|
|
7
|
-
CreateTool.prototype.create = function ({ description, execute }) {
|
|
8
|
-
let _this = this;
|
|
9
|
-
return {
|
|
10
|
-
description,
|
|
11
|
-
execute: async function (args) {
|
|
12
|
-
let toolInfo = {
|
|
13
|
-
type: "tool-call",
|
|
14
|
-
status: "pending",
|
|
15
|
-
id: Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),
|
|
16
|
-
name: description.function.name,
|
|
17
|
-
caller: execute ? "backend" : "frontend",
|
|
18
|
-
args
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
// 后端工具调用
|
|
22
|
-
if (execute) {
|
|
23
|
-
_this.ms.send(toolInfo); // 开始调用工具
|
|
24
|
-
|
|
25
|
-
let result, status;
|
|
26
|
-
try {
|
|
27
|
-
result = await execute(args);
|
|
28
|
-
status = "success"; // 调用成功
|
|
29
|
-
} catch (error) {
|
|
30
|
-
result = error;
|
|
31
|
-
status = "error"; // 调用失败
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
_this.ms.send(initOption({ // 结束调用工具
|
|
35
|
-
status,
|
|
36
|
-
result
|
|
37
|
-
}, toolInfo));
|
|
38
|
-
|
|
39
|
-
return result;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// 前端工具调用
|
|
43
|
-
else {
|
|
44
|
-
let _resolve = null;
|
|
45
|
-
globalThis[toolInfo.id] = function (result) {
|
|
46
|
-
_resolve(result);
|
|
47
|
-
delete globalThis[toolInfo.id];
|
|
48
|
-
};
|
|
49
|
-
|
|
50
|
-
_this.ms.send(toolInfo); // 开始调用工具
|
|
51
|
-
|
|
52
|
-
return new Promise((resolve, reject) => {
|
|
53
|
-
_resolve = resolve;
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
};
|
|
58
|
-
};
|
|
59
|
-
|
|
60
|
-
export default CreateTool;
|
package/src/index.js
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { Model } from "@auipage/model/src/index.js";
|
|
2
|
-
import runConversation from "./runConversation.js";
|
|
3
|
-
import CreateTool from "./createTool.js";
|
|
4
|
-
|
|
5
|
-
function Agent(option) {
|
|
6
|
-
this.model = new Model(option.model);
|
|
7
|
-
this.tools = option.tools || [];
|
|
8
|
-
this.systemPrompt = option.systemPrompt || "";
|
|
9
|
-
this.stream = option.stream || false;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
Agent.prototype.generate = function (messages, logback, thinkback) {
|
|
13
|
-
if (this.systemPrompt) messages.unshift({
|
|
14
|
-
role: "system",
|
|
15
|
-
content: this.systemPrompt
|
|
16
|
-
});
|
|
17
|
-
|
|
18
|
-
return runConversation(this, messages, logback, thinkback);
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
export { Agent, CreateTool };
|
package/src/runConversation.js
DELETED
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import callFuns from "./callFuns.js";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 把一次工具调用的执行结果转成 tool 消息。
|
|
5
|
-
*/
|
|
6
|
-
function toToolMessage(call, value) {
|
|
7
|
-
return {
|
|
8
|
-
role: "tool",
|
|
9
|
-
tool_call_id: call.id,
|
|
10
|
-
tool_name: call.function.name,
|
|
11
|
-
content: typeof value === "string" ? value : (JSON.stringify(value) + "")
|
|
12
|
-
};
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* 把模型响应按 role 追加到 messages,返回是否还有工具调用需要下一轮处理。
|
|
17
|
-
*/
|
|
18
|
-
function appendAssistantMessage(messages, result) {
|
|
19
|
-
if (result.content) {
|
|
20
|
-
messages.push({ role: "assistant", content: result.content });
|
|
21
|
-
}
|
|
22
|
-
if (result.tool_calls && result.tool_calls.length > 0) {
|
|
23
|
-
messages.push({ role: "assistant", tool_calls: result.tool_calls });
|
|
24
|
-
return true;
|
|
25
|
-
}
|
|
26
|
-
return false;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* 执行模型对话循环:
|
|
31
|
-
* 1. 调用模型获取响应
|
|
32
|
-
* 2. 若返回工具调用,依次执行工具并将结果追加到 messages,继续循环
|
|
33
|
-
* 3. 否则将最终内容 resolve 给调用方
|
|
34
|
-
*/
|
|
35
|
-
export default async function runConversation(_this, messages, logback, thinkback) {
|
|
36
|
-
|
|
37
|
-
while (true) {
|
|
38
|
-
const result = await _this.model.completions({
|
|
39
|
-
messages,
|
|
40
|
-
tools: _this.tools,
|
|
41
|
-
stream: _this.stream,
|
|
42
|
-
}, logback, thinkback);
|
|
43
|
-
|
|
44
|
-
const hasToolCalls = appendAssistantMessage(messages, result);
|
|
45
|
-
|
|
46
|
-
if (!hasToolCalls) {
|
|
47
|
-
return result.content;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
const toolResults = await callFuns(_this, result.tool_calls);
|
|
51
|
-
|
|
52
|
-
result.tool_calls.forEach((call, i) => {
|
|
53
|
-
messages.push(toToolMessage(call, toolResults[i]));
|
|
54
|
-
});
|
|
55
|
-
}
|
|
56
|
-
}
|