Claude Agent SDK
為什麼需要 CLAUDE AGENT SDK
- 內建工具鏈,如
Read,Write,Edit,Bash,Glob,Grep,WebSearch)。你只要給它一個方向,它自己就會在後台不斷進行「觀察環境 $\rightarrow$ 採取行動 $\rightarrow$ 驗證結果」的自主循環。 - 具備 subagent 功能,不會互相污染環境,可以並行。
- 自動化 compact contextd
Quick Start - 建立一個自動 fix bugs 的 agent
- 安裝 Claude Agent SDK
- 建立
utils.py
// utils.py
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
return total / len(numbers)
def get_user_name(user):
return user["name"].upper()
3.建立 agent.py
// agent.py
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
async def main():
# Agentic loop: streams messages as Claude works
async for message in query(
prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"], # Tools Claude can use
permission_mode="acceptEdits", # Auto-approve file edits
),
):
# Print human-readable output
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text) # Claude's reasoning
elif hasattr(block, "name"):
print(f"Tool: {block.name}") # Tool being called
elif isinstance(message, ResultMessage):
print(f"Done: {message.subtype}") # Final result
asyncio.run(main())
- 運行 agent sdk
python3 -m venv .venv && source .venv/bin/activate
pip3 install claude-agent-sdk
5. agent 自動會開始呼叫 agent sdk,並針對 utils.py 中的 bug 進行分析