Claude Agent SDK Tutorial: Build Your First Production Agent in Python
28 de abril de 2026
Claude Agent SDK Tutorial: Build Your First Production Agent in Python
The Claude Agent SDK gives you the same agent loop that powers Claude Code — fully programmable in Python. If you’ve ever wanted to ship an autonomous agent that reads files, calls APIs, and reasons across multiple steps without you babysitting each one, this is the SDK you’ve been waiting for.
I’ve been running Paperclip — a production multi-agent system where specialized AI agents coordinate tasks, write code, review PRs, and publish content — all built on top of this SDK. In this tutorial I’ll show you how to go from zero to a working production agent in about 30 minutes, plus the patterns I’ve learned from running it in production.
What Is the Claude Agent SDK?
First, let’s clear up the confusion. There are two different Claude Python libraries:
| | Anthropic Python SDK | Claude Agent SDK |
|---|---|---|
| Package | anthropic | claude-agent-sdk |
| What it does | Direct API access — you manage the loop | Full agent loop — the SDK drives execution |
| Use case | Simple API calls, custom orchestration | Autonomous tasks, multi-step execution |
| Tool handling | Manual | Automatic |
| Streaming | Optional | Built-in |
The Anthropic SDK is a raw API client. You send a message, you get a response, you decide what happens next. The Claude Agent SDK wraps the full agentic loop: the model runs, calls tools, processes results, and continues until the task is done.
Think of it this way: the Anthropic SDK is like having a direct line to a consultant. The Agent SDK is like hiring that consultant to complete a project autonomously.
Two main entry points
The SDK exposes two ways to run agents:
query() — Run a single task to completion. Fire-and-forget style. Great for batch jobs, one-shot automation, and tasks that don’t need conversational state.
ClaudeSDKClient — An async context manager for multi-turn conversations. Use this for user-facing agents, interactive sessions, or when you need to maintain state across exchanges.
Setup and Authentication
pip install claude-agent-sdkSet your API key:
export ANTHROPIC_API_KEY="sk-ant-..."Or pass it programmatically:
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."Your first query() call — working in 5 minutes:
# first_agent.py
import asyncio
from claude_agent_sdk import query
async def main():
async for message in query(
prompt="List the 3 most important things to know about Python asyncio",
system="You are a senior Python developer. Be direct and practical."
):
if hasattr(message, 'text'):
print(message.text, end="", flush=True)
asyncio.run(main())Run it:
python first_agent.pyThat’s the agent loop running. The SDK handles the back-and-forth with the model internally — you just consume the output stream.
Your First Agent: Single Task Automation
Let’s build something real. An agent that reads a directory of log files, identifies error patterns, and outputs a structured report.
# log_analyzer.py
import asyncio
import json
from pathlib import Path
from claude_agent_sdk import query
from claude_agent_sdk.types import ToolUseBlock, ToolResultBlock
TOOLS = [
{
"name": "read_file",
"description": "Read the contents of a file. Use this to inspect log files.",
"input_schema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Absolute path to the file"
}
},
"required": ["path"]
}
},
{
"name": "list_directory",
"description": "List files in a directory",
"input_schema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Directory path to list"
},
"pattern": {
"type": "string",
"description": "Glob pattern, e.g. '*.log'"
}
},
"required": ["path"]
}
}
]
def handle_tool_call(tool_name: str, tool_input: dict) -> str:
if tool_name == "read_file":
path = Path(tool_input["path"])
if not path.exists():
return f"Error: file not found at {path}"
return path.read_text()
if tool_name == "list_directory":
path = Path(tool_input["path"])
pattern = tool_input.get("pattern", "*")
files = list(path.glob(pattern))
return json.dumps([str(f) for f in files])
return f"Unknown tool: {tool_name}"
async def analyze_logs(log_dir: str) -> str:
result_parts = []
async for message in query(
prompt=f"""
Analyze the log files in {log_dir}.
1. List all .log files in that directory
2. Read each one
3. Identify the top 3 error patterns
4. Return a JSON report with: {{errors: [...], frequency: [...], recommendation: "..."}}
""",
system="You are a production systems engineer. Be precise. Return only valid JSON at the end.",
tools=TOOLS,
tool_handler=handle_tool_call
):
if hasattr(message, 'text') and message.text:
result_parts.append(message.text)
return "".join(result_parts)
if __name__ == "__main__":
result = asyncio.run(analyze_logs("/var/log/app"))
print(result)The key thing here: tool_handler is a callback the SDK invokes automatically when the model wants to call a tool. You write the execution logic, the SDK handles the orchestration loop.
Common mistakes
Don’t return None from tool handlers. If a tool fails silently, the model keeps trying and burns tokens. Always return a string — even if it’s an error message.
Don’t put all your instructions in the prompt. Context engineering matters here — more on this in the production patterns section.
Don’t assume the agent runs fast. For tasks with 5+ tool calls, budget for 30–60 seconds. Design your UX accordingly.
Multi-Turn Conversations with ClaudeSDKClient
query() is stateless. Each call starts fresh. When you need the agent to remember previous exchanges — like a customer support agent that tracks what the user already asked — use ClaudeSDKClient.
# support_agent.py
import asyncio
from claude_agent_sdk import ClaudeSDKClient
SYSTEM = """
You are a support agent for DevFellowship, a developer education platform.
You help fellows with technical questions, learning path decisions, and project blockers.
Be direct. Ask one clarifying question at a time. Don't over-explain.
"""
async def run_support_session():
async with ClaudeSDKClient() as client:
print("DevFellowship Support Agent — type 'quit' to exit
")
while True:
user_input = input("You: ").strip()
if user_input.lower() in ("quit", "exit"):
break
print("Agent: ", end="", flush=True)
async for message in client.process_query(
prompt=user_input,
system=SYSTEM
):
if hasattr(message, 'text') and message.text:
print(message.text, end="", flush=True)
print("
")
asyncio.run(run_support_session())ClaudeSDKClient maintains the conversation thread internally across calls. The model has full context of the conversation history when generating each response.
When to use which
| Scenario | Use |
|---|---|
| Process a batch of files | query() |
| Run a nightly data pipeline | query() |
| User-facing chatbot | ClaudeSDKClient |
| Interactive CLI tool | ClaudeSDKClient |
| One-shot code review | query() |
| Multi-step project planning | ClaudeSDKClient |
Custom Tools: Making Your Agent Useful
Tools are where agents become genuinely useful. A tool is a function the model can decide to call. You define the interface; the model decides when and how to call it.
Here’s a tool schema from Paperclip’s production codebase (simplified):
PAPERCLIP_TOOLS = [
{
"name": "get_issue",
"description": """Fetch a task/issue by its identifier (e.g. TAI-77).
Returns the full issue including title, description, status, comments.
Use this when you need context on a specific task before working on it.""",
"input_schema": {
"type": "object",
"properties": {
"identifier": {
"type": "string",
"description": "Issue identifier like TAI-77 or DEV-42"
}
},
"required": ["identifier"]
}
},
{
"name": "update_issue_status",
"description": """Update the status of an issue and optionally post a comment.
Valid statuses: todo, in_progress, in_review, blocked, done.
Always include a comment explaining the status change.""",
"input_schema": {
"type": "object",
"properties": {
"identifier": {"type": "string"},
"status": {
"type": "string",
"enum": ["todo", "in_progress", "in_review", "blocked", "done"]
},
"comment": {
"type": "string",
"description": "Required. Explain why the status changed."
}
},
"required": ["identifier", "status", "comment"]
}
}
]Tool design best practices from production
1. Descriptions are instructions, not labels. The model reads tool descriptions to decide which tool to call and what inputs to pass. “Read a file” is bad. “Read the contents of a file at the given path. Returns raw text. Use this before editing.” is better.
2. Use enums for constrained choices. If a field only accepts specific values, define them as an enum. The model will follow this — saving you validation errors downstream.
3. Make tools atomic. One tool, one thing. Avoid “do this AND that” tools. Composability beats convenience here.
4. Return useful error context. When a tool fails, return a string like "Error: Issue TAI-99 not found. Valid identifiers follow the pattern PREFIX-NUMBER" — not just "Not found". The model uses error messages to self-correct.
Error handling pattern
async def handle_tool(name: str, inputs: dict) -> str:
try:
if name == "get_issue":
issue = await api.get_issue(inputs["identifier"])
if not issue:
return f"Issue {inputs['identifier']} not found. Check the identifier format."
return json.dumps(issue)
return f"Unknown tool: {name}"
except Exception as e:
# Return the error as text — don't raise
# The agent will retry or adapt its approach
return f"Tool error ({name}): {str(e)}"Never let exceptions propagate from your tool handler. Return errors as strings. The agent loop will handle them gracefully.
Production Patterns from Paperclip
I’ve been running a multi-agent system (Paperclip) where agents check out tasks, do the work, post updates, and hand off to other agents. Here’s what I’ve learned about running Claude agents in production.
Pattern 1: System prompt vs tool description — what goes where
This is the biggest context engineering mistake I see. People pack everything into the system prompt and write minimal tool descriptions.
Put in the system prompt:
- Who the agent is and what it’s responsible for
- Global rules and constraints (never do X, always do Y)
- Decision-making frameworks
- Tone and output format
Put in tool descriptions:
- When to call this specific tool (vs alternatives)
- What the output looks like
- Edge cases specific to that tool
- Pre-conditions to check before calling
In Paperclip, each agent has a SOUL.md (voice/personality) and TOOLS.md (tool reference docs) loaded separately. The system prompt stays focused on identity; tools carry their own instructions.
Pattern 2: Task routing between agents
Paperclip runs specialized agents: a writer agent, a researcher agent, an SEO agent. Instead of one generalist agent, each is tuned for its domain.
The routing pattern:
AGENT_REGISTRY = {
"content": ContentWriterAgent,
"research": ResearchAgent,
"seo": SEOAgent,
}
async def route_task(task: dict) -> str:
# Determine which agent should handle this task type
async for message in query(
prompt=f"Task: {task['title']}
Description: {task['description']}
Which agent type should handle this: content, research, or seo?",
system="Return only one word: content, research, or seo."
):
if hasattr(message, 'text'):
agent_type = message.text.strip().lower()
if agent_type in AGENT_REGISTRY:
return await AGENT_REGISTRY[agent_type]().run(task)
raise ValueError("Could not determine agent type")Simple but effective. The routing agent is cheap and fast; the specialized agents do the heavy lifting.
Pattern 3: Avoiding context overflow in long-running agents
Long-running agents accumulate context fast — especially when reading files or processing large outputs. In production I’ve hit two failure modes:
Tool output explosion: Agent reads a 50K-token log file. Context fills up. Model starts hallucinating or truncating.
Fix: Summarize or chunk tool outputs before returning them.
async def read_file_chunked(path: str, max_chars: int = 8000) -> str:
content = Path(path).read_text()
if len(content) <= max_chars:
return content
# Return first chunk with a note about truncation
return content[:max_chars] + f"
[Truncated. File has {len(content)} chars total. Request specific sections if needed.]"History bloat: Multi-turn agent keeps a growing conversation history. After 20 turns, the early context is just noise.
Fix with ClaudeSDKClient: Use the max_turns parameter and reset sessions periodically. Or summarize the conversation state into a compact handoff context.
Pattern 4: Observability
In production you need to know what your agents are doing. Wire up structured logging around your tool handler:
import logging
import time
logger = logging.getLogger("agent.tools")
async def handle_tool_with_logging(name: str, inputs: dict) -> str:
start = time.time()
try:
result = await handle_tool(name, inputs)
logger.info({
"tool": name,
"inputs": inputs,
"duration_ms": int((time.time() - start) * 1000),
"success": True,
"output_len": len(result)
})
return result
except Exception as e:
logger.error({"tool": name, "error": str(e)})
return f"Error: {str(e)}"This gives you a trace of every tool call per agent run. In Paperclip we ship these to Langfuse for observability — you can see exactly what each agent decided, what tools it called, and where it slowed down.
Next Steps
You now have the core patterns to build production-grade agents. Here’s where to go deeper:
Connect your agent to MCP servers. The Model Context Protocol lets you give your agent access to external systems — databases, APIs, file systems — through a standardized interface. I wrote a full tutorial: [MCP Server Tutorial →]
Context engineering deep dive. How you structure your system prompt, tool descriptions, and input framing matters more than model size. Getting this right is the difference between an agent that works 70% of the time and one that works 97% of the time. [Context Engineering for Agents →]
Multi-agent orchestration. Once you have multiple specialized agents, you need patterns for routing, handoffs, and shared state. Paperclip is a real production example of this — I’ll be writing a deep-dive on [production multi-agent patterns →] soon.
If you’re building something with the Claude Agent SDK, I’d genuinely like to hear about it. What patterns are you running into? What’s breaking? Find me on X — I’m building in public.
Thanks,
Tainan Fidelis.
