anthropics/anthropic-sdk-python

3,277 stars Python 8 components

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.

  1. 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
  2. Build conversation request — User calls client.messages.create() with messages list (MessageParam), model name, max_tokens, and optional tools list (ToolParam) [MessageParam]
  3. Serialize and send HTTP request — BaseClient._request() converts Pydantic objects to JSON, adds anthropic-version and authorization headers, sends POST to /v1/messages
  4. 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
  5. Process tool calls — If Message contains ToolUseBlock content, user extracts tool calls, executes corresponding functions, creates new MessageParam with tool results [ToolUseBlock → MessageParam]
  6. 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.

MessageParam src/anthropic/types/message_param.py
dict with role: 'user'|'assistant'|'system', content: str|list[ContentBlockParam]
Created from user input, accumulated in conversation history, serialized to JSON for API calls
Message src/anthropic/types/message.py
Pydantic 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
ToolParam src/anthropic/types/tool_param.py
dict 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
StreamEvent src/anthropic/types/message_stream_event.py
Union 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
ContentBlock src/anthropic/types/content_block.py
Union 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
AgentSession src/anthropic/types/beta/session.py
Pydantic 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.

critical Contract unguarded

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')
critical Ordering unguarded

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
warning Temporal unguarded

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
warning Environment unguarded

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')
warning Domain unguarded

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
warning Resource unguarded

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
info Scale unguarded

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
warning Contract unguarded

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
info Domain unguarded

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'
info Ordering unguarded

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

Conversation history (in-memory)
List of MessageParam objects representing the conversation context, manually maintained by calling code
HTTP connection pool (cache)
httpx client maintains connection pool for reusing TCP connections to API endpoints
Agent session state (state-store)
Server-side session state for agent conversations including environment, tools, and conversation history

Feedback Loops

Delays

Control Points

Technology Stack

httpx (library)
Handles HTTP transport with connection pooling, async support, and timeout management
Pydantic (framework)
Provides data validation, serialization, and type safety for all API request/response models
typing-extensions (library)
Enables advanced type hints for better IDE support and runtime validation
anyio (runtime)
Async compatibility layer for running async code across different event loops
jiter (serialization)
Fast JSON parsing for response deserialization
pytest (testing)
Test framework with async support and fixtures for SDK testing
rich (library)
Pretty printing and terminal formatting for examples and debugging

Key Components

Explore the interactive analysis

See the full architecture map, data flow, and code patterns visualization.

Analyze on CodeSea

Related 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 .