4.3 工具执行循环

核心逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
async function processTurn(userMessage: string): Promise<string> {
const messages = [{ role: 'user', content: userMessage }];

while (true) {
// 调用 LLM
const response = await llm.chatWithTools(messages, tools);

// 检查是否有工具调用
if (!response.toolCalls) {
return response.content; // 没有工具调用,返回结果
}

// 执行工具调用
for (const toolCall of response.toolCalls) {
const tool = tools.find(t => t.name === toolCall.name);
const result = await tool.execute(JSON.parse(toolCall.arguments));

// 将结果添加到消息历史
messages.push({
role: 'assistant',
content: '',
tool_calls: [toolCall]
});
messages.push({
role: 'tool',
tool_call_id: toolCall.id,
content: JSON.stringify(result)
});
}
}
}

导航

上一篇: 4.2 工具定义与注册

下一篇: 4.4 内置工具实现