AI Agent SDK 入门指南

本文将带你了解什么是 Agent SDK,并详细介绍如何使用 @anthropic-ai/claude-agent-sdk 构建你的第一个 AI 智能代理。
什么是 AI Agent?
在深入 Agent SDK 之前,我们先来理解一下什么是 AI Agent(AI 智能代理)。
Agent 的定义
简单来说,AI Agent 是一个能够自主决策和执行任务的 AI 系统。与传统的聊天机器人不同,Agent 不仅能回答问题,还能:
•🤔 自主规划:根据目标分解任务步骤•🔧 使用工具:调用外部 API、执行代码、访问数据库等•🔄 迭代优化:根据执行结果调整策略•💡 做出决策:在多个选项中选择最佳方案
Workflows vs Agents
Anthropic 将 AI 系统分为两类:
|
类型 |
定义 |
特点 |
适用场景 |
| Workflows |
通过预定义代码路径编排 LLM 和工具 |
可预测、一致性高 |
固定流程的任务 |
| Agents |
LLM 动态控制流程和工具使用 |
灵活、自适应 |
开放性问题 |
Agent 的工作流程
用户输入 → Agent 理解任务 → 制定计划 → 使用工具执行 → 获取反馈 → 调整策略 → 完成任务 ↑_______________________________________________________________| (循环迭代)
什么是 Agent SDK?
Agent SDK 是帮助开发者快速构建 AI Agent 的开发工具包。它封装了与 AI 模型交互、工具调用、状态管理等复杂逻辑,让你专注于业务逻辑的实现。
为什么需要 Agent SDK?
构建一个可靠的 Agent 需要处理很多复杂问题:
•❌ 手动管理对话上下文•❌ 解析和执行工具调用•❌ 处理错误和重试逻辑•❌ 追踪成本和使用量
Agent SDK 帮你解决这些问题,提供:
•✅ 简洁的 API 接口•✅ 自动的工具调用处理•✅ 内置的错误恢复机制•✅ 完善的成本追踪
@anthropic-ai/claude-agent-sdk 简介
Claude Agent SDK 是 Anthropic 官方推出的 Agent 开发工具包,它将 Claude Code(Anthropic 的 AI 编程助手)作为运行时,让你能够以编程方式构建强大的 AI Agent。
核心特性
1、 基于 Claude Code 运行时
•利用 Claude 强大的推理能力•内置工具调用支持•可靠的错误处理
2、 简洁的 API 设计
•单函数调用即可启动 Agent•TypeScript 类型支持•清晰的文档
3、 灵活的工具系统
•自定义工具定义•并行工具调用•工具执行追踪
快速开始:Hello World
让我们从最简单的示例开始,构建你的第一个 Agent。
前置准备
1、 安装 Claude Code CLI
# 安装 Claude Codenpm install -g claude-code
2、 获取 Anthropic API Key
访问 Anthropic Console[1] 注册并获取 API Key。
3、 设置环境变量
export ANTHROPIC_API_KEY="your-api-key-here"
安装 SDK
创建一个新项目并安装 SDK:
mkdir my-first-agentcd my-first-agentnpm init -ynpm install @anthropic-ai/claude-agent-sdk
Hello World 示例
创建 index.js 文件:
import { query } from "@anthropic-ai/claude-agent-sdk";
async function main() { // 最简单的 Agent 调用 const result = await query({ prompt: "你好!请介绍一下你自己。" });
console.log("Agent 回复:", result);}
main();
运行:
node index.js
核心 API:query 函数
query 是 Claude Agent SDK 的核心函数,它的基本语法如下:
import { query } from "@anthropic-ai/claude-agent-sdk";
const result = await query({ prompt: string, // 必需:用户的提示词 model?: string, // 可选:模型名称,默认使用最新的 Claude 模型 tools?: Tool[], // 可选:Agent 可以使用的工具列表 maxTokens?: number, // 可选:最大输出 token 数 temperature?: number, // 可选:温度参数 (0-1) systemPrompt?: string, // 可选:系统提示词});
给 Agent 添加工具
Agent 的真正威力在于它能使用工具。让我们创建一个能查询天气的 Agent。
定义工具
import { query } from "@anthropic-ai/claude-agent-sdk";
// 模拟的天气 APIfunction getWeather(location) { const weatherData = { "北京": { temp: 15, condition: "晴朗" }, "上海": { temp: 20, condition: "多云" }, "深圳": { temp: 25, condition: "小雨" }, };
return weatherData[location] || { temp: 18, condition: "未知" };}
// 定义工具const weatherTool = { name: "get_weather", description: "获取指定城市的当前天气信息", input_schema: { type: "object", properties: { location: { type: "string", description: "城市名称,例如:北京、上海、深圳" } }, required: ["location"] }, // 工具执行函数 execute: async ({ location }) => { const weather = getWeather(location); return `${location}的天气:温度 ${weather.temp}°C,${weather.condition}`; }};
async function weatherAgent() { const result = await query({ prompt: "北京今天天气怎么样?", tools: [weatherTool] // 传入工具 });
console.log(result);}
weatherAgent();
工具定义最佳实践
在定义工具时,请注意以下几点:
1、 清晰的工具名称
// ✅ 好的命名 name: "get_weather"
// ❌ 不好的命名 name: "tool1"
2、 详细的描述
// ✅ 好的描述 description: "获取指定城市的当前天气信息,包括温度和天气状况"
// ❌ 不好的描述 description: "天气"
3、 完整的参数说明
input_schema: { type: "object", properties: { location: { type: "string", description: "城市名称,例如:北京、上海、深圳", // 提供示例 example: "北京" } }, required: ["location"] // 明确必需参数 }
实战案例:构建一个研究助手
让我们构建一个更复杂的示例:一个能够搜索网络并生成研究报告的 Agent。
import { query } from "@anthropic-ai/claude-agent-sdk";import axios from "axios";
// 工具 1: 网络搜索const searchTool = { name: "web_search", description: "在互联网上搜索信息", input_schema: { type: "object", properties: { query: { type: "string", description: "搜索关键词" } }, required: ["query"] }, execute: async ({ query }) => { // 这里使用真实的搜索 API,例如 Google Custom Search // 为了演示,我们返回模拟数据 return `搜索 "${query}" 的结果:\n1. 相关文章A\n2. 相关文章B\n3. 相关文章C`; }};
// 工具 2: 保存报告const saveReportTool = { name: "save_report", description: "将研究报告保存到文件", input_schema: { type: "object", properties: { filename: { type: "string", description: "文件名" }, content: { type: "string", description: "报告内容" } }, required: ["filename", "content"] }, execute: async ({ filename, content }) => { const fs = require('fs').promises; await fs.writeFile(filename, content); return `报告已保存到 ${filename}`; }};
async function researchAgent(topic) { const result = await query({ prompt: `请研究"${topic}"这个主题,搜索相关信息并生成一份简短的研究报告,然后保存为 report.md 文件。`, tools: [searchTool, saveReportTool], systemPrompt: "你是一个专业的研究助手,擅长收集信息并生成结构化的报告。" });
console.log("研究完成:", result);}
// 执行研究任务researchAgent("人工智能 Agent 的发展趋势");
常见的 Agent 模式
Anthropic 总结了几种常见的 Agent 架构模式:
1. Prompt Chaining (提示词链)
将任务分解为多个步骤,每一步的输出作为下一步的输入。
// 步骤 1: 生成大纲const outline = await query({ prompt: "为一篇关于 AI Agent 的文章生成大纲"});
// 步骤 2: 基于大纲写文章const article = await query({ prompt: `基于以下大纲写一篇文章:\n${outline}`});
2. Routing (路由)
根据输入类型将任务路由到不同的处理流程。
async function routingAgent(userInput) { // 首先分类用户意图 const intent = await query({ prompt: `分类以下用户请求的类型(技术问题/产品咨询/投诉):${userInput}`, });
// 根据意图路由到不同的专门 Agent if (intent.includes("技术问题")) { return technicalSupportAgent(userInput); } else if (intent.includes("产品咨询")) { return productConsultantAgent(userInput); } else { return complaintHandlerAgent(userInput); }}
3. Parallelization (并行化)
同时执行多个独立的子任务。
async function parallelAgent(topic) { // 并行执行多个研究任务 const [news, academic, social] = await Promise.all([ query({ prompt: `搜索${topic}的最新新闻` }), query({ prompt: `搜索${topic}的学术论文` }), query({ prompt: `分析社交媒体对${topic}的讨论` }) ]);
// 综合结果 return query({ prompt: `综合以下信息生成报告:\n新闻:${news}\n学术:${academic}\n社交:${social}` });}
成本追踪和优化
使用 Agent 时需要注意成本控制。Claude Agent SDK 提供了内置的成本追踪功能。
const result = await query({ prompt: "分析这个代码库的架构", // 追踪使用量 onUsage: (usage) => { console.log("Token 使用量:", { 输入: usage.input_tokens, 输出: usage.output_tokens, 总计: usage.input_tokens + usage.output_tokens }); }});
成本优化建议
1、 使用合适的模型
•简单任务使用 Haiku(便宜快速)•复杂任务使用 Sonnet(平衡性价比)
2、 限制输出长度
const result = await query({ prompt: "简要总结这篇文章", maxTokens: 500 // 限制输出长度 });
3、 缓存系统提示词
•重复使用的系统提示词会被缓存,降低成本
最佳实践
1. 工具设计原则
•单一职责:每个工具只做一件事•清晰文档:提供详细的描述和示例•错误处理:工具执行失败时返回明确的错误信息
const goodTool = { name: "calculate_sum", description: "计算两个数字的和。示例:calculate_sum(5, 3) 返回 8", input_schema: { type: "object", properties: { a: { type: "number", description: "第一个数字" }, b: { type: "number", description: "第二个数字" } }, required: ["a", "b"] }, execute: async ({ a, b }) => { try { if (typeof a !== 'number' || typeof b !== 'number') { return { error: "参数必须是数字" }; } return { result: a + b }; } catch (error) { return { error: error.message }; } }};
2. 系统提示词优化
const result = await query({ prompt: "帮我写一个产品介绍", systemPrompt: `你是一位专业的营销文案撰写专家。规则:- 使用简洁有力的语言- 突出产品的核心优势- 包含情感化的描述- 字数控制在 200 字以内`});
3. 错误处理
async function robustAgent(prompt) { try { const result = await query({ prompt, timeout: 30000, // 30 秒超时 }); return result; } catch (error) { if (error.type === 'timeout') { // 超时重试 return robustAgent(prompt); } else if (error.type === 'rate_limit') { // 等待后重试 await new Promise(r => setTimeout(r, 5000)); return robustAgent(prompt); } else { console.error("Agent 执行失败:", error); throw error; } }}
实用示例集合
示例 1: 代码审查 Agent
const codeReviewTools = [{ name: "read_file", description: "读取代码文件", input_schema: { type: "object", properties: { path: { type: "string", description: "文件路径" } }, required: ["path"] }, execute: async ({ path }) => { const fs = require('fs').promises; return await fs.readFile(path, 'utf-8'); }}];
async function codeReviewAgent(filePath) { return await query({ prompt: `请审查文件 ${filePath} 的代码,检查:\n1. 潜在的 bug\n2. 性能问题\n3. 代码规范\n4. 安全隐患`, tools: codeReviewTools, systemPrompt: "你是一位资深的代码审查专家,擅长发现代码中的问题并提供改进建议。" });}
示例 2: 数据分析 Agent
const dataAnalysisTools = [ { name: "load_csv", description: "加载 CSV 数据文件", input_schema: { type: "object", properties: { path: { type: "string", description: "CSV 文件路径" } }, required: ["path"] }, execute: async ({ path }) => { // 使用 CSV 解析库加载数据 const csv = require('csv-parser'); const fs = require('fs'); const results = [];
return new Promise((resolve) => { fs.createReadStream(path) .pipe(csv()) .on('data', (data) => results.push(data)) .on('end', () => resolve(JSON.stringify(results))); }); } }, { name: "create_chart", description: "创建数据可视化图表", input_schema: { type: "object", properties: { data: { type: "string", description: "JSON 格式的数据" }, chartType: { type: "string", description: "图表类型:line, bar, pie" } }, required: ["data", "chartType"] }, execute: async ({ data, chartType }) => { // 这里可以集成图表库,生成图表 return `已创建 ${chartType} 图表`; } }];
async function dataAnalysisAgent(dataPath, question) { return await query({ prompt: `分析数据文件 ${dataPath},回答问题:${question}。如果需要,请创建可视化图表。`, tools: dataAnalysisTools, systemPrompt: "你是一位数据分析专家,擅长从数据中提取洞察并生成可视化报告。" });}
常见问题解答
Q1: Agent SDK 和普通的 LLM API 调用有什么区别?
A: 主要区别在于:
•普通 API:单次问答,需要手动管理工具调用、上下文等•Agent SDK:自动处理工具调用循环,Agent 可以自主决定何时使用工具,多次迭代直到完成任务
Q2: 如何选择使用 Workflow 还是 Agent?
A: 简单判断:
•Workflow:任务步骤固定,可预测 → 使用 Workflow•Agent:任务开放,需要灵活决策 → 使用 Agent
Q3: Agent 的成本会很高吗?
A: Agent 因为可能多次调用 LLM,成本会高于单次调用。优化建议:
•设置明确的任务边界•使用 maxTokens 限制输出•合理选择模型(Haiku vs Sonnet)•监控和追踪使用量
Q4: Agent 出错了怎么办?
A: 常见错误处理方法:
•设置超时时间•实现重试机制•在工具中添加错误处理•使用明确的系统提示词约束 Agent 行为
学习资源
官方资源
•📚 Claude Agent SDK 官方文档[2]•💻 GitHub 示例仓库[3]•📖 Building Effective Agents 指南[4]
推荐阅读
•Anthropic 的 Agent 架构模式文章•Claude API 文档•各类 Agent 应用案例
下一步
现在你已经掌握了 Claude Agent SDK 的基础知识,可以:
1.✅ 尝试构建一个简单的 Hello World Agent2.✅ 为 Agent 添加自定义工具3.✅ 实现一个实用的小型 Agent 应用4.✅ 探索更复杂的 Agent 架构模式5.✅ 阅读官方文档深入学习
总结
Claude Agent SDK 为构建智能 AI Agent 提供了强大而简洁的工具。通过本文,你应该已经了解:
•🎯 什么是 AI Agent 以及它的工作原理•🔧 如何使用 @anthropic-ai/claude-agent-sdk•🛠️ 如何定义和使用工具•📊 常见的 Agent 架构模式•💡 最佳实践和优化技巧
现在,开始构建你自己的 AI Agent 吧!🚀
作者说明: 本文基于 Claude Agent SDK 最新版本编写,如有更新请参考官方文档。
许可协议: 本文示例代码遵循 MIT 协议,可自由使用和修改。
References
[1] Anthropic Console: https://console.anthropic.com/[2] Claude Agent SDK 官方文档: https://platform.claude.com/docs/en/agent-sdk/overview[3] GitHub 示例仓库: https://github.com/anthropics/claude-agent-sdk-demos[4] Building Effective Agents 指南: https://www.anthropic.com/research/building-effective-agents
更多推荐
所有评论(0)