Example code

Claude Agent SDK examples: python

Open a file to read it highlighted, with links to where the tutorial uses it.

Download all examples (zip)

NameWhat it showsUsed inSize
01_hello.pyThe simplest possible agent. One query(), read-only tools, print every message.P1 §4526 B · raw
02_fix_bugs.pyThe quickstart agent. Finds and fixes crash bugs in src/utils.py with acceptEdits.P1 §51.4 KB · raw
03_multi_turn.pyMulti-turn conversation with ClaudeSDKClient. The second turn relies on the first.P1 1.2 KB · raw
04_custom_tools.pyCustom tools via an in-process MCP server.P2 3.4 KB · raw
05_hooks.pyHooks. PreToolUse blocks writes to .env files; PostToolUse logs every tool result.P2 2.3 KB · raw
06_structured_output.pyStructured output validated against a Pydantic schema.P1 1.6 KB · raw
07_streaming.pyToken-level streaming with include_partial_messages.P1 1.6 KB · raw
08_subagents.pyProgrammatic subagents with AgentDefinition, plus SubagentStart/Stop hooks.P2 §42.5 KB · raw
09_sessions.pySessions: capture an ID, resume it, fork it, and inspect it on disk.P2 §52.0 KB · raw
10_permissions.pyRuntime approval with can_use_tool. Allows file creation, denies deletion, rewrites paths.P2 2.6 KB · raw
11_checkpointing.pyFile checkpointing: let the agent edit a file, then rewind it.P3 §11.8 KB · raw
12_interrupt.pyInterrupt a running turn, drain it, then send a new one.P1 1.5 KB · raw
13_introspection.pyIntrospection: init metadata, context usage, MCP status, server info, dynamic model switch.P3 §32.4 KB · raw
14_errors.pyError handling: max_turns and max_budget_usd limits, ResultError, bad CLI path.P1 1.5 KB · raw
15_skills_and_prompts.pySkills (dispatch /security-check), CLAUDE.md loading, and system prompt variants.P2 §62.9 KB · raw
16_cost_tracking.pyCost and usage: per-step usage deduplicated by message_id, result totals, cache tokens.P3 §22.0 KB · raw
17_streaming_input.pyStreaming input mode via an async generator, plus /compact and ConversationReset via /clear.P1 1.7 KB · raw
18_otel_capture.pyObservability. Run a tiny OTLP/HTTP receiver on localhost, point the agent at it,P3 §44.6 KB · raw
19_sqlite_session_store.pyA custom SessionStore backed by SQLite, validated with the SDK's conformance suite,P3 §5.16.3 KB · raw
20_multi_tenant.pyMulti-tenant isolation. Two tenants in one process: separate cwd, separate config dir, no shared settings or memory.P3 §5.24.0 KB · raw
21_sandbox_and_stderr.pySandbox settings on a host WITHOUT bubblewrap: failIfUnavailable=True stops the run with a clearP3 §61.6 KB · raw
22_concurrency_sizing.pyCapacity planning. Run N sessions concurrently and measure the peak memory of the claude subprocesses.P3 §5.32.4 KB · raw
demo_util.pyShared helpers for the demo scripts: a compact message printer.P1 §42.7 KB · raw
p1_goal_loop.pyA goal-based loop. A Stop hook refuses to let the agent stop until aP4 §4.42.7 KB · raw
p1b_goal_loop_blocked.pySame loop, but the goal has a criterion the prompt never mentioned, so the first stop is blocked. A Stop hook refuses to let the agent stop until aP4 §4.43.2 KB · raw
p2_graph_pipeline.pyA code-owned graph. Your program is the orchestrator; each node is a query().P4 §7.34.2 KB · raw
p3_workflow_patterns.pyThe classic workflow patterns as code: routing, prompt chaining with a gate, and voting.P4 §33.6 KB · raw
p4_handoff.pyHandoffs. Control AND the conversation move between specialists; a router in code decides who's next.P4 §7.63.1 KB · raw
p5_debate.pyA supervised swarm. Peers investigate competing hypotheses, share a blackboard, and a judge decides.P4 §7.64.0 KB · raw
p6_agentic_rag.pyAgentic RAG. Retrieval is a tool the agent calls as often as it likes; the answer must cite sources.P4 §6.24.4 KB · raw
p7_deferred_approval.pyDeferred approval. A PreToolUse hook pauses the run at a risky command; the process ends withP4 §103.6 KB · raw
p8_eval_gate.pyHarness-as-code. An end-state eval that scores a CLAUDE.md change before you ship it.P4 §51.9 KB · raw
p9_circuit_breaker.pyA circuit breaker on a goal loop. Part of the verifier's condition depends on somethingP4 §4.52.9 KB · raw