The Anthropic Python SDK is the official library for calling Claude from Python applications. It handles authentication, request formatting, error handling, and retry logic, so you write a few lines of Python rather than hand-crafting HTTP requests to the messages API. This guide covers installation, making your first call, streaming, tool use, batch processing, and error handling — everything you need to go from zero to production with the Anthropic SDK.
Installation and Setup
Install the Anthropic SDK with pip: pip install anthropic. The SDK requires Python 3.9 or later. For async support with aiohttp, install with pip install "anthropic[aiohttp]". If you are using Amazon Bedrock to access Claude, install with pip install "anthropic[bedrock]". If you are using Google Vertex AI, install with pip install "anthropic[vertex]".
Set your API key as the environment variable ANTHROPIC_API_KEY. The client reads it automatically when no api_key argument is passed. Never hardcode the key in source code — use python-dotenv to load it from a .env file in development and an environment variable or secrets manager in production.
Your First API Call
The core of the SDK is the client.messages.create() method. Create a client, call the method with a model name and a messages list, and iterate over the content blocks in the response. The model argument accepts the current Claude model identifiers — check docs.claude.com for the latest model strings. The messages list follows the same format as the raw API: a list of dicts with role (“user” or “assistant”) and content (a string or a list of content blocks).
Figure 1 — Anthropic SDK: key client methods
Streaming Responses
For interactive applications where you want to display text as it generates, use the streaming context manager. Call client.messages.stream() as a context manager, then iterate over text_stream to get each token as a string as it arrives. The stream manager also provides get_final_message() to retrieve the complete response object with all metadata (input tokens, output tokens, stop reason) after the stream completes. Streaming dramatically improves perceived responsiveness in chat applications — the user sees the first word within a second rather than waiting for the entire response to complete.
Async Client
For applications that handle many concurrent requests — web servers, async pipelines — use the AsyncAnthropic client. Import AsyncAnthropic instead of Anthropic, use await with the same method calls, and run everything inside an async function. The async client is compatible with asyncio, FastAPI, and any other async Python framework. For async streaming, use async with client.messages.stream() and async for text in stream.text_stream. The async client supports the same methods and parameters as the sync client — switching between them is a one-line change.
Tool Use (Function Calling)
Tool use lets Claude call functions you define and return their results back to the model as part of a multi-turn conversation. Define tools as a list of dicts, each with a name, description, and input_schema (a JSON Schema object describing the parameters). Pass the tools list to messages.create(). When Claude decides to call a tool, the response contains a tool_use content block with the tool name and input parameters. Execute the tool, create a new user message with a tool_result content block containing the result, and send the updated conversation back to the API. The SDK provides helpers that simplify this loop — check the beta_tool import for function decorator support that automatically generates the schema from Python type annotations.
Batch Processing
The Message Batches API processes up to 10,000 requests asynchronously at 50% cost reduction compared to real-time calls. Construct a list of request objects with a custom_id and a params dict matching the messages.create() signature. Call client.messages.batches.create(requests=batch_list) to submit. The batch completes within 24 hours but typically in minutes for most sizes. Poll client.messages.batches.retrieve(batch_id) to check status, or use client.messages.batches.results(batch_id) when complete to stream the results. Match results to requests via the custom_id field. Batch processing is ideal for offline enrichment, classification at scale, and any non-latency-sensitive workload.
Error Handling
The SDK raises typed exceptions for different error conditions. anthropic.APIConnectionError covers network failures. anthropic.RateLimitError (HTTP 429) means you have hit the rate limit — the SDK retries automatically with exponential backoff up to a configurable max (default 2 retries). anthropic.APIStatusError covers other HTTP errors with the status_code and response available on the exception. Wrap your API calls in try-except blocks that handle these specifically. For production applications, add structured logging of APIStatusError exceptions including the request_id property from the response, which you need to include in any support request to Anthropic.
Prompt Caching
Prompt caching significantly reduces cost and latency for applications that send the same large context with every request — a long system prompt, a set of reference documents, or a shared conversation history. Mark the cacheable portion of your system prompt or messages with a cache_control block: add {type: “text”, text: “…”, cache_control: {type: “ephemeral”}} as the content block to cache. Cached content is stored for 5 minutes (extendable) and does not count toward input token cost for cache hits. The response includes cache_creation_input_tokens (tokens written to cache, billed once) and cache_read_input_tokens (tokens read from cache, billed at 10% of normal input token cost). For applications that prepend 10,000+ tokens of context to every request, prompt caching can reduce per-request cost by 80% or more.
Frequently Asked Questions
- What models are available through the Python SDK?
- The SDK supports all current Claude models. Model identifier strings change with new releases — always check docs.claude.com/en/docs/about-claude/models for the current model names and their context window sizes rather than hardcoding model strings from memory.
- Is the SDK compatible with the OpenAI Python library interface?
- Partially. Anthropic provides an OpenAI-compatible endpoint at api.anthropic.com/v1 that accepts requests in OpenAI Chat Completions format, so code written for the OpenAI SDK can call Claude with minimal changes. For full Anthropic feature access (prompt caching, extended thinking, batch processing), use the native Anthropic SDK.
- How do I handle rate limits in production?
- The SDK retries rate limit errors automatically with backoff. For high-throughput applications, implement client-side token counting (client.messages.count_tokens()) to pre-check requests against your rate limits, and use the Message Batches API for non-latency-sensitive volume to stay within real-time limits.
Last updated: October 2026. For the latest SDK documentation and model names, see docs.claude.com.
Extended Thinking
Claude’s extended thinking capability lets the model reason through complex problems before producing its final answer. Enable it by adding thinking: {type: ‘enabled’, budget_tokens: N} to your messages.create() call, where budget_tokens is the maximum tokens the model can spend on internal reasoning (minimum 1,024). The response content blocks include both thinking blocks (the model’s internal reasoning, which you can read but typically don’t show to end users) and text blocks (the final answer). Extended thinking improves accuracy significantly on complex reasoning tasks — mathematics, multi-step logic, code analysis — at the cost of higher token usage and latency. It is available on Claude Sonnet 4.6 and above. For tasks where answer quality matters more than speed, extended thinking with a budget of 8,000-16,000 tokens produces noticeably better results on difficult problems.
Token Counting and Cost Estimation
The client.messages.count_tokens() method returns the exact token count for a request without sending it to the model. This is useful for pre-validating that a request fits within the model’s context window, for estimating cost before submitting a batch, and for implementing token budgeting in applications that need to stay under a limit. Call it with the same arguments as messages.create() (model, messages, system, tools) and it returns a usage object with input_tokens. Combine this with the official pricing from docs.claude.com to calculate exact cost estimates per request type before committing to a production volume.
The Anthropic Python SDK is designed to be minimal and opinionated — it handles the request lifecycle so you focus on what to send and what to do with the response. The progression from first call to streaming to tool use to batch processing maps directly to increasingly sophisticated application patterns, and the SDK’s consistent interface across all of these makes the learning curve shallow. Start with a simple messages.create() call, add streaming when you need responsiveness, add tool use when the task requires external data or actions, and move to batch processing when volume and cost become constraints.
Organising SDK Code in a Real Project
Create the client once in a single module and import it everywhere, so timeouts, retries, and the API key are configured in one place. Always set max_tokens explicitly, since the messages endpoint requires it, and keep long prompts in separate text files rather than inline strings so they can be reviewed and versioned like code. Log the request ID from every response, and wrap calls in a small helper that records latency and token usage. When you later add caching, batching, or a second model, those changes then touch one file instead of dozens of scattered call sites.