English ← MyDocs

文档索引

在此获取完整文档索引:https://code.claude.com/docs/llms.txt 使用此文件发现所有可用页面,然后再进一步探索。

Agent SDK 概述

使用 Claude Code 作为库构建生产级 AI 智能体

Note

自 2026 年 6 月 15 日起,订阅计划上的 Agent SDK 和 claude -p 使用将从新的每月 Agent SDK 额度中扣除,与您的交互式使用限制分开。详情请参阅在 Claude 计划中使用 Claude Agent SDK

构建能够自主读取文件、运行命令、搜索网页、编辑代码等的 AI 智能体。Agent SDK 为您提供了与 Claude Code 相同的工具、智能体循环和上下文管理,可通过 Python 和 TypeScript 进行编程。

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions


async def main():
    async for message in query(
        prompt="Find and fix the bug in auth.py",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
    ):
        print(message)  # Claude reads the file, finds the bug, edits it


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find and fix the bug in auth.ts",
  options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
  console.log(message); // Claude reads the file, finds the bug, edits it
}

Agent SDK 包含用于读取文件、运行命令和编辑代码的内置工具,因此您的智能体可以立即开始工作,无需您实现工具执行。深入了解快速入门或探索使用 SDK 构建的真实智能体:

开始使用

  1. 安装 SDK

    npm install @anthropic-ai/claude-agent-sdk
    
    pip install claude-agent-sdk
    
    Note

    TypeScript SDK 作为可选依赖捆绑了适用于您平台的原生 Claude Code 二进制文件,因此您无需单独安装 Claude Code。

  2. 设置 API 密钥

    Console 获取 API 密钥,然后将其设置为环境变量:

    export ANTHROPIC_API_KEY=your-api-key
    

    SDK 还支持通过第三方 API 提供商进行身份验证:

    • Amazon Bedrock:设置 CLAUDE_CODE_USE_BEDROCK=1 环境变量并配置 AWS 凭证
    • Claude Platform on AWS:设置 CLAUDE_CODE_USE_ANTHROPIC_AWS=1ANTHROPIC_AWS_WORKSPACE_ID,然后配置 AWS 凭证
    • Google Vertex AI:设置 CLAUDE_CODE_USE_VERTEX=1 环境变量并配置 Google Cloud 凭证
    • Microsoft Azure:设置 CLAUDE_CODE_USE_FOUNDRY=1 环境变量并配置 Azure 凭证

    详情请参阅 BedrockClaude Platform on AWSVertex AIAzure AI Foundry 的设置指南。

    Note

    除非事先获得批准,否则 Anthropic 不允许第三方开发者为其产品提供 claude.ai 登录或速率限制,包括基于 Claude Agent SDK 构建的智能体。请改用本文档中描述的 API 密钥身份验证方法。

  3. 运行您的第一个智能体

    此示例创建一个使用内置工具列出当前目录中文件的智能体。

    import asyncio
    from claude_agent_sdk import query, ClaudeAgentOptions
    
    
    async def main():
        async for message in query(
            prompt="What files are in this directory?",
            options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),
        ):
            if hasattr(message, "result"):
                print(message.result)
    
    
    asyncio.run(main())
    
    import { query } from "@anthropic-ai/claude-agent-sdk";
    
    for await (const message of query({
      prompt: "What files are in this directory?",
      options: { allowedTools: ["Bash", "Glob"] }
    })) {
      if ("result" in message) console.log(message.result);
    }
    

准备开始构建? 按照快速入门在几分钟内创建一个查找并修复 bug 的智能体。

功能

Claude Code 的所有强大功能均可在 SDK 中使用:

您的智能体可以开箱即用地读取文件、运行命令和搜索代码库。主要工具包括:

工具功能
Read读取工作目录中的任何文件
Write创建新文件
Edit对现有文件进行精确编辑
Bash运行终端命令、脚本、git 操作
Monitor监视后台脚本并将每行输出作为事件响应
Glob按模式查找文件(**/*.tssrc/**/*.py
Grep使用正则表达式搜索文件内容
WebSearch搜索网页获取最新信息
WebFetch获取并解析网页内容
AskUserQuestion通过多选选项向用户提出澄清性问题

此示例创建一个在代码库中搜索 TODO 注释的智能体:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions


async def main():
    async for message in query(
        prompt="Find all TODO comments and create a summary",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
    ):
        if hasattr(message, "result"):
            print(message.result)


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find all TODO comments and create a summary",
  options: { allowedTools: ["Read", "Glob", "Grep"] }
})) {
  if ("result" in message) console.log(message.result);
}

在智能体生命周期的关键节点运行自定义代码。SDK 钩子使用回调函数来验证、记录、阻止或转换智能体行为。

可用钩子: PreToolUsePostToolUseStopSessionStartSessionEndUserPromptSubmit 等。

此示例将所有文件更改记录到审计文件:

import asyncio
from datetime import datetime
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher


async def log_file_change(input_data, tool_use_id, context):
    file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
    with open("./audit.log", "a") as f:
        f.write(f"{datetime.now()}: modified {file_path}\n")
    return {}


async def main():
    async for message in query(
        prompt="Refactor utils.py to improve readability",
        options=ClaudeAgentOptions(
            permission_mode="acceptEdits",
            hooks={
                "PostToolUse": [
                    HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
                ]
            },
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)


asyncio.run(main())
import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
import { appendFile } from "fs/promises";

const logFileChange: HookCallback = async (input) => {
  const filePath = (input as any).tool_input?.file_path ?? "unknown";
  await appendFile("./audit.log", `${new Date().toISOString()}: modified ${filePath}\n`);
  return {};
};

for await (const message of query({
  prompt: "Refactor utils.py to improve readability",
  options: {
    permissionMode: "acceptEdits",
    hooks: {
      PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

了解更多关于钩子的信息 →

生成专门的智能体来处理聚焦的子任务。您的主智能体委托工作,子智能体报告结果。

定义具有专门指令的自定义智能体。子智能体通过 Agent 工具调用,因此请在 allowedTools 中包含 Agent 以自动批准这些调用:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition


async def main():
    async for message in query(
        prompt="Use the code-reviewer agent to review this codebase",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Glob", "Grep", "Agent"],
            agents={
                "code-reviewer": AgentDefinition(
                    description="Expert code reviewer for quality and security reviews.",
                    prompt="Analyze code quality and suggest improvements.",
                    tools=["Read", "Glob", "Grep"],
                )
            },
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Use the code-reviewer agent to review this codebase",
  options: {
    allowedTools: ["Read", "Glob", "Grep", "Agent"],
    agents: {
      "code-reviewer": {
        description: "Expert code reviewer for quality and security reviews.",
        prompt: "Analyze code quality and suggest improvements.",
        tools: ["Read", "Glob", "Grep"]
      }
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

来自子智能体上下文的消息包含 parent_tool_use_id 字段,让您可以跟踪哪些消息属于哪个子智能体执行。

了解更多关于子智能体的信息 →

通过模型上下文协议连接到外部系统:数据库、浏览器、API 以及更多

此示例连接 Playwright MCP 服务器为您的智能体提供浏览器自动化功能:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions


async def main():
    async for message in query(
        prompt="Open example.com and describe what you see",
        options=ClaudeAgentOptions(
            mcp_servers={
                "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
            }
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Open example.com and describe what you see",
  options: {
    mcpServers: {
      playwright: { command: "npx", args: ["@playwright/mcp@latest"] }
    }
  }
})) {
  if ("result" in message) console.log(message.result);
}

了解更多关于 MCP 的信息 →

精确控制智能体可以使用哪些工具。允许安全操作,阻止危险操作,或要求对敏感操作进行审批。

Note

有关交互式审批提示和 AskUserQuestion 工具,请参阅处理审批和用户输入

此示例创建一个只能分析但不能修改代码的只读智能体。allowed_tools 预批准 ReadGlobGrep

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions


async def main():
    async for message in query(
        prompt="Review this code for best practices",
        options=ClaudeAgentOptions(
            allowed_tools=["Read", "Glob", "Grep"],
        ),
    ):
        if hasattr(message, "result"):
            print(message.result)


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Review this code for best practices",
  options: {
    allowedTools: ["Read", "Glob", "Grep"]
  }
})) {
  if ("result" in message) console.log(message.result);
}

了解更多关于权限的信息 →

跨多次交互维持上下文。Claude 会记住已读取的文件、已完成的分析和对话历史。稍后恢复会话,或分叉会话以探索不同的方法。

此示例从第一次查询中捕获会话 ID,然后恢复以继续完整上下文:

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage


async def main():
    session_id = None

    # First query: capture the session ID
    async for message in query(
        prompt="Read the authentication module",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
    ):
        if isinstance(message, SystemMessage) and message.subtype == "init":
            session_id = message.data["session_id"]

    # Resume with full context from the first query
    async for message in query(
        prompt="Now find all places that call it",  # "it" = auth module
        options=ClaudeAgentOptions(resume=session_id),
    ):
        if isinstance(message, ResultMessage):
            print(message.result)


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

let sessionId: string | undefined;

// First query: capture the session ID
for await (const message of query({
  prompt: "Read the authentication module",
  options: { allowedTools: ["Read", "Glob"] }
})) {
  if (message.type === "system" && message.subtype === "init") {
    sessionId = message.session_id;
  }
}

// Resume with full context from the first query
for await (const message of query({
  prompt: "Now find all places that call it", // "it" = auth module
  options: { resume: sessionId }
})) {
  if ("result" in message) console.log(message.result);
}

了解更多关于会话的信息 →

Claude Code 功能

SDK 还支持 Claude Code 基于文件系统的配置。使用默认选项时,SDK 从工作目录中的 .claude/~/.claude/ 加载这些配置。要限制加载哪些来源,请在选项中设置 setting_sources(Python)或 settingSources(TypeScript)。

功能描述位置
SkillsClaude 自动使用或通过 /name 调用的专门能力.claude/skills/*/SKILL.md
Commands旧格式的自定义命令。新自定义命令请使用 skills.claude/commands/*.md
Memory项目上下文和指令CLAUDE.md.claude/CLAUDE.md
Plugins通过 skills、agents、hooks 和 MCP 服务器进行扩展通过 plugins 选项以编程方式使用

比较 Agent SDK 与其他 Claude 工具

Claude 平台提供多种使用 Claude 进行构建的方式。以下是 Agent SDK 的定位:

Anthropic Client SDK 提供直接的 API 访问:您发送提示并自行实现工具执行。Agent SDK 为您提供具有内置工具执行的 Claude。

使用 Client SDK,您需要实现工具循环。使用 Agent SDK,Claude 自行处理:

# Client SDK: You implement the tool loop
response = client.messages.create(...)
while response.stop_reason == "tool_use":
    result = your_tool_executor(response.tool_use)
    response = client.messages.create(tool_result=result, **params)

# Agent SDK: Claude handles tools autonomously
async for message in query(prompt="Fix the bug in auth.py"):
    print(message)
// Client SDK: You implement the tool loop
let response = await client.messages.create({ ...params });
while (response.stop_reason === "tool_use") {
  const result = yourToolExecutor(response.tool_use);
  response = await client.messages.create({ tool_result: result, ...params });
}

// Agent SDK: Claude handles tools autonomously
for await (const message of query({ prompt: "Fix the bug in auth.ts" })) {
  console.log(message);
}

相同的功能,不同的接口:

使用场景最佳选择
交互式开发CLI
CI/CD 管道SDK
自定义应用程序SDK
一次性任务CLI
生产环境自动化SDK

许多团队两者都使用:CLI 用于日常开发,SDK 用于生产。工作流可以在两者之间直接转换。

Managed Agents 是一个托管的 REST API:Anthropic 运行智能体和沙盒,您的应用程序发送事件并流式回传结果。Agent SDK 是一个在您自己的进程中运行智能体循环的库。

Agent SDKManaged Agents
运行在您的进程、您的基础设施Anthropic 托管的基础设施
接口Python 或 TypeScript 库REST API
智能体操作于您基础设施上的文件每个会话的托管沙盒
会话状态您文件系统上的 JSONLAnthropic 托管的事件日志
自定义工具进程内 Python 或 TypeScript 函数Claude 触发工具;您执行并返回结果
最适合本地原型开发、直接在文件系统和服务上工作的智能体无需操作沙盒或会话基础设施的生产智能体、长时间运行和异步会话

常见的路径是在本地使用 Agent SDK 进行原型开发,然后转向 Managed Agents 用于生产。

更新日志

查看 SDK 更新、错误修复和新功能的完整更新日志:

报告错误

如果您遇到 Agent SDK 的错误或问题:

品牌指南

对于集成 Claude Agent SDK 的合作伙伴,使用 Claude 品牌是可选的。在您的产品中引用 Claude 时:

允许:

  • "Claude Agent"(下拉菜单首选)
  • "Claude"(在已标记为 "Agents" 的菜单中)
  • "{YourAgentName} Powered by Claude"(如果您已有智能体名称)

不允许:

  • "Claude Code" 或 "Claude Code Agent"
  • Claude Code 品牌的 ASCII 艺术或模仿 Claude Code 的视觉元素

您的产品应保持自己的品牌标识,不应看起来像 Claude Code 或任何 Anthropic 产品。有关品牌合规性的问题,请联系 Anthropic 销售团队

许可证和条款

Claude Agent SDK 的使用受 Anthropic 商业服务条款的约束,包括当您使用它为您自己的客户和最终用户提供产品和服务时,除非特定组件或依赖项受该组件 LICENSE 文件中指示的不同许可证约束。

后续步骤