## Installation ## Requirements ## Usage ## Async usage ### Using aiohttp for better concurrency ## Streaming responses ### Streaming helpers ## Token counting ## Tool use ### Tool helpers ## Message batches ### Creating a batch ### Getting results from a batch ## File uploads ## Handling errors ## Request IDs ## Retries ## Timeouts ## Long requests ## Auto-pagination ## Default headers ## Type system ### Request parameters ### Response models ### Handling null vs missing fields ## Advanced usage ### Accessing raw response data (for example, headers) ### Streaming response body ### Logging ### Making custom/undocumented requests #### Undocumented endpoints #### Undocumented request params #### Undocumented response properties ### Configuring the HTTP client ### Managing HTTP resources ## Beta features ## Platform integrations ## Semantic versioning ### Determining the installed version ## Additional resources
The whole hunk
790 lines, first recordedThe first capture of this source. The page was already there, and this is what it said.
---
title: Python SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python
description: Install and configure the Anthropic Python SDK with sync and async client support
---
The Anthropic Python SDK provides convenient access to the Claude API from Python applications. It supports both synchronous and asynchronous operations, streaming, and integrations with Amazon Bedrock, Claude Platform on AWS, Google Cloud, and Microsoft Foundry.
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers Python-specific SDK features and configuration.
</Info>
## Installation
```bash
pip install anthropic
```
For platform-specific integrations or improved async performance, install with extras:
```bash
# For Amazon Bedrock support
pip install "anthropic[bedrock]"
# For Google Cloud support
pip install "anthropic[vertex]"
# For Claude Platform on AWS support
pip install "anthropic[aws]"
# Microsoft Foundry support is included in the base package
# For improved async performance with aiohttp
pip install "anthropic[aiohttp]"
```
## Requirements
Python 3.9 or later is required.
## Usage
```python
import os
from anthropic import Anthropic
client = Anthropic(
# This is the default and can be omitted
api_key=os.environ.get("ANTHROPIC_API_KEY"),
)
message = client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
)
for block in message.content:
if block.type == "text":
print(block.text)
```
<Tip>
Consider using [python-dotenv](https://pypi.org/project/python-dotenv/) to add `ANTHROPIC_API_KEY="my-anthropic-api-key"` to your `.env` file so that your API key isn't stored in source control.
</Tip>
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
## Async usage
```python
import os
import asyncio
from anthropic import AsyncAnthropic
client = AsyncAnthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY"),
)
async def main() -> None:
message = await client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
)
print(message.content)
asyncio.run(main())
```
### Using aiohttp for better concurrency
For improved async performance, you can use the `aiohttp` HTTP backend instead of the default `httpx`:
```python
import os
import asyncio
from anthropic import AsyncAnthropic, DefaultAioHttpClient
async def main() -> None:
async with AsyncAnthropic(
api_key=os.environ.get("ANTHROPIC_API_KEY"),
http_client=DefaultAioHttpClient(),
) as client:
message = await client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
)
print(message.content)
asyncio.run(main())
```
## Streaming responses
The SDK provides support for streaming responses using Server-Sent Events (SSE).
```python
client = Anthropic()
stream = client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
stream=True,
)
for event in stream:
print(event.type)
```
The async client uses the exact same interface:
```python
client = AsyncAnthropic()
stream = await client.messages.create(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Hello, Claude",
}
],
model="claude-opus-5",
stream=True,
)
async for event in stream:
print(event.type)
```
### Streaming helpers
The SDK also provides streaming helpers that use context managers and provide access to the accumulated text and the final message:
```python
async def main() -> None:
async with client.messages.stream(
max_tokens=1024,
messages=[
{
"role": "user",
"content": "Say hello there!",
}
],
model="claude-opus-5",
) as stream:
async for text in stream.text_stream:
print(text, end="", flush=True)
print()
message = await stream.get_final_message()
print(message.to_json())
asyncio.run(main())
```
Streaming with `client.messages.stream(...)` exposes various helpers including accumulation and SDK-specific events.
Alternatively, you can use `client.messages.create(..., stream=True)` which only returns an iterable of the events in the stream and uses less memory (it doesn't build up a final message object for you).
## Token counting
You can see the exact usage for a given request through the `usage` response property:
```python
message = client.messages.create(...)
print(message.usage)
# Usage(input_tokens=25, output_tokens=13)
```
You can also count tokens before making a request:
```python
count = client.messages.count_tokens(
model="claude-opus-5", messages=[{"role": "user", "content": "Hello, world"}]
)
print(count.input_tokens) # 10
```
## Tool use
This SDK provides support for tool use, also known as function calling. For more details, see [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
### Tool helpers
The SDK provides helpers for defining and running tools as pure Python functions. The `@beta_tool` decorator generates the tool schema from the function signature and docstring:
```python
import json
from anthropic import Anthropic, beta_tool
client = Anthropic()
@beta_tool
def get_weather(location: str) -> str:
"""Get the weather for a given location.
Args:
location: The city and state, for example, San Francisco, CA
Returns:
A JSON-encoded string with the location, temperature, and weather condition.
"""
return json.dumps(
{
"location": location,
"temperature": "68°F",
"condition": "Sunny",
}
)
# Use the tool_runner to automatically handle tool calls
runner = client.beta.messages.tool_runner(
max_tokens=1024,
model="claude-opus-5",
tools=[get_weather],
messages=[
{"role": "user", "content": "What is the weather in SF?"},
],
)
for message in runner:
print(message)
```
On every iteration, an API request is made. If the response includes a call to one of the given tools, the tool is automatically called, and the result is returned directly to the model in the next iteration.
## Message batches
This SDK provides support for [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) under `client.messages.batches`.
### Creating a batch
Message Batches takes an array of requests, where each object has a `custom_id` identifier and the same request `params` as the standard Messages API:
```python
client.messages.batches.create(
requests=[
{
"custom_id": "my-first-request",
"params": {
"model": "claude-opus-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello, world"}],
},
},
{
"custom_id": "my-second-request",
"params": {
"model": "claude-opus-5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hi again, friend"}],
},
},
Cut at 300 lines. The page has the rest.