Anthropic Claude SDK
The Anthropic Python SDK calls Claude models via the Messages API. It supports streaming, tool use, vision, and structured outputs for production LLM applications.
Search across all documentation pages
The Anthropic Python SDK calls Claude models via the Messages API. It supports streaming, tool use, vision, and structured outputs for production LLM applications.
Quick-reference recipe card - copy-paste ready.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system="You are a helpful assistant.",
messages=[{"role": "user", "content": "Hello!"}],
)
print(message.content[0].text)When to reach for this:
"""anthropic_claude_sdk.py - messages, streaming, and tool use."""
from __future__ import annotations
import json
import anthropic
client = anthropic.Anthropic()
# Basic message
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=512,
system="You are a Python code reviewer. Be concise.",
messages=[{"role": "user", "content": "Review: def add(a,b): return a+b"}],
)
print(response.content[0].text)
# Streaming
print("--- streaming ---")
with client.messages.stream(
model="claude-sonnet-4-20250514",
max_tokens=256,
messages=[{"role": "user", "content": "Count from 1 to 5."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
print()
# Tool use
tools = [{
"name": "get_weather",
"description": "Get weather for a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}]
def get_weather(city: str) -> str:
return json.dumps({"city": city, "temp_f": 72, "condition": "sunny"})
msg = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Austin?"}],
)
while msg.stop_reason == "tool_use":
tool_results = []
for block in msg.content:
if block.type == "tool_use":
result = get_weather(**block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": result,
})
msg = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "What's the weather in Austin?"},
{"role": "assistant", "content": msg.content},
{"role": "user", "content": tool_results},
],
)
print(msg.content[0].text)What this demonstrates:
messages.stream and text_stream.system, messages, and optional tools.text, tool_use, tool_result, image.end_turn, tool_use, max_tokens.text_stream yields only text deltas.client.messages.count_tokens() before sending.| Model | Speed | Capability | Use |
|---|---|---|---|
| Haiku | Fastest | Basic tasks | Classification, extraction |
| Sonnet | Balanced | Strong reasoning | General applications |
| Opus | Slowest | Best quality | Complex analysis, coding |
# Async client
import asyncio
import anthropic
async def main():
client = anthropic.AsyncAnthropic()
msg = await client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=256,
messages=[{"role": "user", "content": "Hi"}],
)
print(msg.content[0].text)
asyncio.run(main())max_tokens; requests fail without it. Fix: always set max_tokens explicitly.tool_use but code does not handle it. Fix: check stop_reason and submit tool_result blocks.anthropic.Anthropic() reads ANTHROPIC_API_KEY from environment.tenacity or SDK retry config.block.type before accessing .text.| Alternative | Use When | Don't Use When |
|---|---|---|
| Anthropic SDK | Claude models | Need OpenAI ecosystem |
| OpenAI SDK | GPT models, wider tooling | Prefer Claude's safety/style |
| LiteLLM | Multi-provider abstraction | Single-provider simplicity |
| AWS Bedrock | Claude via AWS IAM | Direct API is simpler |
export ANTHROPIC_API_KEY="sk-ant-..."api_key= to the constructor.stop_reason == "tool_use", execute the tool.stop_reason == "end_turn".with client.messages.stream(...) as stream:
for text in stream.text_stream:
print(text, end=""){"role": "user", "content": [
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": b64}},
{"type": "text", "text": "What is in this image?"},
]}count = client.messages.count_tokens(
model="claude-sonnet-4-20250514",
messages=[{"role": "user", "content": "Hello"}],
)
print(count.input_tokens)import anthropic
try:
client.messages.create(...)
except anthropic.RateLimitError:
time.sleep(5) # backoff
except anthropic.APIStatusError as e:
print(e.status_code, e.message)system parameter is the dedicated system prompt.AsyncAnthropic in async route handlers.StreamingResponse for SSE to clients.claude-sonnet-4-20250514).max_tokens.Stack versions: This page was written for Python 3.14.0 (stable 3.14, maintenance 3.13), FastAPI 0.115+, Django 5.2, Flask 3.1, Pydantic 2, PyTorch 2.6+, pandas 2.2+, Polars 1.x, ruff 0.9+, and uv 0.6+.
Reviewed by Chris St. John·Last updated Jul 19, 2026