Loading lesson…
Loading lesson…
You may already have used Claude's basic API: send one message, get one reply, just like chatting. But if you want Claude to help you read files, run commands, search code, fix bugs, verify the result itself, and continue iterating, this kind of "autonomous work" is not something the basic API can do.
Claude Agent SDK is built exactly for this scenario. It packages all of Claude Code's capabilities - reading and writing files, executing commands, searching code, editing files, browsing the web - into a programmable library. You do not need to write the tool-calling loop yourself. Claude can execute tools autonomously and iterate autonomously until the task is truly completed.
One-sentence summary: the basic SDK is "you ask, it answers"; the Agent SDK is "you assign, it works."
Look at the code first, and the difference is obvious:
# Basic anthropic SDK: you must write your own loop to handle tool calls
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": "Fix the bug in auth.py"}],
tools=[...] # You must define tools yourself
)
# Claude asks to call some tool
while response.stop_reason == "tool_use":
result = your_tool_executor(response.tool_use) # You must execute it yourself
response = client.messages.create(tool_result=result, **params) # You must feed it back yourself
# Agent SDK: one block and done, Claude reads files, finds bugs, and edits code by itself
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Fix the bug in auth.py",
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
):
print(message) # Claude reads files, locates issues, and edits code by itself
The difference is clear:
| Comparison Item | Basic anthropic SDK | Claude Agent SDK |
|---|---|---|
| Tool execution | You implement it | Claude handles it |
| Tool loop | You implement it | Built-in agent loop |
| Built-in tools | None, all self-defined | Read/write files, Bash, search, and more out of the box |
| Context management | You maintain it | Auto compression and auto management |
| Best for | Chat, generation, simple tool use | Autonomously completing complex tasks |
There are many Agent frameworks on the market - LangChain, LlamaIndex, CrewAI, AutoGPT, and more. What is unique about Claude Agent SDK compared with them?
📚 For a detailed comparison, see the appendix: Mainstream Agent Framework Comparison
In short:
| Framework | Best-Fit Scenario |
|---|---|
| Claude Agent SDK | Let Claude autonomously complete coding, file operations, and command execution |
| LangChain | Build complex general AI apps with highly customized flows |
| CrewAI | Simulate multi-role collaboration scenarios (virtual teams, role-playing) |
| LlamaIndex | Build knowledge-base QA systems that connect enterprise data with LLMs |
Python needs 3.10+, and TypeScript needs Node.js 18+:
# Python
pip install claude-agent-sdk
# TypeScript
npm install @anthropic-ai/claude-agent-sdk
Just set the API key environment variable:
export ANTHROPIC_API_KEY=your-api-key
Cloud-platform authentication is also supported:
CLAUDE_CODE_USE_BEDROCK=1 + AWS credentialsCLAUDE_CODE_USE_VERTEX=1 + GCP credentialsCLAUDE_CODE_USE_FOUNDRY=1 + Azure credentialsIf you use a proxy, gateway, or self-hosted API endpoint, you can change the default API URL through the env parameter:
from claude_agent_sdk import query, ClaudeAgentOptions
async for message in query(
prompt="Hello",
options=ClaudeAgentOptions(
env={
"ANTHROPIC_BASE_URL": "https://your-proxy.example.com",
"ANTHROPIC_API_KEY": "your-api-key",
}
),
):
print(message)
ClaudeAgentOptions does not have a direct base_url parameter, but the env field can pass arbitrary environment variables into the underlying Claude Code CLI. Common environment variables:
| Environment Variable | Purpose |
|---|---|
ANTHROPIC_BASE_URL | Custom API endpoint (proxy, gateway) |
ANTHROPIC_API_KEY | API key |
ANTHROPIC_AUTH_TOKEN | Alternative auth token |
ANTHROPIC_CUSTOM_HEADERS | Custom request headers |
The Agent SDK runtime principle can be summarized in one sentence: collect context -> execute actions -> verify results -> repeat.
This is exactly how human developers work: read code first, then modify code, then run tests and check results. If it is wrong, keep iterating. Agent SDK automates this loop.
Mode 1: query() function - stateless, suitable for one-off tasks
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())
Mode 2: ClaudeSDKClient - stateful, suitable for multi-turn conversation
Use this when you need to preserve context and interact across multiple turns. For example, first ask Claude to read one module, then ask it to find all call sites of that module - in the second turn it still remembers what it read in the first turn.
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
session_id = None
# Turn 1: read the auth module
async for message in query(
prompt="Read the authentication module code",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
):
if hasattr(message, "subtype") and message.subtype == "init":
session_id = message.session_id
# Turn 2: continue based on previous context
async for message in query(
prompt="Find all places that call it",
options=ClaudeAgentOptions(resume=session_id),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
This is one of the best parts of Agent SDK - you do not need to implement any tools yourself, Claude can use them directly:
| Tool | Capability | Typical Use |
|---|---|---|
| Read | Read files | View code, read configs |
| Write | Create files | Generate new files |
| Edit | Precise file edits | Bug fixes, refactoring |
| Bash | Run terminal commands | Run tests, install dependencies, git operations |
| Glob | Pattern-based file search | **/*.py, src/**/*.ts |
| Grep | Regex content search | Find function definitions, TODOs |
| WebSearch | Search web pages | Look up docs, find approaches |
| WebFetch | Fetch web content | Read online docs |
| Task | Launch sub-agents | Parallelize sub-tasks |
Use allowed_tools to control which tools the agent can use:
# Read-only agent: can inspect but cannot modify
options = ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep"],
permission_mode="bypassPermissions"
)
# Full agent: can read, write, and execute commands
options = ClaudeAgentOptions(
allowed_tools=["Read", "Write", "Edit", "Bash", "Glob", "Grep"]
)