anthropics/anthropic-sdk-python
HTTP client that formats Python function calls as Claude API requests
User creates client with API key, calls client.messages.create() with MessageParam list and optional ToolParam list. The client serializes this to JSON, sends HTTP POST to Claude API with auth headers, receives either complete JSON response or streaming server-sent events. For streaming, events are parsed and accumulated into final Message. Tool calls in response trigger function execution, results are sent back as new messages.
Under the hood, the system uses 3 feedback loops, 3 data pools, 4 control points to manage its runtime behavior.
A 8-component library. 849 files analyzed. Data flows through 6 distinct pipeline stages.
How Data Flows Through the System
User creates client with API key, calls client.messages.create() with MessageParam list and optional ToolParam list. The client serializes this to JSON, sends HTTP POST to Claude API with auth headers, receives either complete JSON response or streaming server-sent events. For streaming, events are parsed and accumulated into final Message. Tool calls in response trigger function execution, results are sent back as new messages.
- Initialize client with credentials — Anthropic() constructor reads API key from environment or parameter, sets up httpx client with base URL, auth headers, and timeout configs
- Build conversation request — User calls client.messages.create() with messages list (MessageParam), model name, max_tokens, and optional tools list (ToolParam) [MessageParam]
- Serialize and send HTTP request — BaseClient._request() converts Pydantic objects to JSON, adds anthropic-version and authorization headers, sends POST to /v1/messages
- Parse API response — For non-streaming: JSON response is deserialized into Message object with content blocks. For streaming: server-sent events are parsed by JSONStreamParser into StreamEvent objects
- Process tool calls — If Message contains ToolUseBlock content, user extracts tool calls, executes corresponding functions, creates new MessageParam with tool results [ToolUseBlock → MessageParam]
- Handle streaming accumulation — MessageStream processes ContentBlockDeltaEvent objects, accumulates text and tool call data, produces final Message when stream completes [StreamEvent → Message]
Data Models
The data structures that flow between stages — the contracts that hold the system together.
src/anthropic/types/message_param.pydict with role: 'user'|'assistant'|'system', content: str|list[ContentBlockParam]
Created from user input, accumulated in conversation history, serialized to JSON for API calls
src/anthropic/types/message.pyPydantic model with id: str, role: 'assistant', content: list[ContentBlock], model: str, usage: Usage, stop_reason: str
Deserialized from API JSON response, content blocks extracted for text/tool results, returned to calling code
src/anthropic/types/tool_param.pydict with name: str, description: str, input_schema: JSONSchema dict defining parameters
Defined by user as function schemas, sent to Claude for tool selection, referenced when Claude chooses to call tools
src/anthropic/types/message_stream_event.pyUnion of event types: MessageStartEvent, ContentBlockStartEvent, ContentBlockDeltaEvent, etc., each with type: str and event-specific data
Parsed from server-sent events during streaming, processed by MessageStream to accumulate final message
src/anthropic/types/content_block.pyUnion of TextBlock(type='text', text: str), ToolUseBlock(type='tool_use', id: str, name: str, input: dict), ImageBlock, etc.
Created from API response content, used to extract text or execute tool calls, may be modified for follow-up requests
src/anthropic/types/beta/session.pyPydantic model with id: str, environment_id: str, agent: dict, status: 'active'|'idle'|'errored', expires_at: datetime
Created via sessions.create(), used to send user events and receive agent responses, expires after timeout
Hidden Assumptions
Things this code relies on but never validates. These are the things that cause silent failures when the system changes.
The API response always contains at least one tool_use content block when stop_reason is 'tool_use', and next() will find it
If this fails: StopIteration exception crashes the program if Claude returns stop_reason='tool_use' but no actual tool_use blocks in content
examples/tools.py:next(c for c in message.content if c.type == 'tool_use')
The response object from messages.create() can be directly used as MessageParam content without any transformation or validation
If this fails: If the API response structure changes or contains fields that aren't valid in MessageParam, subsequent API calls fail with serialization errors
examples/messages.py:response.role and response.content
Agent sessions are immediately ready for events after creation - no startup delay or async initialization required
If this fails: Events sent too quickly after session creation could be lost or cause session errors if the backend hasn't finished initializing
examples/agents.py:session creation and immediate use
The ANTHROPIC_API_KEY environment variable is always a valid, non-expired API key when present
If this fails: Authentication failures result in HTTP 401 errors rather than clear 'invalid key' messages, making debugging harder
examples/agents.py:os.environ.get('ANTHROPIC_API_KEY')
Tool input schemas follow exact JSON Schema format that Claude expects - any deviation in nested properties, types, or required fields is handled gracefully
If this fails: Malformed schemas cause Claude to refuse tool calls or generate invalid tool parameters that crash user functions
examples/tools.py:input_schema object structure
The streaming session will eventually go idle and terminate the event loop naturally
If this fails: If a session never goes idle due to server issues, the client code hangs indefinitely with no timeout mechanism
examples/agents.py:streaming events without timeout
1024 tokens is sufficient for any response, including complex tool calls or long explanations
If this fails: Response truncation causes incomplete tool calls or cut-off explanations, breaking conversation flow
examples/messages.py:max_tokens=1024
Tool execution always produces serializable results that can be converted to string content for the API
If this fails: Complex objects, binary data, or exceptions from tool functions cause JSON serialization failures when building follow-up messages
examples/tools.py:tool result message construction
The specified model version exists and supports agent functionality - no validation of model availability or capabilities
If this fails: API returns unclear errors if model doesn't exist or doesn't support agents, making troubleshooting difficult
examples/agents.py:agent model='claude-sonnet-4-6'
Messages can be appended to conversation history in any order as long as roles alternate properly
If this fails: If API response contains system-level metadata or unexpected role values, the conversation structure becomes invalid for subsequent calls
examples/messages.py:conversation building with response.role and response.content
System Behavior
How the system operates at runtime — where data accumulates, what loops, what waits, and what controls what.
Data Pools
List of MessageParam objects representing the conversation context, manually maintained by calling code
httpx client maintains connection pool for reusing TCP connections to API endpoints
Server-side session state for agent conversations including environment, tools, and conversation history
Feedback Loops
- Tool calling loop (recursive, reinforcing) — Trigger: Message contains ToolUseBlock content. Action: User executes tool function, creates MessageParam with tool result, sends new request to continue conversation. Exit: Message has no tool calls or user chooses to stop.
- HTTP retry with exponential backoff (retry, balancing) — Trigger: HTTP request fails with retryable status code (429, 502, 503, 504). Action: BaseClient waits with exponential backoff then retries request. Exit: Request succeeds or max retries exceeded.
- Agent event streaming (polling, reinforcing) — Trigger: User sends events to agent session. Action: Server processes events and streams responses back, user can send more events. Exit: Session goes idle or errors.
Delays
- HTTP request timeout (rate-limit, ~600 seconds default) — Requests fail if API takes longer than timeout to respond
- Streaming response buffering (async-processing) — Stream events arrive incrementally as server generates response
- Agent session idle timeout (scheduled-job, ~varies by session config) — Sessions automatically expire after idle period
Control Points
- ANTHROPIC_API_KEY (env-var) — Controls: Authentication for all API requests
- max_tokens (hyperparameter) — Controls: Maximum tokens in generated response. Default: 1024 in examples
- stream parameter (runtime-toggle) — Controls: Whether to use streaming or complete response mode. Default: false by default
- model parameter (architecture-switch) — Controls: Which Claude model variant to use (claude-sonnet-4-5, claude-haiku-4-5, etc). Default: claude-sonnet-4-5-20250929 in examples
Technology Stack
Handles HTTP transport with connection pooling, async support, and timeout management
Provides data validation, serialization, and type safety for all API request/response models
Enables advanced type hints for better IDE support and runtime validation
Async compatibility layer for running async code across different event loops
Fast JSON parsing for response deserialization
Test framework with async support and fixtures for SDK testing
Pretty printing and terminal formatting for examples and debugging
Key Components
- Anthropic (gateway) — Main synchronous client that configures authentication, base URL, and HTTP transport, then exposes resource modules for API access
src/anthropic/_client.py - Messages (adapter) — Handles message creation, streaming, and parsing - converts MessageParam lists to API requests and Message responses back to Python objects
src/anthropic/resources/messages.py - MessageStream (processor) — Processes server-sent events from streaming endpoints, accumulates partial content into final Message objects, handles tool call coordination
src/anthropic/lib/_stream.py - BaseClient (executor) — HTTP transport abstraction that handles auth headers, request serialization, response deserialization, error handling, and retry logic
src/anthropic/_base_client.py - beta_tool (transformer) — Decorator that converts Python functions to ToolParam schemas by inspecting signatures and docstrings, enabling function calling with Claude
src/anthropic/tools.py - Sessions (orchestrator) — Manages agent sessions - creates sessions with environment/agent configs, sends user events, streams agent responses
src/anthropic/resources/beta/sessions/sessions.py - JSONStreamParser (decoder) — Parses server-sent event streams, extracts JSON data from event lines, handles connection errors and timeouts
src/anthropic/_streaming.py - BetaLocalFilesystemMemoryTool (adapter) — Provides persistent memory for agents by storing/retrieving memories from local filesystem, implements memory commands like store/search/delete
src/anthropic/tools/beta/memory.py
Explore the interactive analysis
See the full architecture map, data flow, and code patterns visualization.
Analyze on CodeSeaRelated Library Repositories
Frequently Asked Questions
What is anthropic-sdk-python used for?
HTTP client that formats Python function calls as Claude API requests anthropics/anthropic-sdk-python is a 8-component library written in Python. Data flows through 6 distinct pipeline stages. The codebase contains 849 files.
How is anthropic-sdk-python architected?
anthropic-sdk-python is organized into 5 architecture layers: Client Layer, Resource Layer, Type System, Transport Layer, and 1 more. Data flows through 6 distinct pipeline stages. This layered structure keeps concerns separated and modules independent.
How does data flow through anthropic-sdk-python?
Data moves through 6 stages: Initialize client with credentials → Build conversation request → Serialize and send HTTP request → Parse API response → Process tool calls → .... User creates client with API key, calls client.messages.create() with MessageParam list and optional ToolParam list. The client serializes this to JSON, sends HTTP POST to Claude API with auth headers, receives either complete JSON response or streaming server-sent events. For streaming, events are parsed and accumulated into final Message. Tool calls in response trigger function execution, results are sent back as new messages. This pipeline design reflects a complex multi-stage processing system.
What technologies does anthropic-sdk-python use?
The core stack includes httpx (Handles HTTP transport with connection pooling, async support, and timeout management), Pydantic (Provides data validation, serialization, and type safety for all API request/response models), typing-extensions (Enables advanced type hints for better IDE support and runtime validation), anyio (Async compatibility layer for running async code across different event loops), jiter (Fast JSON parsing for response deserialization), pytest (Test framework with async support and fixtures for SDK testing), and 1 more. A focused set of dependencies that keeps the build manageable.
What system dynamics does anthropic-sdk-python have?
anthropic-sdk-python exhibits 3 data pools (Conversation history, HTTP connection pool), 3 feedback loops, 4 control points, 3 delays. The feedback loops handle recursive and retry. These runtime behaviors shape how the system responds to load, failures, and configuration changes.
What design patterns does anthropic-sdk-python use?
5 design patterns detected: Resource-based API organization, Sync/Async client mirroring, Streaming with context managers, Tool calling protocol, Pydantic model validation.
Analyzed on April 20, 2026 by CodeSea. Written by Karolina Sarna.