async processQuery(query: string): Promise<string> {
if (!this.client) {
throw new Error("客户端未连接");
}
// 使用用户查询初始化消息数组
let messages: Anthropic.MessageParam[] = [
{
role: "user",
content: query,
},
];
// 获取可用工具
const toolsResponse = await this.client.request(
{ method: "tools/list" },
ListToolsResultSchema
);
const availableTools = toolsResponse.tools.map((tool: any) => ({
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema,
}));
const finalText: string[] = [];
let currentResponse = await this.anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1000,
messages,
tools: availableTools,
});
// 处理响应和任何工具调用
while (true) {
// 将 Claude 的响应添加到最终文本和消息中
for (const content of currentResponse.content) {
if (content.type === "text") {
finalText.push(content.text);
} else if (content.type === "tool_use") {
const toolName = content.name;
const toolArgs = content.input;
// 执行工具调用
const result = await this.client.request(
{
method: "tools/call",
params: {
name: toolName,
arguments: toolArgs,
},
},
CallToolResultSchema
);
finalText.push(
`[调用工具 ${toolName},参数为 ${JSON.stringify(toolArgs)}]`
);
// 将 Claude 的响应(包括工具使用)添加到消息中
messages.push({
role: "assistant",
content: currentResponse.content,
});
// 将工具结果添加到消息中
messages.push({
role: "user",
content: [
{
type: "tool_result",
tool_use_id: content.id,
content: [
{ type: "text", text: JSON.stringify(result.content) },
],
},
],
});
// 使用工具结果获取 Claude 的下一次响应
currentResponse = await this.anthropic.messages.create({
model: "claude-3-5-sonnet-20241022",
max_tokens: 1000,
messages,
tools: availableTools,
});
// 将 Claude 对工具结果的解释添加到最终文本
if (currentResponse.content[0]?.type === "text") {
finalText.push(currentResponse.content[0].text);
}
// 继续循环以处理任何额外的工具调用
continue;
}
}
// 如果到达这里,说明响应中没有工具调用
break;
}
return finalText.join("\n");
}