← 博客教程
构建第一个能够调用工具的 AI Agent
分步教程:使用 MCP 工具构建能搜索网页、执行代码和发送邮件的 AI Agent。
·4 分钟阅读
本教程将带你构建可调用外部工具的 AI Agent,进行网页搜索、沙箱代码执行和邮件发送。我们将使用 4agent 目录中兼容 MCP 的工具。
准备条件
- Node.js 20+
- 你选择的 LLM 提供商的 API 密钥
- 基本的 TypeScript 使用经验
第一步:选择工具
每个 Agent 都需要适合任务的工具。示例中的研究助手要查找并总结信息,因此需要:
- 网页搜索:查找最新信息
- 代码执行:处理和分析数据
- 邮件:发送结果
E
E2B
让 AI Agent 执行代码的云沙箱
第二步:配置项目
mkdir my-agent && cd my-agent
npm init -y
npm install @anthropic-ai/sdk @e2b/code-interpreter创建支持 ESM 模块解析的 tsconfig.json,并以 src/index.ts 作为入口。
第三步:定义 Agent 循环
Agent 的核心是工具调用循环:
- 向 LLM 发送消息与可用工具
- LLM 决定是否调用工具以及调用哪个工具
- 执行工具并返回结果
- 重复以上步骤,直到 LLM 给出最终回答
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
async function runAgent(task: string) {
const messages: Anthropic.MessageParam[] = [
{ role: "user", content: task },
];
while (true) {
const response = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 4096,
tools: toolDefinitions,
messages,
});
// Check if the model wants to use a tool
if (response.stop_reason === "tool_use") {
const toolUse = response.content.find(
(c) => c.type === "tool_use"
);
const result = await executeTool(
toolUse.name,
toolUse.input
);
messages.push(
{ role: "assistant", content: response.content },
{ role: "user", content: [{ type: "tool_result", tool_use_id: toolUse.id, content: result }] },
);
} else {
// Final response
return response.content;
}
}
}第四步:实现工具执行
每个工具都需要处理函数,将 LLM 的请求转换为 API 调用:
async function executeTool(
name: string,
input: Record<string, unknown>
): Promise<string> {
switch (name) {
case "run_code":
return await runCodeInSandbox(input.code as string);
case "search_web":
return await searchWeb(input.query as string);
default:
return `Unknown tool: ${name}`;
}
}使用 E2B 执行代码
import { Sandbox } from "@e2b/code-interpreter";
async function runCodeInSandbox(code: string) {
const sandbox = await Sandbox.create();
const result = await sandbox.runCode(code);
await sandbox.kill();
return JSON.stringify(result);
}第五步:运行 Agent
const result = await runAgent(
"Find the top 5 trending AI tools this week and create a summary table."
);
console.log(result);现在 Agent 会搜索网页、在沙箱中处理结果,并返回结构化回答。
后续步骤
- 添加记忆,让 Agent 能跨对话保留上下文
- 为工具故障添加错误处理和重试
- 在 4agent 目录探索更多工具,扩展 Agent 能力
提示
将模型生成的工具参数视为不可信输入。调用外部服务前先验证,并避免在提示词、工具结果和日志中出现密钥等秘密。
参考来源
tutorialagentsmcpgetting-started