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-TW/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-TW/agent-sdk/quickstart">
44 在幾分鐘內構建一個除錯代理
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 建立並啟動虛擬環境,然後安裝套件。安裝到虛擬環境可避免在最近的 Debian、Ubuntu 和 Homebrew 安裝上執行 `pip install` 時系統 Python 返回的 `error: externally-managed-environment` 失敗。
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's Agent Platform**:設定 `CLAUDE_CODE_USE_VERTEX=1` 環境變數並配置 Google Cloud 認證
124 * **Microsoft Azure**:設定 `CLAUDE_CODE_USE_FOUNDRY=1` 環境變數並配置 Azure 認證
125
126 有關詳細資訊,請參閱 [Amazon Bedrock](/zh-TW/amazon-bedrock)、[Claude Platform on AWS](/zh-TW/claude-platform-on-aws)、[Google Cloud's Agent Platform](/zh-TW/google-vertex-ai) 或 [Microsoft Foundry](/zh-TW/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-TW/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>24SDK 僅作為 Python 和 TypeScript 的庫提供。若要從另一種語言驅動相同的代理迴圈,請[以子程序的形式運行 CLI](/docs/zh-TW/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-TW/agent-sdk/quickstart)在幾分鐘內建立一個尋找和修復錯誤的代理。
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-TW/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-TW/agent-sdk/hooks)
291 </Tab>
292
293 <Tab title="子代理">
294 生成專門的代理來處理集中的子任務。您的主代理委派工作,子代理報告結果。
295 31
296 定義具有專門指令的自訂代理。子代理透過 Agent 工具呼叫,因此在 `allowedTools` 中包含 `Agent` 以自動批准這些呼叫:32| 功能 | 功能說明 | 深入了解 |
33| ------------ | ------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
34| 內建工具 | 讀取、寫入、編輯檔案、執行命令和搜尋網路 | [工具參考](/docs/zh-TW/tools-reference) |
35| Hooks | 在代理生命週期的關鍵點執行自訂程式碼 | [Hooks](/docs/zh-TW/agent-sdk/hooks) |
36| 子代理 | 生成專門的代理來處理集中的子任務 | [子代理](/docs/zh-TW/agent-sdk/subagents) |
37| MCP | 透過 Model Context Protocol 連接外部工具和資料來源 | [MCP](/docs/zh-TW/agent-sdk/mcp) |
38| 權限 | 控制哪些工具自動執行、哪些需要批准 | [權限](/docs/zh-TW/agent-sdk/permissions) |
39| 工作階段 | 在多次交換中保持上下文、稍後恢復或分叉 | [工作階段](/docs/zh-TW/agent-sdk/sessions) |
40| Skills、命令和記憶 | 從您的專案的 `.claude/` 和 `~/.claude/` 自動載入,與 Claude Code 相同 | [Skills](/docs/zh-TW/agent-sdk/skills)、[命令](/docs/zh-TW/agent-sdk/skills#commands-in-agent-sdk-sessions)、[記憶](/docs/zh-TW/agent-sdk/modifying-system-prompts)、[設定載入](/docs/zh-TW/agent-sdk/claude-code-features) |
41| Plugins | 封裝 skills、代理、hooks 和 MCP 伺服器,並按本機路徑載入 | [Plugins](/docs/zh-TW/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-TW/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-TW/agent-sdk/mcp)
395 </Tab>
396
397 <Tab title="權限">
398 精確控制您的代理可以使用哪些工具。允許安全操作、阻止危險操作或要求對敏感操作進行批准。
399
400 <Note>
401 有關互動式批准提示和 `AskUserQuestion` 工具,請參閱[處理批准和使用者輸入](/zh-TW/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-TW/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-TW/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-TW/agent-sdk/skills) | Claude 自動使用或您使用 `/name` 呼叫的專門功能 | `.claude/skills/*/SKILL.md` |
515| [Commands](/zh-TW/agent-sdk/slash-commands) | 舊版格式的自訂命令。新的自訂命令請使用 skills | `.claude/commands/*.md` |
516| [Memory](/zh-TW/agent-sdk/modifying-system-prompts) | 專案上下文和指令 | `CLAUDE.md` 或 `.claude/CLAUDE.md` |
517| [Plugins](/zh-TW/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-TW/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-TW/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-TW/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-TW/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 報告錯誤63 報告錯誤
601</h2>64</h2>
602 65
634 後續步驟97 後續步驟
635</h2>98</h2>
636 99
637<CardGroup cols={2}>100這些資源涵蓋了使用 Agent SDK 構建的更深入的技術細節和範例專案。
638 <Card title="快速入門" icon="play" href="/zh-TW/agent-sdk/quickstart">
639 構建在幾分鐘內尋找和修復錯誤的代理
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-TW/agent-sdk/typescript">
647 完整的 TypeScript API 參考和範例
648 </Card>
649 101
650 <Card title="Python SDK" icon="code" href="/zh-TW/agent-sdk/python">102* [快速入門](/docs/zh-TW/agent-sdk/quickstart):構建您的第一個代理,用於尋找和修復錯誤
651 完整的 Python API 參考和範例103* [遷移指南](/docs/zh-TW/agent-sdk/migration-guide):從 Claude Code SDK 套件遷移到 Agent SDK
652 </Card>104* [代理迴圈](/docs/zh-TW/agent-sdk/agent-loop):Claude 如何規劃、呼叫工具以及決定何時任務完成
653</CardGroup>105* [範例代理](https://github.com/anthropics/claude-agent-sdk-demos):用於本地開發的示範應用程式
106* [TypeScript SDK](/docs/zh-TW/agent-sdk/typescript):完整的 TypeScript API 參考和範例
107* [Python SDK](/docs/zh-TW/agent-sdk/python):完整的 Python API 參考和範例
108* [Agent harness 設計](https://claude.com/blog/a-harness-for-every-task-dynamic-workflows-in-claude-code):Claude Code 團隊如何使用動態工作流程來同時協調許多子代理