@auipage/agent 0.1.0-alpha.5 → 0.2.0-alpha.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auipage/agent",
3
- "version": "0.1.0-alpha.5",
3
+ "version": "0.2.0-alpha.0",
4
4
  "description": "@auipage/agent",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -30,8 +30,8 @@
30
30
  },
31
31
  "homepage": "https://github.com/handless-ui/auipage#readme",
32
32
  "dependencies": {
33
- "@auipage/model": "^0.1.0-alpha.5",
34
- "@auipage/types": "^0.1.0-alpha.5",
33
+ "@auipage/model": "^0.2.0-alpha.0",
34
+ "@auipage/types": "^0.2.0-alpha.0",
35
35
  "oipage": "^2.1.0"
36
36
  }
37
37
  }
package/src/callFuns.js CHANGED
@@ -8,28 +8,37 @@
8
8
  */
9
9
  export default function callFuns(_this, tool_calls) {
10
10
 
11
- const tasks = tool_calls.map(call => {
12
- const tool = _this.tools.find(
13
- t => t.description.function.name === call.function.name
11
+ // #doc:map
12
+ const tasks = (tool_calls || []).map(call => {
13
+ const fn = (call && call.function) || {};
14
+ const tool = (_this.tools || []).find(
15
+ t => t.description.function.name === fn.name
14
16
  );
15
17
 
16
18
  if (!tool) {
17
- return Promise.resolve("工具" + call.function.name + "不存在");
19
+ return Promise.resolve("工具" + fn.name + "不存在");
18
20
  }
19
21
 
20
- let result;
22
+ if (typeof tool.execute !== "function") {
23
+ return Promise.resolve("工具" + fn.name + "缺少 execute");
24
+ }
25
+
26
+ let args;
21
27
  try {
22
- result = tool.execute(JSON.parse(call.function.arguments));
28
+ // 无参工具:arguments 为空字符串或缺失时按 {} 处理
29
+ args = typeof fn.arguments === "string" && fn.arguments.trim() ? JSON.parse(fn.arguments) : {};
23
30
  } catch (e) {
24
31
  return Promise.resolve("参数解析失败:" + e);
25
32
  }
26
33
 
27
- if (result instanceof Promise) {
28
- // 工具内部报错也不要阻断对话,转成字符串继续往下走
29
- return result.catch(e => "运行出错:" + e);
34
+ try {
35
+ // 工具内部报错(含同步抛错)也不要阻断对话,转成字符串继续往下走
36
+ return Promise.resolve(tool.execute(args)).catch(e => "运行出错:" + e);
37
+ } catch (e) {
38
+ return Promise.resolve("运行出错:" + e);
39
+ // #end
30
40
  }
31
- return Promise.resolve(result);
32
41
  });
33
42
 
34
43
  return Promise.all(tasks);
35
- };
44
+ };
package/src/createTool.js CHANGED
@@ -4,21 +4,30 @@ function CreateTool(ms) {
4
4
  this.ms = ms;
5
5
  }
6
6
 
7
- CreateTool.prototype.create = function ({ description, execute }) {
7
+ /**
8
+ * 包装一个工具。
9
+ *
10
+ * @param {object} input description + 可选 execute(缺省即前端工具)
11
+ * @param {object} [options] { timeout } 前端工具等待页面回传的超时毫秒数,0 表示不限制
12
+ */
13
+ CreateTool.prototype.create = function ({ description, execute }, options) {
8
14
  let _this = this;
15
+ const timeout = options && options.timeout > 0 ? options.timeout : 0;
16
+
9
17
  return {
10
18
  description,
11
19
  execute: async function (args) {
12
20
  let toolInfo = {
13
21
  type: "tool-call",
14
22
  status: "pending",
15
- id: Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),
23
+ id: Date.now().toString() + "_" + Math.random().toString(36).substring(2).toUpperCase(),
16
24
  name: description.function.name,
17
25
  caller: execute ? "backend" : "frontend",
18
26
  args
19
27
  };
20
28
 
21
29
  // 后端工具调用
30
+ // #doc:backend
22
31
  if (execute) {
23
32
  _this.ms.send(toolInfo); // 开始调用工具
24
33
 
@@ -36,25 +45,57 @@ CreateTool.prototype.create = function ({ description, execute }) {
36
45
  result
37
46
  }, toolInfo));
38
47
 
48
+ // 失败继续抛出,由 callFuns 统一转成给模型的错误文本
49
+ if (status === "error") throw result;
50
+
39
51
  return result;
52
+ // #end
40
53
  }
41
54
 
42
55
  // 前端工具调用
43
- else {
44
- let _resolve = null;
45
- globalThis[toolInfo.id] = function (result) {
46
- _resolve(result);
47
- delete globalThis[toolInfo.id];
48
- };
56
+ let settle = null;
57
+ let timer = null;
49
58
 
50
- _this.ms.send(toolInfo); // 开始调用工具
59
+ const done = () => {
60
+ if (timer) { clearTimeout(timer); timer = null; }
61
+ delete globalThis[toolInfo.id];
62
+ };
63
+
64
+ // 先建好 Promise 再推事件,避免页面同步回传时 _resolve 还不存在
65
+ const waiting = new Promise((resolve, reject) => {
66
+ settle = { resolve, reject };
67
+ });
51
68
 
52
- return new Promise((resolve, reject) => {
53
- _resolve = resolve;
54
- });
69
+ globalThis[toolInfo.id] = function (result, status) {
70
+ if (!settle) return;
71
+ const current = settle;
72
+ settle = null;
73
+ done();
74
+ if (status === "error") current.reject(result);
75
+ else current.resolve(result);
76
+ };
77
+
78
+ if (timeout > 0) {
79
+ timer = setTimeout(() => {
80
+ if (!settle) return;
81
+ const current = settle;
82
+ settle = null;
83
+ done();
84
+ current.reject(new Error("前端工具调用超时:" + description.function.name));
85
+ }, timeout);
55
86
  }
87
+
88
+ try {
89
+ _this.ms.send(toolInfo); // 开始调用工具
90
+ } catch (error) {
91
+ settle = null;
92
+ done();
93
+ throw error;
94
+ }
95
+
96
+ return waiting;
56
97
  }
57
98
  };
58
99
  };
59
100
 
60
- export default CreateTool;
101
+ export default CreateTool;
package/src/index.js CHANGED
@@ -3,19 +3,39 @@ import runConversation from "./runConversation.js";
3
3
  import CreateTool from "./createTool.js";
4
4
 
5
5
  function Agent(option) {
6
+ option = option || {};
7
+
8
+ // #doc:ctor
6
9
  this.model = new Model(option.model);
7
10
  this.tools = option.tools || [];
8
11
  this.systemPrompt = option.systemPrompt || "";
9
12
  this.stream = option.stream || false;
13
+
14
+ // 工具调用循环上限,0 表示不限制
15
+ this.maxSteps = option.maxSteps > 0 ? option.maxSteps : 0;
16
+
17
+ // 取消信号,透传给每次模型请求
18
+ this.signal = option.signal || null;
19
+ // #end
10
20
  }
11
21
 
12
22
  Agent.prototype.generate = function (messages, logback, thinkback) {
13
- if (this.systemPrompt) messages.unshift({
14
- role: "system",
15
- content: this.systemPrompt
16
- });
23
+ if (!Array.isArray(messages)) messages = [];
24
+
25
+ // 注入 system 提示词;首条已是同内容时跳过,避免复用同一数组时累积(原地修改,保持契约)
26
+ // #doc:system
27
+ if (this.systemPrompt) {
28
+ let first = messages[0];
29
+ if (!first || first.role !== "system" || first.content !== this.systemPrompt) {
30
+ messages.unshift({
31
+ role: "system",
32
+ content: this.systemPrompt
33
+ });
34
+ }
35
+ }
36
+ // #end
17
37
 
18
38
  return runConversation(this, messages, logback, thinkback);
19
39
  };
20
40
 
21
- export { Agent, CreateTool };
41
+ export { Agent, CreateTool };
@@ -34,11 +34,17 @@ function appendAssistantMessage(messages, result) {
34
34
  */
35
35
  export default async function runConversation(_this, messages, logback, thinkback) {
36
36
 
37
- while (true) {
37
+ // maxSteps 为 0 表示不限制
38
+ // #doc:loop
39
+ const maxSteps = _this.maxSteps > 0 ? _this.maxSteps : Infinity;
40
+
41
+ for (let step = 1; step <= maxSteps; step++) {
42
+
38
43
  const result = await _this.model.completions({
39
44
  messages,
40
45
  tools: _this.tools,
41
46
  stream: _this.stream,
47
+ signal: _this.signal || void 0,
42
48
  }, logback, thinkback);
43
49
 
44
50
  const hasToolCalls = appendAssistantMessage(messages, result);
@@ -52,5 +58,8 @@ export default async function runConversation(_this, messages, logback, thinkbac
52
58
  result.tool_calls.forEach((call, i) => {
53
59
  messages.push(toToolMessage(call, toolResults[i]));
54
60
  });
61
+ // #end
55
62
  }
56
- }
63
+
64
+ throw new Error("工具调用步骤超过 maxSteps 上限:" + _this.maxSteps);
65
+ }
package/types/agent.d.ts CHANGED
@@ -20,6 +20,13 @@ export interface AgentOptions {
20
20
  tools?: AgentTool[];
21
21
  /** 是否开启流式输出,默认 false */
22
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;
23
30
  }
24
31
 
25
32
  export declare class Agent {
@@ -30,6 +37,10 @@ export declare class Agent {
30
37
  tools: AgentTool[];
31
38
  systemPrompt: string;
32
39
  stream: boolean;
40
+ /** 工具调用循环上限,0 表示不限制 */
41
+ maxSteps: number;
42
+ /** 取消信号,未设置时为 null */
43
+ signal: AbortSignal | null;
33
44
 
34
45
  /**
35
46
  * 执行对话循环:模型请求 → 工具调用 → 结果回传 → 继续请求,直至拿到最终文本。
@@ -23,6 +23,12 @@ export interface CreateToolInput {
23
23
  execute?: ToolExecutor;
24
24
  }
25
25
 
26
+ /** ct.create 的可选配置 */
27
+ export interface CreateToolOptions {
28
+ /** 前端工具等待页面回传的超时毫秒数,0 / 缺省表示不限制;超时以 error reject */
29
+ timeout?: number;
30
+ }
31
+
26
32
  export declare class CreateTool {
27
33
  constructor(ms: MessageSender);
28
34
 
@@ -31,8 +37,8 @@ export declare class CreateTool {
31
37
 
32
38
  /**
33
39
  * 包装一个工具为标准 AgentTool:
34
- * - 有 execute:执行前后通过消息流推送 pending / success / error;
35
- * - 无 execute:只推送 pending,随后挂起,等待 globalThis[id](result) 唤醒。
40
+ * - 有 execute:执行前后通过消息流推送 pending / success / error;失败时抛错由 callFuns 转成文本;
41
+ * - 无 execute:只推送 pending,随后挂起,等待 globalThis[id](result, status?) 唤醒。
36
42
  */
37
- create(input: CreateToolInput): AgentTool;
43
+ create(input: CreateToolInput, options?: CreateToolOptions): AgentTool;
38
44
  }