6 6
7> 使用 Claude Code 作为库构建生产级 AI 代理7> 使用 Claude Code 作为库构建生产级 AI 代理
8 8
9构建能够自主读取文件、运行命令、搜索网络、编辑代码等的 AI 代理。Agent SDK 为您提供了与 Claude Code 相同的工具、代理循环和上下文管理,可在 Python 和 TypeScript 中编程。有关代理工具设计背后的思考,请参阅博客上的 [A harness for every task: dynamic workflows in Claude Code](https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code)。9代理是一个应用程序,它通过规划自己的步骤并调用读取文件、运行命令或编辑代码的工具来完成任务。Agent SDK 为您提供了与 Claude Code 相同的工具、[代理循环](/docs/zh-CN/agent-sdk/agent-loop)和上下文管理,可在 Python 和 TypeScript 中编程。
10 10
11<CodeGroup>11<h2 id="compare-the-agent-sdk-to-other-claude-tools">
12 ```python Python theme={null}12 将 Agent SDK 与其他 Claude 工具进行比较
13 import asyncio
14 from claude_agent_sdk import query, ClaudeAgentOptions
15
16
17 async def main():
18 async for message in query(
19 prompt="Find and fix the bug in auth.py",
20 options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
21 ):
22 print(message) # Claude reads the file, finds the bug, edits it
23
24
25 asyncio.run(main())
26 ```
27
28 ```typescript TypeScript theme={null}
29 import { query } from "@anthropic-ai/claude-agent-sdk";
30
31 for await (const message of query({
32 prompt: "Find and fix the bug in auth.ts",
33 options: { allowedTools: ["Read", "Edit", "Bash"] }
34 })) {
35 console.log(message); // Claude reads the file, finds the bug, edits it
36 }
37 ```
38</CodeGroup>
39
40Agent SDK 包含用于读取文件、运行命令和编辑代码的内置工具,因此您的代理可以立即开始工作,无需您实现工具执行。深入了解快速入门或探索使用 SDK 构建的真实代理:
41
42<CardGroup cols={2}>
43 <Card title="快速入门" icon="play" href="/zh-CN/agent-sdk/quickstart">
44 在几分钟内构建一个 bug 修复代理
45 </Card>
46
47 <Card title="示例代理" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">
48 电子邮件助手、研究代理等
49 </Card>
50</CardGroup>
51
52<h2 id="get-started">
53 开始使用
54</h2>13</h2>
55 14
56<Steps>15Agent SDK、CLI、Client SDK 和 Managed Agents 各自满足不同的需求。使用该表格找到与您正在构建的内容相匹配的工具。
57 <Step title="安装 SDK">
58 <Tabs>
59 <Tab title="TypeScript">
60 ```bash theme={null}
61 npm install @anthropic-ai/claude-agent-sdk
62 ```
63 </Tab>
64
65 <Tab title="Python (uv)">
66 [uv](https://docs.astral.sh/uv/) 是一个快速的 Python 包管理器,可以自动处理虚拟环境:
67
68 ```bash theme={null}
69 uv init
70 uv add claude-agent-sdk
71 ```
72 </Tab>
73
74 <Tab title="Python (pip)">
75 创建并激活虚拟环境,然后安装该包。安装到虚拟环境中可以避免 `error: externally-managed-environment` 失败,该失败是最近的 Debian、Ubuntu 和 Homebrew 安装上的系统 Python 在 venv 外运行 `pip install` 时返回的。
76
77 在 macOS 或 Linux 上:
78
79 ```bash theme={null}
80 python3 -m venv .venv
81 source .venv/bin/activate
82 pip install claude-agent-sdk
83 ```
84
85 在 Windows 上:
86
87 ```powershell theme={null}
88 py -m venv .venv
89 .venv\Scripts\Activate.ps1
90 pip install claude-agent-sdk
91 ```
92
93 如果 PowerShell 因执行策略错误而阻止 `Activate.ps1`,请先运行 `Set-ExecutionPolicy -Scope Process RemoteSigned`。
94
95 Python 包需要 Python 3.10 或更高版本。如果 pip 报告 `No matching distribution found for claude-agent-sdk`,说明您的解释器版本早于 3.10。在 macOS 或 Linux 上运行 `python3 --version`,或在 Windows 上运行 `py --version`,以检查版本。
96 </Tab>
97 </Tabs>
98
99 <Note>
100 TypeScript SDK 为您的平台捆绑了一个本地 Claude Code 二进制文件作为可选依赖项,因此您无需单独安装 Claude Code。
101 </Note>
102 </Step>
103
104 <Step title="设置您的 API 密钥">
105 从[控制台](https://platform.claude.com/)获取 API 密钥,然后将其设置为环境变量。
106
107 在 macOS 或 Linux 上:
108
109 ```bash theme={null}
110 export ANTHROPIC_API_KEY=sk-ant-xxxxx
111 ```
112
113 在 Windows PowerShell 上:
114
115 ```powershell theme={null}
116 $env:ANTHROPIC_API_KEY = "sk-ant-xxxxx"
117 ```
118
119 SDK 还支持通过第三方 API 提供商进行身份验证:
120
121 * **Amazon Bedrock**:设置 `CLAUDE_CODE_USE_BEDROCK=1` 环境变量并配置 AWS 凭证
122 * **Claude Platform on AWS**:设置 `CLAUDE_CODE_USE_ANTHROPIC_AWS=1` 和 `ANTHROPIC_AWS_WORKSPACE_ID`,然后配置 AWS 凭证
123 * **Google Cloud 的 Agent Platform**:设置 `CLAUDE_CODE_USE_VERTEX=1` 环境变量并配置 Google Cloud 凭证
124 * **Microsoft Azure**:设置 `CLAUDE_CODE_USE_FOUNDRY=1` 环境变量并配置 Azure 凭证
125
126 有关详细信息,请参阅 [Amazon Bedrock](/zh-CN/amazon-bedrock)、[Claude Platform on AWS](/zh-CN/claude-platform-on-aws)、[Google Cloud 的 Agent Platform](/zh-CN/google-vertex-ai) 或 [Microsoft Foundry](/zh-CN/microsoft-foundry) 的设置指南。
127
128 <Note>
129 除非事先获得批准,否则 Anthropic 不允许第三方开发人员为其产品(包括基于 Claude Agent SDK 构建的代理)提供 claude.ai 登录或速率限制。请改用本文档中描述的 API 密钥身份验证方法。
130 </Note>
131 </Step>
132 16
133 <Step title="运行您的第一个代理">17| 如果您... | 使用 | 原因 |
134 此示例创建一个代理,该代理使用内置工具列出当前目录中的文件。18| ----------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------ |
19| 构建代理而不自己实现工具循环 | **Agent SDK** | 一个在您自己的进程中运行代理循环的库,支持 Python 或 TypeScript。 |
20| 进行交互式开发或从终端运行一次性任务 | [**Claude Code CLI**](/docs/zh-CN/overview) | 终端界面,为日常交互使用而构建。 |
21| 直接调用 API 并自己实现工具循环 | [**Client SDK**](https://platform.claude.com/docs/en/api/client-sdks) | 直接访问 Anthropic API 而不是 Claude Code。您自己实现工具循环。 |
22| 运行长期运行或异步代理,无需管理您自己的沙箱或会话基础设施 | [**Managed Agents**](https://platform.claude.com/docs/en/managed-agents/overview) | 托管 REST API,是 Agent SDK 的独立产品。Anthropic 运行代理和沙箱。 |
135 23
136 <CodeGroup>24该 SDK 仅作为 Python 和 TypeScript 的库提供。要从另一种语言驱动相同的代理循环,请[以子进程的形式运行 CLI](/docs/zh-CN/headless),使用 `-p` 标志和 `--output-format json`。
137 ```python Python theme={null}
138 import asyncio
139 from claude_agent_sdk import query, ClaudeAgentOptions
140
141
142 async def main():
143 async for message in query(
144 prompt="What files are in this directory?",
145 options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),
146 ):
147 if hasattr(message, "result"):
148 print(message.result)
149
150
151 asyncio.run(main())
152 ```
153
154 ```typescript TypeScript theme={null}
155 import { query } from "@anthropic-ai/claude-agent-sdk";
156
157 for await (const message of query({
158 prompt: "What files are in this directory?",
159 options: { allowedTools: ["Bash", "Glob"] }
160 })) {
161 if ("result" in message) console.log(message.result);
162 }
163 ```
164 </CodeGroup>
165 </Step>
166</Steps>
167
168**准备好构建了吗?** 按照[快速入门](/zh-CN/agent-sdk/quickstart)在几分钟内创建一个查找和修复 bug 的代理。
169 25
170<h2 id="capabilities">26<h2 id="capabilities">
171 功能27 功能
172</h2>28</h2>
173 29
174使 Claude Code 强大的一切都可在 SDK 中使用:30这些 Claude Code 功能在 SDK 中可用:
175
176<Tabs>
177 <Tab title="内置工具">
178 您的代理可以开箱即用地读取文件、运行命令和搜索代码库。关键工具包括:
179
180 | 工具 | 功能 |
181 | ------------------------------------------------------------------------------ | -------------------------------- |
182 | **Read** | 读取工作目录中的任何文件 |
183 | **Write** | 创建新文件 |
184 | **Edit** | 对现有文件进行精确编辑 |
185 | **Bash** | 运行终端命令、脚本、git 操作 |
186 | **Monitor** | 监视后台脚本并对每个输出行作为事件做出反应 |
187 | **Glob** | 按模式查找文件(`**/*.ts`、`src/**/*.py`) |
188 | **Grep** | 使用正则表达式搜索文件内容 |
189 | **WebSearch** | 搜索网络以获取当前信息 |
190 | **WebFetch** | 获取并解析网页内容 |
191 | **[AskUserQuestion](/zh-CN/agent-sdk/user-input#handle-clarifying-questions)** | 向用户提出带有多选选项的澄清问题 |
192
193 此示例创建一个代理,该代理在您的代码库中搜索 TODO 注释:
194
195 <CodeGroup>
196 ```python Python theme={null}
197 import asyncio
198 from claude_agent_sdk import query, ClaudeAgentOptions
199
200
201 async def main():
202 async for message in query(
203 prompt="Find all TODO comments and create a summary",
204 options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep"]),
205 ):
206 if hasattr(message, "result"):
207 print(message.result)
208
209
210 asyncio.run(main())
211 ```
212
213 ```typescript TypeScript theme={null}
214 import { query } from "@anthropic-ai/claude-agent-sdk";
215
216 for await (const message of query({
217 prompt: "Find all TODO comments and create a summary",
218 options: { allowedTools: ["Read", "Glob", "Grep"] }
219 })) {
220 if ("result" in message) console.log(message.result);
221 }
222 ```
223 </CodeGroup>
224 </Tab>
225
226 <Tab title="Hooks">
227 在代理生命周期的关键点运行自定义代码。SDK hooks 使用回调函数来验证、记录、阻止或转换代理行为。
228
229 **可用 hooks:** `PreToolUse`、`PostToolUse`、`Stop`、`SessionStart`、`SessionEnd`、`UserPromptSubmit` 等。
230
231 此示例将所有文件更改记录到审计文件:
232
233 <CodeGroup>
234 ```python Python theme={null}
235 import asyncio
236 from datetime import datetime
237 from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
238
239
240 async def log_file_change(input_data, tool_use_id, context):
241 file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
242 with open("./audit.log", "a") as f:
243 f.write(f"{datetime.now()}: modified {file_path}\n")
244 return {}
245
246
247 async def main():
248 async for message in query(
249 prompt="Refactor utils.py to improve readability",
250 options=ClaudeAgentOptions(
251 permission_mode="acceptEdits",
252 hooks={
253 "PostToolUse": [
254 HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
255 ]
256 },
257 ),
258 ):
259 if hasattr(message, "result"):
260 print(message.result)
261
262
263 asyncio.run(main())
264 ```
265
266 ```typescript TypeScript theme={null}
267 import { query, HookCallback } from "@anthropic-ai/claude-agent-sdk";
268 import { appendFile } from "fs/promises";
269
270 const logFileChange: HookCallback = async (input) => {
271 const filePath = (input as any).tool_input?.file_path ?? "unknown";
272 await appendFile("./audit.log", `${new Date().toISOString()}: modified ${filePath}\n`);
273 return {};
274 };
275
276 for await (const message of query({
277 prompt: "Refactor utils.py to improve readability",
278 options: {
279 permissionMode: "acceptEdits",
280 hooks: {
281 PostToolUse: [{ matcher: "Edit|Write", hooks: [logFileChange] }]
282 }
283 }
284 })) {
285 if ("result" in message) console.log(message.result);
286 }
287 ```
288 </CodeGroup>
289
290 [了解更多关于 hooks →](/zh-CN/agent-sdk/hooks)
291 </Tab>
292
293 <Tab title="子代理">
294 生成专门的代理来处理专注的子任务。您的主代理委派工作,子代理报告结果。
295 31
296 定义具有专门说明的自定义代理。子代理通过 Agent 工具调用,因此在 `allowedTools` 中包含 `Agent` 以自动批准这些调用:32| 功能 | 功能说明 | 了解更多 |
33| ------------ | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34| 内置工具 | 读取、写入、编辑文件,运行命令,搜索网络 | [工具参考](/docs/zh-CN/tools-reference) |
35| Hooks | 在代理生命周期的关键点运行自定义代码 | [Hooks](/docs/zh-CN/agent-sdk/hooks) |
36| Subagents | 生成专门的代理来处理专注的子任务 | [Subagents](/docs/zh-CN/agent-sdk/subagents) |
37| MCP | 通过 Model Context Protocol 连接外部工具和数据源 | [MCP](/docs/zh-CN/agent-sdk/mcp) |
38| 权限 | 控制哪些工具自动运行,哪些需要批准 | [权限](/docs/zh-CN/agent-sdk/permissions) |
39| 会话 | 在多次交换中保持上下文,稍后恢复或分叉 | [会话](/docs/zh-CN/agent-sdk/sessions) |
40| Skills、命令和内存 | 从您的项目的 `.claude/` 和 `~/.claude/` 自动加载,与 Claude Code 相同 | [Skills](/docs/zh-CN/agent-sdk/skills)、[命令](/docs/zh-CN/agent-sdk/skills#commands-in-agent-sdk-sessions)、[内存](/docs/zh-CN/agent-sdk/modifying-system-prompts)、[配置加载](/docs/zh-CN/agent-sdk/claude-code-features) |
41| Plugins | 打包 skills、代理、hooks 和 MCP 服务器,并按本地路径加载它们 | [Plugins](/docs/zh-CN/agent-sdk/plugins) |
297 42
298 <CodeGroup>43<h2 id="get-started">
299 ```python Python theme={null}44 开始使用
300 import asyncio
301 from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
302
303
304 async def main():
305 async for message in query(
306 prompt="Use the code-reviewer agent to review this codebase",
307 options=ClaudeAgentOptions(
308 allowed_tools=["Read", "Glob", "Grep", "Agent"],
309 agents={
310 "code-reviewer": AgentDefinition(
311 description="Expert code reviewer for quality and security reviews.",
312 prompt="Analyze code quality and suggest improvements.",
313 tools=["Read", "Glob", "Grep"],
314 )
315 },
316 ),
317 ):
318 if hasattr(message, "result"):
319 print(message.result)
320
321
322 asyncio.run(main())
323 ```
324
325 ```typescript TypeScript theme={null}
326 import { query } from "@anthropic-ai/claude-agent-sdk";
327
328 for await (const message of query({
329 prompt: "Use the code-reviewer agent to review this codebase",
330 options: {
331 allowedTools: ["Read", "Glob", "Grep", "Agent"],
332 agents: {
333 "code-reviewer": {
334 description: "Expert code reviewer for quality and security reviews.",
335 prompt: "Analyze code quality and suggest improvements.",
336 tools: ["Read", "Glob", "Grep"]
337 }
338 }
339 }
340 })) {
341 if ("result" in message) console.log(message.result);
342 }
343 ```
344 </CodeGroup>
345
346 来自子代理上下文内的消息包含 `parent_tool_use_id` 字段,让您可以跟踪哪些消息属于哪个子代理执行。
347
348 [了解更多关于子代理 →](/zh-CN/agent-sdk/subagents)
349 </Tab>
350
351 <Tab title="MCP">
352 通过 Model Context Protocol 连接到外部系统:数据库、浏览器、API 和[数百个更多](https://github.com/modelcontextprotocol/servers)。
353
354 此示例连接 [Playwright MCP 服务器](https://github.com/microsoft/playwright-mcp)以为您的代理提供浏览器自动化功能:
355
356 <CodeGroup>
357 ```python Python theme={null}
358 import asyncio
359 from claude_agent_sdk import query, ClaudeAgentOptions
360
361
362 async def main():
363 async for message in query(
364 prompt="Open example.com and describe what you see",
365 options=ClaudeAgentOptions(
366 mcp_servers={
367 "playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
368 }
369 ),
370 ):
371 if hasattr(message, "result"):
372 print(message.result)
373
374
375 asyncio.run(main())
376 ```
377
378 ```typescript TypeScript theme={null}
379 import { query } from "@anthropic-ai/claude-agent-sdk";
380
381 for await (const message of query({
382 prompt: "Open example.com and describe what you see",
383 options: {
384 mcpServers: {
385 playwright: { command: "npx", args: ["@playwright/mcp@latest"] }
386 }
387 }
388 })) {
389 if ("result" in message) console.log(message.result);
390 }
391 ```
392 </CodeGroup>
393
394 [了解更多关于 MCP →](/zh-CN/agent-sdk/mcp)
395 </Tab>
396
397 <Tab title="权限">
398 精确控制您的代理可以使用哪些工具。允许安全操作、阻止危险操作或要求对敏感操作进行批准。
399
400 <Note>
401 对于交互式批准提示和 `AskUserQuestion` 工具,请参阅[处理批准和用户输入](/zh-CN/agent-sdk/user-input)。
402 </Note>
403
404 此示例创建一个只读代理,可以分析但不能修改代码。`allowed_tools` 预先批准 `Read`、`Glob` 和 `Grep`。
405
406 <CodeGroup>
407 ```python Python theme={null}
408 import asyncio
409 from claude_agent_sdk import query, ClaudeAgentOptions
410
411
412 async def main():
413 async for message in query(
414 prompt="Review this code for best practices",
415 options=ClaudeAgentOptions(
416 allowed_tools=["Read", "Glob", "Grep"],
417 ),
418 ):
419 if hasattr(message, "result"):
420 print(message.result)
421
422
423 asyncio.run(main())
424 ```
425
426 ```typescript TypeScript theme={null}
427 import { query } from "@anthropic-ai/claude-agent-sdk";
428
429 for await (const message of query({
430 prompt: "Review this code for best practices",
431 options: {
432 allowedTools: ["Read", "Glob", "Grep"]
433 }
434 })) {
435 if ("result" in message) console.log(message.result);
436 }
437 ```
438 </CodeGroup>
439
440 [了解更多关于权限 →](/zh-CN/agent-sdk/permissions)
441 </Tab>
442
443 <Tab title="会话">
444 在多次交换中保持上下文。Claude 记住读取的文件、完成的分析和对话历史。稍后恢复会话,或分叉它们以探索不同的方法。
445
446 此示例从第一个查询中捕获会话 ID,然后恢复以继续完整上下文:
447
448 <CodeGroup>
449 ```python Python theme={null}
450 import asyncio
451 from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage
452
453
454 async def main():
455 session_id = None
456
457 # First query: capture the session ID
458 async for message in query(
459 prompt="Read the authentication module",
460 options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
461 ):
462 if isinstance(message, SystemMessage) and message.subtype == "init":
463 session_id = message.data["session_id"]
464
465 # Resume with full context from the first query
466 async for message in query(
467 prompt="Now find all places that call it", # "it" = auth module
468 options=ClaudeAgentOptions(resume=session_id),
469 ):
470 if isinstance(message, ResultMessage):
471 print(message.result)
472
473
474 asyncio.run(main())
475 ```
476
477 ```typescript TypeScript theme={null}
478 import { query } from "@anthropic-ai/claude-agent-sdk";
479
480 let sessionId: string | undefined;
481
482 // First query: capture the session ID
483 for await (const message of query({
484 prompt: "Read the authentication module",
485 options: { allowedTools: ["Read", "Glob"] }
486 })) {
487 if (message.type === "system" && message.subtype === "init") {
488 sessionId = message.session_id;
489 }
490 }
491
492 // Resume with full context from the first query
493 for await (const message of query({
494 prompt: "Now find all places that call it", // "it" = auth module
495 options: { resume: sessionId }
496 })) {
497 if ("result" in message) console.log(message.result);
498 }
499 ```
500 </CodeGroup>
501
502 [了解更多关于会话 →](/zh-CN/agent-sdk/sessions)
503 </Tab>
504</Tabs>
505
506<h3 id="claude-code-features">
507 Claude Code 功能
508</h3>
509
510SDK 还支持 Claude Code 的基于文件系统的配置。使用默认选项,SDK 从您的工作目录中的 `.claude/` 和 `~/.claude/` 加载这些。要限制加载哪些源,请在您的选项中设置 `setting_sources`(Python)或 `settingSources`(TypeScript)。
511
512| 功能 | 描述 | 位置 |
513| --------------------------------------------------- | ------------------------------- | --------------------------------- |
514| [Skills](/zh-CN/agent-sdk/skills) | Claude 自动使用或您使用 `/name` 调用的专门功能 | `.claude/skills/*/SKILL.md` |
515| [Commands](/zh-CN/agent-sdk/slash-commands) | 旧格式的自定义命令。为新的自定义命令使用 skills | `.claude/commands/*.md` |
516| [Memory](/zh-CN/agent-sdk/modifying-system-prompts) | 项目上下文和说明 | `CLAUDE.md` 或 `.claude/CLAUDE.md` |
517| [Plugins](/zh-CN/agent-sdk/plugins) | 使用 skills、代理、hooks 和 MCP 服务器扩展 | 通过 `plugins` 选项编程 |
518
519<h2 id="compare-the-agent-sdk-to-other-claude-tools">
520 将 Agent SDK 与其他 Claude 工具进行比较
521</h2>45</h2>
522 46
523Claude 平台提供了多种使用 Claude 构建的方式。以下是 Agent SDK 的适用场景:47按照 [快速入门](/docs/zh-CN/agent-sdk/quickstart) 安装 SDK、设置您的 API 密钥,并构建您的第一个代理,该代理可以查找并修复现有代码中的错误。
524
525<Tabs>
526 <Tab title="Agent SDK vs Client SDK">
527 [Anthropic Client SDK](https://platform.claude.com/docs/zh-CN/api/client-sdks) 为您提供直接 API 访问:您发送提示并自己实现工具执行。**Agent SDK** 为您提供具有内置工具执行的 Claude。
528
529 使用 Client SDK,您实现工具循环。使用 Agent SDK,Claude 处理它:
530
531 <CodeGroup>
532 ```python Python theme={null}
533 # Client SDK: You implement the tool loop
534 response = client.messages.create(...)
535 while response.stop_reason == "tool_use":
536 result = your_tool_executor(response.tool_use)
537 response = client.messages.create(tool_result=result, **params)
538
539 # Agent SDK: Claude handles tools autonomously
540 async for message in query(prompt="Fix the bug in auth.py"):
541 print(message)
542 ```
543
544 ```typescript TypeScript theme={null}
545 // Client SDK: You implement the tool loop
546 let response = await client.messages.create({ ...params });
547 while (response.stop_reason === "tool_use") {
548 const result = yourToolExecutor(response.tool_use);
549 response = await client.messages.create({ tool_result: result, ...params });
550 }
551 48
552 // Agent SDK: Claude handles tools autonomously49<Note>
553 for await (const message of query({ prompt: "Fix the bug in auth.ts" })) {50 除非事先获得批准,否则 Anthropic 不允许第三方开发者为其产品(包括基于 Claude Agent SDK 构建的代理)提供 claude.ai 登录或速率限制。请改用 [快速入门](/docs/zh-CN/agent-sdk/quickstart) 中描述的 API 密钥身份验证方法。
554 console.log(message);51</Note>
555 }
556 ```
557 </CodeGroup>
558 </Tab>
559
560 <Tab title="Agent SDK vs Claude Code CLI">
561 相同的功能,不同的界面:
562
563 | 用例 | 最佳选择 |
564 | -------- | ---- |
565 | 交互式开发 | CLI |
566 | CI/CD 管道 | SDK |
567 | 自定义应用程序 | SDK |
568 | 一次性任务 | CLI |
569 | 生产自动化 | SDK |
570
571 许多团队同时使用两者:CLI 用于日常开发,SDK 用于生产。工作流在它们之间直接转换。
572 </Tab>
573
574 <Tab title="Agent SDK vs Managed Agents">
575 [Managed Agents](https://platform.claude.com/docs/zh-CN/managed-agents/overview) 是一个托管的 REST API:Anthropic 运行代理和沙箱,您的应用程序发送事件并流回结果。**Agent SDK** 是一个在您自己的进程内运行代理循环的库。
576
577 | | Agent SDK | Managed Agents |
578 | --------- | -------------------------- | ---------------------------- |
579 | **运行位置** | 您的进程,您的基础设施 | Anthropic 管理的基础设施 |
580 | **界面** | Python 或 TypeScript 库 | REST API |
581 | **代理工作于** | 您的基础设施上的文件 | 每个会话的托管沙箱 |
582 | **会话状态** | 您的文件系统上的 JSONL | Anthropic 托管的事件日志 |
583 | **自定义工具** | 进程内 Python 或 TypeScript 函数 | Claude 触发工具;您执行并返回结果 |
584 | **最适合** | 本地原型设计,直接在您的文件系统和服务上工作的代理 | 生产代理,无需操作沙箱或会话基础设施,长期运行和异步会话 |
585
586 一个常见的路径是先使用 Agent SDK 在本地进行原型设计,然后为生产环境迁移到 Managed Agents。
587 </Tab>
588</Tabs>
589 52
590<h2 id="changelog">53<h2 id="changelog">
591 更新日志54 更新日志
596* **TypeScript SDK**:[查看 CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md)59* **TypeScript SDK**:[查看 CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md)
597* **Python SDK**:[查看 CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md)60* **Python SDK**:[查看 CHANGELOG.md](https://github.com/anthropics/claude-agent-sdk-python/blob/main/CHANGELOG.md)
598 61
599<h2 id="reporting-bugs">62<h2 id="report-bugs">
600 报告 bug63 报告 bug
601</h2>64</h2>
602 65
613 76
614**允许:**77**允许:**
615 78
616* "Claude Agent"(首选用于下拉菜单)79* "Claude Agent",首选用于下拉菜单
617* "Claude"(当已在标记为"Agents"的菜单中时)80* "Claude",当已在标记为"Agents"的菜单中时
618* "{YourAgentName} Powered by Claude"(如果您有现有的代理名称)81* "{YourAgentName} Powered by Claude",如果您有现有的代理名称
619 82
620**不允许:**83**不允许:**
621 84
634 后续步骤97 后续步骤
635</h2>98</h2>
636 99
637<CardGroup cols={2}>100这些资源涵盖了使用 Agent SDK 构建的更深层次的技术细节和示例项目。
638 <Card title="快速入门" icon="play" href="/zh-CN/agent-sdk/quickstart">
639 构建一个在几分钟内查找和修复 bug 的代理
640 </Card>
641
642 <Card title="示例代理" icon="star" href="https://github.com/anthropics/claude-agent-sdk-demos">
643 电子邮件助手、研究代理等
644 </Card>
645
646 <Card title="TypeScript SDK" icon="code" href="/zh-CN/agent-sdk/typescript">
647 完整的 TypeScript API 参考和示例
648 </Card>
649 101
650 <Card title="Python SDK" icon="code" href="/zh-CN/agent-sdk/python">102* [快速入门](/docs/zh-CN/agent-sdk/quickstart):构建你的第一个查找和修复 bug 的代理
651 完整的 Python API 参考和示例103* [迁移指南](/docs/zh-CN/agent-sdk/migration-guide):从 Claude Code SDK 包迁移到 Agent SDK
652 </Card>104* [Agent 循环](/docs/zh-CN/agent-sdk/agent-loop):Claude 如何规划、调用工具以及决定任务何时完成
653</CardGroup>105* [示例代理](https://github.com/anthropics/claude-agent-sdk-demos):用于本地开发的演示应用
106* [TypeScript SDK](/docs/zh-CN/agent-sdk/typescript):完整的 TypeScript API 参考和示例
107* [Python SDK](/docs/zh-CN/agent-sdk/python):完整的 Python API 参考和示例
108* [Agent 工具设计](https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code):Claude Code 团队如何使用动态工作流来同时编排许多子代理