@auipage/agent 0.1.0 → 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",
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",
34
- "@auipage/types": "^0.1.0",
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
@@ -1,35 +1,44 @@
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
- };
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
+ // #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
16
+ );
17
+
18
+ if (!tool) {
19
+ return Promise.resolve("工具" + fn.name + "不存在");
20
+ }
21
+
22
+ if (typeof tool.execute !== "function") {
23
+ return Promise.resolve("工具" + fn.name + "缺少 execute");
24
+ }
25
+
26
+ let args;
27
+ try {
28
+ // 无参工具:arguments 为空字符串或缺失时按 {} 处理
29
+ args = typeof fn.arguments === "string" && fn.arguments.trim() ? JSON.parse(fn.arguments) : {};
30
+ } catch (e) {
31
+ return Promise.resolve("参数解析失败:" + e);
32
+ }
33
+
34
+ try {
35
+ // 工具内部报错(含同步抛错)也不要阻断对话,转成字符串继续往下走
36
+ return Promise.resolve(tool.execute(args)).catch(e => "运行出错:" + e);
37
+ } catch (e) {
38
+ return Promise.resolve("运行出错:" + e);
39
+ // #end
40
+ }
41
+ });
42
+
43
+ return Promise.all(tasks);
44
+ };
package/src/createTool.js CHANGED
@@ -1,60 +1,101 @@
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;
1
+ import { initOption } from "oipage/web/option/index.js";
2
+
3
+ function CreateTool(ms) {
4
+ this.ms = ms;
5
+ }
6
+
7
+ /**
8
+ * 包装一个工具。
9
+ *
10
+ * @param {object} input description + 可选 execute(缺省即前端工具)
11
+ * @param {object} [options] { timeout } 前端工具等待页面回传的超时毫秒数,0 表示不限制
12
+ */
13
+ CreateTool.prototype.create = function ({ description, execute }, options) {
14
+ let _this = this;
15
+ const timeout = options && options.timeout > 0 ? options.timeout : 0;
16
+
17
+ return {
18
+ description,
19
+ execute: async function (args) {
20
+ let toolInfo = {
21
+ type: "tool-call",
22
+ status: "pending",
23
+ id: Date.now().toString() + "_" + Math.random().toString(36).substring(2).toUpperCase(),
24
+ name: description.function.name,
25
+ caller: execute ? "backend" : "frontend",
26
+ args
27
+ };
28
+
29
+ // 后端工具调用
30
+ // #doc:backend
31
+ if (execute) {
32
+ _this.ms.send(toolInfo); // 开始调用工具
33
+
34
+ let result, status;
35
+ try {
36
+ result = await execute(args);
37
+ status = "success"; // 调用成功
38
+ } catch (error) {
39
+ result = error;
40
+ status = "error"; // 调用失败
41
+ }
42
+
43
+ _this.ms.send(initOption({ // 结束调用工具
44
+ status,
45
+ result
46
+ }, toolInfo));
47
+
48
+ // 失败继续抛出,由 callFuns 统一转成给模型的错误文本
49
+ if (status === "error") throw result;
50
+
51
+ return result;
52
+ // #end
53
+ }
54
+
55
+ // 前端工具调用
56
+ let settle = null;
57
+ let timer = null;
58
+
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
+ });
68
+
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);
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;
97
+ }
98
+ };
99
+ };
100
+
101
+ export default CreateTool;
package/src/index.js CHANGED
@@ -1,21 +1,41 @@
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 };
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
+ option = option || {};
7
+
8
+ // #doc:ctor
9
+ this.model = new Model(option.model);
10
+ this.tools = option.tools || [];
11
+ this.systemPrompt = option.systemPrompt || "";
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
20
+ }
21
+
22
+ Agent.prototype.generate = function (messages, logback, thinkback) {
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
37
+
38
+ return runConversation(this, messages, logback, thinkback);
39
+ };
40
+
41
+ export { Agent, CreateTool };
@@ -1,56 +1,65 @@
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
- }
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
+ // maxSteps 为 0 表示不限制
38
+ // #doc:loop
39
+ const maxSteps = _this.maxSteps > 0 ? _this.maxSteps : Infinity;
40
+
41
+ for (let step = 1; step <= maxSteps; step++) {
42
+
43
+ const result = await _this.model.completions({
44
+ messages,
45
+ tools: _this.tools,
46
+ stream: _this.stream,
47
+ signal: _this.signal || void 0,
48
+ }, logback, thinkback);
49
+
50
+ const hasToolCalls = appendAssistantMessage(messages, result);
51
+
52
+ if (!hasToolCalls) {
53
+ return result.content;
54
+ }
55
+
56
+ const toolResults = await callFuns(_this, result.tool_calls);
57
+
58
+ result.tool_calls.forEach((call, i) => {
59
+ messages.push(toToolMessage(call, toolResults[i]));
60
+ });
61
+ // #end
62
+ }
63
+
64
+ throw new Error("工具调用步骤超过 maxSteps 上限:" + _this.maxSteps);
65
+ }
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
- export declare class Agent {
26
- constructor(options: AgentOptions);
27
-
28
- /** 底层模型实例 */
29
- model: Model;
30
- tools: AgentTool[];
31
- systemPrompt: string;
32
- stream: boolean;
33
-
34
- /**
35
- * 执行对话循环:模型请求 → 工具调用 → 结果回传 → 继续请求,直至拿到最终文本。
36
- *
37
- * @param messages 本轮对话消息数组;配置了非空 systemPrompt 时会自动插到最前(原地修改)
38
- * @param logback 流式正文增量回调
39
- * @param thinkback 流式思维链增量回调
40
- * @returns 模型最终回复;只产出工具调用而无文本时可能为 undefined
41
- */
42
- generate(
43
- messages: ChatMessage[],
44
- logback?: Logback,
45
- thinkback?: Thinkback
46
- ): Promise<string | undefined>;
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
+ }
@@ -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
- export declare class CreateTool {
27
- constructor(ms: MessageSender);
28
-
29
- /** 构造时传入的消息流发送端 */
30
- ms: MessageSender;
31
-
32
- /**
33
- * 包装一个工具为标准 AgentTool:
34
- * - 有 execute:执行前后通过消息流推送 pending / success / error;
35
- * - 无 execute:只推送 pending,随后挂起,等待 globalThis[id](result) 唤醒。
36
- */
37
- create(input: CreateToolInput): AgentTool;
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
+ }