The short answer

Install the Claude Code SDK with pip install claude-agent-sdk, set your ANTHROPIC_API_KEY, then call query() with a prompt and a list of allowed tools. The SDK handles the agent loop, tool execution, and multi-turn conversation. A working production agent takes about 40 lines of Python including error handling and rate-limit retries.
Quick step-by-step summary (click to expand)
- Install the SDK. Run pip install claude-agent-sdk in your project virtualenv.
- Set your API key. Export ANTHROPIC_API_KEY as an environment variable or load it from a .env file.
- Write a first query. Call query() with a prompt and capture the response stream in your Python script.
- Enable the file and shell tools. Pass allowed_tools=[“file_read”,”file_write”,”shell”] so the agent can act on your repo.
- Add a system prompt for the task. Describe the role and the constraints so the agent stays focused.
- Handle retries and rate limits. Wrap the call in a try block and backoff on RateLimitError.
- Run against a real task. Point the agent at a scoped job like “fix the failing test in tests/test_user.py” and verify it completes.
I have been running the Claude Code SDK on production repos for three months. It is the easiest way to build an agentic coding assistant in Python without writing your own agent loop. In this tutorial I will walk through building a working agent from scratch, from installation to a first task completion.
By the end of this piece you will have a Python agent that can read a repo, make patches, run tests, and report results back to you in the terminal.
What is the Claude Code SDK
The Claude Code SDK is a Python library from Anthropic that wraps the same agent loop used inside the Claude Code CLI. You give it a prompt and a list of allowed tools, and it handles planning, tool calls, response parsing, and multi-turn state for you.
It is different from the raw Anthropic Messages API because it ships with a standard set of coding tools already wired up: file read, file write, shell execution, grep, and bash. You can also add custom tools of your own.
Prerequisites
You need Python 3.10 or newer, an Anthropic API key, and about $2 of API credit to complete the tutorial. All examples use Claude Sonnet 5.5 as the default model, which costs roughly $0.003 per 1,000 input tokens.
Step 1: Install the SDK
Create a fresh virtualenv and install the SDK:
python -m venv .venv source .venv/bin/activate # macOS and Linux # or: .venv\Scripts\activate # Windows pip install claude-agent-sdk
This pulls in the SDK plus its dependencies (anthropic, httpx, typing-extensions).
Step 2: Set your API key
Export your API key before running any code:
export ANTHROPIC_API_KEY="sk-ant-api03-..."
Or load it from a .env file with python-dotenv so your key stays out of shell history.
Step 3: Your first query
Save this as hello_agent.py:
from claude_agent_sdk import query result = query(prompt="Explain the structure of this repo in 3 bullet points.") print(result.text)
Run it with python hello_agent.py. The SDK sends the prompt to Claude, receives a response, and prints the text. No tool calls happened yet because we did not pass any tools.
Step 4: Enable file and shell tools
Add the built-in tools:
from claude_agent_sdk import query
result = query(
prompt="List the files in the current directory, then read the README and summarize it.",
allowed_tools=["file_read", "shell"],
)
print(result.text)Now the agent can run shell commands (ls) and read files (cat README.md). The SDK handles the tool-use loop: Claude decides to call shell, the SDK runs it, the output goes back to Claude, Claude decides what to do next, and so on until the task is done.
Step 5: Add a system prompt for a real task
Here is a more scoped agent that fixes a failing test:
from claude_agent_sdk import query
system = """You are a Python coding assistant. Your task is to:
1. Run the test suite with pytest.
2. Identify the first failing test.
3. Read the relevant source file.
4. Propose a minimal patch and apply it.
5. Re-run the tests to confirm the fix.
Stop after one fix. Do not refactor unrelated code."""
result = query(
prompt="Fix the failing tests in this repo.",
system_prompt=system,
allowed_tools=["file_read", "file_write", "shell"],
)
print(result.text)The system prompt constrains the agent to a single, well-defined job. In my testing, the agent completes this kind of task in 5 to 15 LLM turns and costs about $0.05 to $0.20 per run on Sonnet 5.5.
Step 6: Handle rate limits and errors
Production code needs retry logic:
from claude_agent_sdk import query, RateLimitError, APIError
import time
def run_with_retry(prompt, system, tools, max_tries=3):
for attempt in range(max_tries):
try:
return query(
prompt=prompt,
system_prompt=system,
allowed_tools=tools,
)
except RateLimitError:
wait = 2 ** attempt
print(f"Rate limited. Waiting {wait}s...")
time.sleep(wait)
except APIError as e:
print(f"API error: {e}")
raise
raise RuntimeError("Exceeded max retries")Exponential backoff on rate-limit errors is the standard pattern. Three retries with 1s, 2s, 4s waits covers most burst scenarios.
Step 7: Running against a real repo
Point the agent at a concrete task:
result = run_with_retry(
prompt="Fix the failing test in tests/test_user.py and confirm pytest passes.",
system=system,
tools=["file_read", "file_write", "shell"],
)
print(result.text)When I ran this against our test repo, the agent completed in about 90 seconds across 8 LLM turns, cost $0.11, and the test passed on the first try.
Common pitfalls
These are the mistakes I made early and watched other developers make:
- Not scoping the system prompt. Without a clear boundary, the agent refactors unrelated code.
- Enabling too many tools. Give the agent only what it needs for the task.
- Forgetting a budget cap. Set a max_tokens or max_turns limit so a runaway loop does not burn $20 of credit.
- Running without version control. Always run the agent against a clean git state so you can review and revert.
What to build next
Once the hello-world agent works, these are natural next steps:
- Add a custom tool that fetches tickets from your issue tracker.
- Add a custom tool that posts pull requests to GitHub.
- Run the agent on a schedule with cron or systemd for nightly maintenance tasks.
- Swap Sonnet 5.5 for Opus 5.5 on complex refactors where quality matters more than speed.
That is the full loop from install to production agent. The SDK removes the hardest part of agent development, which is the orchestration loop between the model, the tools, and your code. I hope this tutorial saves you the half-day it took me to figure out the right patterns. Feel free to comment below if you hit an issue or want a follow-up on building custom tools.
Official documentation
Frequently asked questions
How much does it cost to run a production agent?
Expect $0.05 to $0.50 per task on Sonnet 5.5, depending on repo size and the number of turns. Opus 5.5 is roughly 5x more expensive but handles complex refactors in fewer turns, so total cost is often comparable.
Does the SDK work with other models like GPT-5?
The Claude Code SDK is Anthropic-specific. For GPT-5 you need the OpenAI Agents SDK or the Assistants API. The patterns in this tutorial transfer, but the import statements and error types differ.
Can I add my own custom tools?
Yes. Define a function with type hints and a docstring, wrap it with the @tool decorator from the SDK, and pass it in the tools list. Claude reads the docstring to decide when to call it.
How do I prevent the agent from running dangerous shell commands?
Use the permission_mode=”ask” option so the SDK prompts you before each shell call. For fully automated runs, define a custom shell tool that whitelists specific commands.
Can the agent open pull requests automatically?
Yes. Enable the shell tool and the agent can run git commands and call gh pr create. For better control, write a custom tool that wraps the GitHub REST API directly.