Back to Blog

深入理解 Claude Agent SDK:构建智能 AI 应用的完整指南

2026-03-28
Claude Agent SDK TypeScript AI 开发工具

深入理解 Claude Agent SDK:构建智能 AI 应用的完整指南

Claude Agent SDK 是 Anthropic 提供的官方软件开发工具包,用于构建能够使用工具(Tools)和执行复杂任务的 Claude 应用。本文将详细介绍如何使用 Agent SDK 开发强大的 AI 应用。

什么是 Claude Agent SDK?

Claude Agent SDK 是一个 TypeScript/JavaScript 库,提供了与 Anthropic API 交互的高级抽象。它的核心特性包括:

  • 工具调用(Tool Use):让 Claude 能够调用外部工具和 API
  • 对话管理:自动处理多轮对话的上下文
  • 流式响应:支持实时流式输出
  • 错误处理:内置重试和错误恢复机制
  • 类型安全:完整的 TypeScript 类型定义

安装和设置

安装 SDK

npm install @anthropic-ai/sdk

基本配置

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY,
});

核心概念

1. 消息(Messages)

Claude API 基于"消息"(Messages)的概念。每条消息包含一个角色(Role)和内容(Content):

const message = await client.messages.create({
  model: "claude-3-7-sonnet-20250219",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: "Hello, Claude!"
    }
  ]
});

2. 工具(Tools)

工具定义了 Claude 可以调用的外部函数。每个工具包含:

  • name: 工具名称
  • description: 工具功能的详细描述
  • input_schema: 输入参数的 JSON Schema
const tools = [
  {
    name: "get_weather",
    description: "Get the current weather in a given location",
    input_schema: {
      type: "object",
      properties: {
        location: {
          type: "string",
          description: "The city and state, e.g. San Francisco, CA"
        },
        unit: {
          type: "string",
          enum: ["celsius", "fahrenheit"],
          description: "The temperature unit"
        }
      },
      required: ["location"]
    }
  }
];

实战示例

示例一:简单的工具调用

import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

async function chatWithTools() {
  const response = await client.messages.create({
    model: "claude-3-7-sonnet-20250219",
    max_tokens: 1024,
    tools: [
      {
        name: "calculator",
        description: "Perform basic mathematical calculations",
        input_schema: {
          type: "object",
          properties: {
            expression: {
              type: "string",
              description: "Mathematical expression to evaluate"
            }
          },
          required: ["expression"]
        }
      }
    ],
    messages: [
      {
        role: "user",
        content: "What is 25 * 37 + 15?"
      }
    ]
  });

  // 检查 Claude 是否想要使用工具
  if (response.stop_reason === "tool_use") {
    for (const block of response.content) {
      if (block.type === "tool_use") {
        console.log("Claude wants to use tool:", block.name);
        console.log("Input:", block.input);

        // 执行工具调用
        const result = eval(block.input.expression);
        console.log("Result:", result);

        // 将结果返回给 Claude
        const followUp = await client.messages.create({
          model: "claude-3-7-sonnet-20250219",
          max_tokens: 1024,
          messages: [
            {
              role: "user",
              content: "What is 25 * 37 + 15?"
            },
            {
              role: "assistant",
              content: response.content
            },
            {
              role: "user",
              content: [
                {
                  type: "tool_result",
                  tool_use_id: block.id,
                  content: String(result)
                }
              ]
            }
          ]
        });

        console.log("Final response:", followUp.content);
      }
    }
  }
}

示例二:多轮对话 Agent

class ChatAgent {
  private client: Anthropic;
  private conversationHistory: Array<{role: string, content: any}> = [];

  constructor(apiKey: string) {
    this.client = new Anthropic({ apiKey });
  }

  async chat(userMessage: string) {
    // 添加用户消息到历史
    this.conversationHistory.push({
      role: "user",
      content: userMessage
    });

    // 调用 Claude API
    const response = await this.client.messages.create({
      model: "claude-3-7-sonnet-20250219",
      max_tokens: 1024,
      messages: this.conversationHistory
    });

    // 提取响应文本
    const assistantMessage = response.content
      .filter(block => block.type === "text")
      .map(block => block.text)
      .join("\n");

    // 添加助手响应到历史
    this.conversationHistory.push({
      role: "assistant",
      content: response.content
    });

    return assistantMessage;
  }

  getHistory() {
    return this.conversationHistory;
  }

  clearHistory() {
    this.conversationHistory = [];
  }
}

// 使用示例
const agent = new ChatAgent(process.env.ANTHROPIC_API_KEY!);
const response1 = await agent.chat("What's the capital of France?");
console.log(response1);

const response2 = await agent.chat("And what's its population?");
console.log(response2);

示例三:构建知识库问答 Agent

async function createRAGAgent() {
  const client = new Anthropic();

  // 模拟知识库检索
  async function retrieveDocuments(query: string): Promise<string[]> {
    // 这里应该连接到实际的向量数据库
    return [
      `Document about ${query}: ...`,
      `Another relevant document: ...`
    ];
  }

  async function askQuestion(question: string) {
    // 1. 检索相关文档
    const documents = await retrieveDocuments(question);

    // 2. 构建带上下文的提示
    const context = documents.join("\n\n");

    // 3. 调用 Claude
    const response = await client.messages.create({
      model: "claude-3-7-sonnet-20250219",
      max_tokens: 1024,
      system: `You are a helpful assistant that answers questions based on the provided context.
Use only the information from the context to answer questions. If the answer is not in the context, say "I don't have enough information to answer that."`,
      messages: [
        {
          role: "user",
          content: `Context:\n${context}\n\nQuestion: ${question}`
        }
      ]
    });

    return response.content[0].text;
  }

  return { askQuestion };
}

// 使用示例
const ragAgent = await createRAGAgent();
const answer = await ragAgent.askQuestion("What is the return policy?");
console.log(answer);

示例四:流式响应

async function streamChat() {
  const client = new Anthropic();

  const stream = await client.messages.create({
    model: "claude-3-7-sonnet-20250219",
    max_tokens: 1024,
    messages: [
      {
        role: "user",
        content: "Write a short poem about AI"
      }
    ],
    stream: true
  });

  for await (const event of stream) {
    if (event.type === "content_block_delta") {
      process.stdout.write(event.delta.text);
    }
  }
}

高级功能

自定义系统提示

const response = await client.messages.create({
  model: "claude-3-7-sonnet-20250219",
  max_tokens: 1024,
  system: `You are a helpful assistant specialized in Python programming.
Always provide code examples with proper error handling.`,
  messages: [
    {
      role: "user",
      content: "How do I read a file in Python?"
    }
  ]
});

处理多种内容类型

const response = await client.messages.create({
  model: "claude-3-7-sonnet-20250219",
  max_tokens: 1024,
  messages: [
    {
      role: "user",
      content: [
        {
          type: "text",
          text: "What do you see in this image?"
        },
        {
          type: "image",
          source: {
            type: "base64",
            media_type: "image/jpeg",
            data: "base64-encoded-image-data"
          }
        }
      ]
    }
  ]
});

错误处理和重试

async function callWithRetry(
  fn: () => Promise<any>,
  maxRetries: number = 3
): Promise<any> {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error: any) {
      if (error.status === 429) {
        // 速率限制,等待后重试
        const waitTime = Math.pow(2, i) * 1000;
        await new Promise(resolve => setTimeout(resolve, waitTime));
      } else if (i === maxRetries - 1) {
        throw error;
      }
    }
  }
}

最佳实践

1. 管理令牌限制

  • 估算输入和输出令牌数
  • 使用适当的 max_tokens 设置
  • 考虑使用较小的模型(如 Claude 3 Haiku)以降低成本

2. 工具设计原则

  • 清晰的描述:提供详细的工具描述,帮助 Claude 理解何时使用
  • 良好的 schema:使用 JSON Schema 定义清晰的输入结构
  • 错误处理:优雅地处理工具执行失败的情况

3. 对话管理

  • 限制对话历史长度以避免超出令牌限制
  • 实现对话摘要功能
  • 考虑使用外部存储保存长期对话历史

4. 性能优化

  • 使用流式响应改善用户体验
  • 并行执行独立的工具调用
  • 缓存常见查询的结果

常见用例

1. 代码生成和审查

async function reviewCode(code: string) {
  const response = await client.messages.create({
    model: "claude-3-7-sonnet-20250219",
    max_tokens: 2048,
    system: "You are an expert code reviewer. Analyze the code for bugs, security issues, and best practices.",
    messages: [
      {
        role: "user",
        content: `Review this code:\n\n${code}`
      }
    ]
  });

  return response.content[0].text;
}

2. 数据分析

async function analyzeData(data: any[]) {
  const response = await client.messages.create({
    model: "claude-3-7-sonnet-20250219",
    max_tokens: 2048,
    tools: [
      {
        name: "calculate_statistics",
        description: "Calculate statistical metrics",
        input_schema: {
          type: "object",
          properties: {
            operation: {
              type: "string",
              enum: ["mean", "median", "mode", "std"]
            }
          }
        }
      }
    ],
    messages: [
      {
        role: "user",
        content: `Analyze this data and provide insights: ${JSON.stringify(data)}`
      }
    ]
  });

  return response;
}

3. 文档生成

async function generateDocumentation(code: string) {
  const response = await client.messages.create({
    model: "claude-3-7-sonnet-20250219",
    max_tokens: 4096,
    system: "You are a technical writer. Generate clear documentation from code.",
    messages: [
      {
        role: "user",
        content: `Generate documentation for:\n\n${code}`
      }
    ]
  });

  return response.content[0].text;
}

相关资源

总结

Claude Agent SDK 为构建智能 AI 应用提供了强大而灵活的工具。通过工具调用、对话管理和流式响应等特性,你可以创建出能够执行复杂任务、理解上下文并提供实时反馈的 AI 应用。

无论你是要构建聊天机器人、代码助手、数据分析工具还是其他 AI 应用,Claude Agent SDK 都能提供必要的功能和灵活性来实现你的想法。


本文发布于 2026 年 3 月 28 日,基于 Claude Agent SDK 的最新版本编写

Enjoyed this article? Share it with others!