my-ai-chat-framework 2.7.0 → 3.0.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.
@@ -2,212 +2,242 @@
2
2
  * 工具调用插件
3
3
  * 功能:拦截助手消息中的 tool_calls,执行对应的工具,将结果作为 tool 消息加入对话,
4
4
  * 然后自动继续对话(通过 sendExisting / sendExistingStream),直到没有新的工具调用。
5
- *
5
+ *
6
6
  * 设计要点:
7
7
  * - 支持普通请求和流式请求(通过 isStream 标志区分)
8
8
  * - 支持多次工具调用循环(maxIterations 防止无限循环)
9
- * - 串行执行工具(可后续升级为并行)
9
+ * - 并行执行工具
10
10
  * - 工具执行失败时,仍然返回错误信息给 AI,而不是中断整个流程
11
11
  * - 触发 tool-error 事件,方便用户监听工具执行异常
12
+ *
13
+ * 注意:请使用 createToolCallingPlugin() 工厂创建实例。
14
+ * 默认导出的 toolCallingPlugin 是兼容用的模块级单例,装到多个 ChatService
15
+ * 实例会互相覆盖(executor 表、工具定义、配置),新代码不要直接用单例。
12
16
  */
13
- export const toolCallingPlugin = {
14
- name: 'tool-calling',
15
- maxIterations: 5, // 最大工具调用循环次数,防止无限循环(例如 AI 反复请求同一工具)
16
-
17
- /**
18
- * 安装插件,覆盖 ChatService 的 registerTool、send、stream 方法
19
- * @param {ChatService} chatService - ChatService 实例
20
- */
21
- install(chatService) {
22
- this.chatService = chatService;
23
- this._tools = new Map(); // 存储工具名 -> { executor, description }
24
-
25
- // 初始化 config.tools 数组(用于存放 OpenAI 格式的工具定义)
26
- if (!chatService.config.tools) {
27
- chatService.config.tools = [];
28
- }
17
+ export const toolCallingPlugin = createToolCallingPlugin();
18
+
19
+ /**
20
+ * 创建工具调用插件实例(工厂)。
21
+ * @param {Object} [options] — { timeout, maxIterations }
22
+ */
23
+ export function createToolCallingPlugin(options = {}) {
24
+ return {
25
+ name: 'tool-calling',
26
+ maxIterations: options.maxIterations || 5, // 最大工具调用循环次数,防止无限循环
27
+ _options: { ...options },
28
+ _tools: new Map(), // 工具名 -> { executor, description }
29
+ _toolDefs: [], // OpenAI 格式的工具定义(按注册顺序)
30
+ chatService: null,
29
31
 
30
32
  /**
31
- * 注册工具
32
- * @param {string} name - 工具名称(唯一标识)
33
- * @param {string} description - 工具描述(告诉 AI 何时调用)
34
- * @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
35
- * @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
36
- * @returns {ChatService} 返回 chatService 实例,支持链式调用
33
+ * 安装插件:挂 registerTool、注册 beforeRequest 钩子注入工具定义、注册响应处理钩子
34
+ * @param {ChatService} chatService - ChatService 实例
35
+ * @param {Object} [options] - 安装时配置(合并进 _options)
37
36
  */
38
- chatService.registerTool = (name, description, executor, parameters = {}) => {
39
- // 保存执行器
40
- this._tools.set(name, { executor, description });
41
-
42
- // 构建 OpenAI 兼容的工具定义
43
- const toolDefinition = {
44
- type: 'function',
45
- function: {
46
- name,
47
- description,
48
- parameters: {
49
- type: 'object',
50
- properties: parameters,
51
- required: Object.keys(parameters).filter(key => parameters[key]?.required)
37
+ install(chatService, options = {}) {
38
+ this._options = { ...this._options, ...options };
39
+ this.chatService = chatService;
40
+
41
+ // 每次请求前把工具定义注入到请求配置(v3.0:beforeSend 车间,不再用 _hooks 钩子)
42
+ chatService.pipe({
43
+ name: 'tool-calling-inject',
44
+ phase: 'beforeSend',
45
+ run: ({ config }) => {
46
+ if (this._toolDefs.length) config.tools = this._toolDefs;
47
+ }
48
+ });
49
+
50
+ /**
51
+ * 注册工具
52
+ * @param {string} name - 工具名称(唯一标识)
53
+ * @param {string} description - 工具描述(告诉 AI 何时调用)
54
+ * @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
55
+ * @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
56
+ * @returns {ChatService} 返回 chatService 实例,支持链式调用
57
+ */
58
+ chatService.registerTool = (name, description, executor, parameters = {}) => {
59
+ // 保存执行器
60
+ this._tools.set(name, { executor, description });
61
+
62
+ // 构建 OpenAI 兼容的工具定义
63
+ const toolDefinition = {
64
+ type: 'function',
65
+ function: {
66
+ name,
67
+ description,
68
+ parameters: {
69
+ type: 'object',
70
+ properties: parameters,
71
+ required: Object.keys(parameters).filter(key => parameters[key]?.required)
72
+ }
52
73
  }
74
+ };
75
+ // 避免重复添加相同工具
76
+ const existing = this._toolDefs.find(t => t.function.name === name);
77
+ if (!existing) {
78
+ this._toolDefs.push(toolDefinition);
53
79
  }
80
+ return chatService;
54
81
  };
55
- // 避免重复添加相同工具
56
- const existing = chatService.config.tools.find(t => t.function.name === name);
57
- if (!existing) {
58
- chatService.config.tools.push(toolDefinition);
59
- }
60
- return chatService;
61
- };
62
-
63
- // 注册响应后处理钩子,不再覆盖 send/stream
64
- chatService._processResponse = async (response, { isStream, onProgress, onDone }) => {
65
- return this._handleWithTools(response, isStream, onProgress, onDone);
66
- };
67
- },
68
-
69
- /**
70
- * 核心处理逻辑:检查响应 → 执行工具 → 继续请求 → 循环
71
- * @param {Object} initialResponse - 初始 AI 响应
72
- * @param {boolean} isStream - 是否流式
73
- * @param {Function} onProgress - 流式进度回调
74
- * @param {Function} onDone - 流式完成回调
75
- * @returns {Promise<Object>} 最终 AI 响应
76
- */
77
- async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
78
- const self = this;
79
- const chat = this.chatService;
80
- let iteration = 0;
82
+
83
+ // 响应后处理(v3.0:afterSend 车间,不再占用 ChatService._processResponse 单座槽位)
84
+ chatService.pipe({
85
+ name: 'tool-calling-loop',
86
+ phase: 'afterSend',
87
+ run: async (ctx) => {
88
+ ctx.result = await this._handleWithTools(
89
+ ctx.result,
90
+ ctx.isStream,
91
+ ctx.onProgress || undefined,
92
+ ctx.onDone || undefined
93
+ );
94
+ }
95
+ });
96
+ },
81
97
 
82
98
  /**
83
- * 递归处理工具调用
84
- * @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
85
- * @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
99
+ * 核心处理逻辑:检查响应 → 执行工具 → 继续请求 → 循环
100
+ * @param {Object} initialResponse - 初始 AI 响应
101
+ * @param {boolean} isStream - 是否流式
102
+ * @param {Function} onProgress - 流式进度回调
103
+ * @param {Function} onDone - 流式完成回调
104
+ * @returns {Promise<Object>} 最终 AI 响应
86
105
  */
87
- async function processResponse(initialResponse) {
88
- let lastResponse = initialResponse;
89
- while (iteration < self.maxIterations) {
90
- // 检查 AI 返回的消息中是否包含工具调用请求
91
- const toolCalls = lastResponse?.toolCalls;
92
- if (!toolCalls || toolCalls.length === 0) break;
93
-
94
- iteration++;
95
- // 并行执行所有工具调用(彼此独立,不会因一个失败而阻塞其他)
96
- const toolResults = await Promise.all(
97
- toolCalls.map(async (call) => {
98
- const toolName = call.function?.name;
99
-
100
- // 解析参数(JSON.parse 可能失败,需单独 try/catch)
101
- let args;
102
- try {
103
- args = JSON.parse(call.function?.arguments || '{}');
104
- } catch (parseErr) {
105
- chat.emit('tool-error', {
106
- toolName: toolName || 'unknown',
107
- error: parseErr,
108
- toolCallId: call.id,
109
- stage: 'parse',
110
- timestamp: Date.now()
111
- });
112
- return {
113
- tool_call_id: call.id,
114
- error: `参数解析失败: ${parseErr.message}`,
115
- success: false
116
- };
117
- }
106
+ async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
107
+ const self = this;
108
+ const chat = this.chatService;
109
+ let iteration = 0;
118
110
 
119
- const tool = self._tools.get(toolName);
120
- if (!tool) {
121
- chat.emit('tool-error', {
122
- toolName,
123
- error: new Error(`Tool not registered: ${toolName}`),
124
- toolCallId: call.id,
125
- stage: 'lookup',
126
- timestamp: Date.now()
127
- });
128
- return {
129
- tool_call_id: call.id,
130
- error: `工具 ${toolName} 未注册`,
131
- success: false
132
- };
133
- }
111
+ /**
112
+ * 递归处理工具调用
113
+ * @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
114
+ * @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
115
+ */
116
+ async function processResponse(initialResponse) {
117
+ let lastResponse = initialResponse;
118
+ while (iteration < self.maxIterations) {
119
+ // 检查 AI 返回的消息中是否包含工具调用请求
120
+ const toolCalls = lastResponse?.toolCalls;
121
+ if (!toolCalls || toolCalls.length === 0) break;
122
+
123
+ iteration++;
124
+ // 并行执行所有工具调用(彼此独立,不会因一个失败而阻塞其他)
125
+ const toolResults = await Promise.all(
126
+ toolCalls.map(async (call) => {
127
+ const toolName = call.function?.name;
134
128
 
135
- try {
136
- // 工具执行超时控制
137
- const toolTimeout = chat.config.toolTimeout;
138
- let execPromise = tool.executor(args);
139
- if (toolTimeout && typeof toolTimeout === 'number' && toolTimeout > 0) {
140
- const timeoutErr = new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
141
- timeoutErr.name = 'ToolTimeoutError';
142
- const timeoutPromise = new Promise((_, reject) =>
143
- setTimeout(() => reject(timeoutErr), toolTimeout)
144
- );
145
- execPromise = Promise.race([execPromise, timeoutPromise]);
129
+ // 解析参数(JSON.parse 可能失败,需单独 try/catch)
130
+ let args;
131
+ try {
132
+ args = JSON.parse(call.function?.arguments || '{}');
133
+ } catch (parseErr) {
134
+ chat.emit('tool-error', {
135
+ toolName: toolName || 'unknown',
136
+ error: parseErr,
137
+ toolCallId: call.id,
138
+ stage: 'parse',
139
+ timestamp: Date.now()
140
+ });
141
+ return {
142
+ tool_call_id: call.id,
143
+ error: `参数解析失败: ${parseErr.message}`,
144
+ success: false
145
+ };
146
146
  }
147
147
 
148
- const result = await execPromise;
149
- chat.emit('tool-success', {
150
- toolName,
151
- result,
152
- toolCallId: call.id,
153
- timestamp: Date.now()
154
- });
155
- return {
156
- tool_call_id: call.id,
157
- content: typeof result === 'string' ? result : JSON.stringify(result),
158
- success: true
159
- };
160
- } catch (err) {
161
- const stage = err.name === 'ToolTimeoutError' ? 'timeout' : 'execute';
162
- chat.emit('tool-error', {
163
- toolName,
164
- error: err,
165
- toolCallId: call.id,
166
- stage,
167
- timestamp: Date.now()
168
- });
169
- return {
170
- tool_call_id: call.id,
171
- error: err.message,
172
- success: false
173
- };
174
- }
175
- })
176
- );
177
-
178
- // 将工具执行结果作为 tool 消息添加到对话历史
179
- for (const tr of toolResults) {
180
- // 注意:addTool 的第二个参数是 tool_call_id
181
- // 如果工具执行失败且没有内容,则传递错误信息作为 content
182
- const content = tr.success ? tr.content : (tr.error || '工具执行失败');
183
- chat.messages.addTool(content, tr.tool_call_id);
184
- }
148
+ const tool = self._tools.get(toolName);
149
+ if (!tool) {
150
+ chat.emit('tool-error', {
151
+ toolName,
152
+ error: new Error(`Tool not registered: ${toolName}`),
153
+ toolCallId: call.id,
154
+ stage: 'lookup',
155
+ timestamp: Date.now()
156
+ });
157
+ return {
158
+ tool_call_id: call.id,
159
+ error: `工具 ${toolName} 未注册`,
160
+ success: false
161
+ };
162
+ }
163
+
164
+ try {
165
+ // 工具执行超时控制(工厂 options.timeout 优先,兼容旧 config.toolTimeout)
166
+ const toolTimeout = self._options.timeout ?? chat.config.toolTimeout;
167
+ let execPromise = tool.executor(args);
168
+ if (toolTimeout && typeof toolTimeout === 'number' && toolTimeout > 0) {
169
+ const timeoutErr = new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
170
+ timeoutErr.name = 'ToolTimeoutError';
171
+ const timeoutPromise = new Promise((_, reject) =>
172
+ setTimeout(() => reject(timeoutErr), toolTimeout)
173
+ );
174
+ execPromise = Promise.race([execPromise, timeoutPromise]);
175
+ }
185
176
 
186
- // 再次请求 AI,获取基于工具结果的回复
187
- if (isStream) {
188
- // 流式继续:使用 sendExistingStream
189
- await new Promise((resolve) => {
190
- chat.sendExistingStream(
191
- (chunk) => {
192
- if (onProgress) onProgress(chunk);
193
- lastResponse = chunk;
194
- },
195
- (final) => {
196
- lastResponse = final;
197
- resolve();
177
+ const result = await execPromise;
178
+ chat.emit('tool-success', {
179
+ toolName,
180
+ result,
181
+ toolCallId: call.id,
182
+ timestamp: Date.now()
183
+ });
184
+ return {
185
+ tool_call_id: call.id,
186
+ content: typeof result === 'string' ? result : JSON.stringify(result),
187
+ success: true
188
+ };
189
+ } catch (err) {
190
+ const stage = err.name === 'ToolTimeoutError' ? 'timeout' : 'execute';
191
+ chat.emit('tool-error', {
192
+ toolName,
193
+ error: err,
194
+ toolCallId: call.id,
195
+ stage,
196
+ timestamp: Date.now()
197
+ });
198
+ return {
199
+ tool_call_id: call.id,
200
+ error: err.message,
201
+ success: false
202
+ };
198
203
  }
199
- );
200
- });
201
- } else {
202
- // 非流式继续:使用 sendExisting
203
- lastResponse = await chat.sendExisting();
204
+ })
205
+ );
206
+
207
+ // 将工具执行结果作为 tool 消息添加到对话历史
208
+ for (const tr of toolResults) {
209
+ // 注意:addTool 的第二个参数是 tool_call_id
210
+ // 如果工具执行失败且没有内容,则传递错误信息作为 content
211
+ const content = tr.success ? tr.content : (tr.error || '工具执行失败');
212
+ chat.messages.addTool(content, tr.tool_call_id);
213
+ }
214
+
215
+ // 再次请求 AI,获取基于工具结果的回复
216
+ if (isStream) {
217
+ // 流式继续:使用 sendExistingStream
218
+ await new Promise((resolve) => {
219
+ chat.sendExistingStream(
220
+ (chunk) => {
221
+ if (onProgress) onProgress(chunk);
222
+ lastResponse = chunk;
223
+ },
224
+ (final) => {
225
+ lastResponse = final;
226
+ resolve();
227
+ }
228
+ );
229
+ });
230
+ } else {
231
+ // 非流式继续:使用 sendExisting
232
+ lastResponse = await chat.sendExisting();
233
+ }
204
234
  }
235
+ return lastResponse;
205
236
  }
206
- return lastResponse;
207
- }
208
237
 
209
- // 初始响应已由 ChatService 发出,直接进入工具调用循环
210
- const final = await processResponse(initialResponse);
211
- return final;
212
- }
213
- };
238
+ // 初始响应已由 ChatService 发出,直接进入工具调用循环
239
+ const final = await processResponse(initialResponse);
240
+ return final;
241
+ }
242
+ };
243
+ }