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.
- package/CHANGELOG.md +65 -0
- package/LICENSE +20 -20
- package/README.md +100 -13
- package/README_ZH.md +375 -0
- package/dist/my-ai-chat-framework.browser.es.js +758 -248
- package/dist/my-ai-chat-framework.browser.es.js.map +1 -1
- package/dist/my-ai-chat-framework.browser.umd.js +762 -247
- package/dist/my-ai-chat-framework.browser.umd.js.map +1 -1
- package/dist/my-ai-chat-framework.node.cjs.js +762 -247
- package/dist/my-ai-chat-framework.node.cjs.js.map +1 -1
- package/docs/DEVELOPER.md +479 -0
- package/package.json +31 -8
- package/src/adapters/openai.js +82 -7
- package/src/core/ChatService.js +415 -61
- package/src/core/Errors.js +59 -59
- package/src/core/MessageStore.js +27 -0
- package/src/core/Pipeline.js +48 -0
- package/src/core/SystemPromptStore.js +118 -118
- package/src/index.js +6 -4
- package/src/plugins/model-registry.js +223 -187
- package/src/plugins/tool-calling.js +215 -185
- package/src/utils/MessageFormatter.js +204 -204
- package/src/utils/typeCheck.js +11 -11
- package/src/utils/url.js +17 -17
|
@@ -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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
//
|
|
26
|
-
|
|
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 {
|
|
33
|
-
* @param {
|
|
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
|
|
39
|
-
|
|
40
|
-
this.
|
|
41
|
-
|
|
42
|
-
//
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
* @
|
|
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
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
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
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
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
|
-
|
|
202
|
-
//
|
|
203
|
-
|
|
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
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
};
|
|
238
|
+
// 初始响应已由 ChatService 发出,直接进入工具调用循环
|
|
239
|
+
const final = await processResponse(initialResponse);
|
|
240
|
+
return final;
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
}
|