Python SDK Basics
9 examples to get you started with the Anthropic Python SDK - 6 basic and 3 intermediate.
Prerequisites
- Python 3.8 or newer.
- An Anthropic API key, available from the Anthropic Console.
- Install the SDK:
pip install anthropic. - Set your key as an environment variable so you never hardcode it:
export ANTHROPIC_API_KEY=sk-ant-....
Basic Examples
1. Install the SDK
Add the official package to your project with pip.
pip install anthropic- Installs the
anthropicpackage and its dependencies, includinghttpxfor HTTP transport. - Pin a version in
requirements.txt(anthropic>=0.40,<1.0) for reproducible builds. - No extra system dependencies are required on a standard Python install.
2. Create a client
Construct a client once, reusing the API key from the environment.
import anthropic
client = anthropic.Anthropic()- With no arguments,
Anthropic()reads theANTHROPIC_API_KEYenvironment variable automatically. - Construct the client once at startup and reuse it for every request; do not create a new client per call.
- Pass
api_key="sk-ant-..."explicitly only when you cannot use an environment variable, for example when a key is loaded from a secrets manager at runtime.
Related: The Anthropic Python SDK Mental Model - how the client fits into the SDK's design
3. Send your first message
Call the Messages API with a model, a token limit, and a list of messages.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "In one sentence, what is a Python decorator?"}
],
)
print(message.content[0].text)modelselects which Claude model answers the request;claude-sonnet-5is a strong default for most workloads.max_tokenscaps the length of the response, not the length of your input.messagesis a list of turns; the first entry must haverole="user".
4. Read the response text
message.content is a list of content blocks, not a single string.
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Name three prime numbers."}],
)
for block in message.content:
if block.type == "text":
print(block.text)- Claude's reply can contain multiple content blocks (text, tool calls, and so on), so
contentis always a list. - Checking
block.type == "text"before reading.textavoids errors when a response contains non-text blocks. - For a simple text-only reply,
message.content[0].textis a common shortcut once you know the shape of your responses.
5. Set a system prompt
Use the system parameter to steer the model's behavior for the whole conversation.
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
system="You are a terse Python tutor. Answer in one short paragraph.",
messages=[{"role": "user", "content": "What is a generator?"}],
)
print(message.content[0].text)systemis a top-level parameter, separate frommessages, and applies to the entire request.- Use it for persona, tone, and formatting instructions rather than repeating them in every user message.
- A stable, unchanging
systemprompt is also what makes prompt caching effective later on.
6. Control max_tokens
max_tokens is a hard ceiling on the response, and hitting it truncates output.
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=100,
messages=[{"role": "user", "content": "Write a 500-word essay on Python typing."}],
)
print(message.stop_reason) # "max_tokens" if the essay was cut off
print(message.content[0].text)stop_reasontells you why generation stopped:"end_turn"for a natural finish,"max_tokens"for a truncation.- Setting
max_tokenstoo low for the task silently cuts off the answer rather than raising an error. - A common default for short-to-medium replies is 1024-4096; long-form output needs more, and above roughly 16000 you should switch to streaming (see Related).
Related: Streaming Responses with the Python SDK - avoid timeouts on large responses
Intermediate Examples
7. Multi-turn conversation
The API is stateless - you resend the full conversation history on every call.
import anthropic
client = anthropic.Anthropic()
messages = [
{"role": "user", "content": "My favorite language is Python."},
]
first = client.messages.create(model="claude-sonnet-5", max_tokens=200, messages=messages)
messages.append({"role": "assistant", "content": first.content[0].text})
messages.append({"role": "user", "content": "What did I say my favorite language was?"})
second = client.messages.create(model="claude-sonnet-5", max_tokens=200, messages=messages)
print(second.content[0].text)- Claude has no memory between calls; every prior turn you want remembered must be in the
messageslist you send. - Append the assistant's own reply back into
messagesbefore adding the next user turn, so the model sees its own prior answer. - Messages must start with
role="user"and generally alternateuser/assistant.
8. Handle errors with typed exceptions
Catch the SDK's specific exception classes instead of a single broad except.
import anthropic
client = anthropic.Anthropic()
try:
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)
except anthropic.RateLimitError:
print("Rate limited - back off and retry later.")
except anthropic.APIConnectionError:
print("Network error reaching the API.")
except anthropic.APIStatusError as e:
print(f"API returned an error: {e.status_code} {e.message}")RateLimitError,APIConnectionError, andAPIStatusErrorare distinct classes for distinct failure modes; catch the most specific one first.- The SDK already retries transient failures (network errors, 429, 5xx) automatically, so an exception here means retries were exhausted or the failure was not retryable.
- See the exception reference page for the full mapping from exception type to recommended handling.
Related: Python SDK Exception Types at a Glance - the full exception-to-strategy mapping
9. Configure timeout and retries at construction
Set client-wide defaults for how long to wait and how many times to retry.
import anthropic
client = anthropic.Anthropic(
max_retries=4,
timeout=30.0,
)
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Summarize the plot of a short story about a lighthouse."}],
)
print(message.content[0].text)max_retriescontrols how many times the SDK automatically retries a transient failure before raising; the default is 2.timeoutis in seconds for the Python SDK and applies per request unless overridden.- Use
client.with_options(...)to override either setting for a single call without changing the client's defaults.
Related: Python SDK Retry and Timeout Configuration Reference - every setting, compared side by side
Stack versions: Written against the Claude model lineup current as of ~June 2026 - Claude Fable 5, Claude Opus 4.8, Claude Sonnet 5 (the default), and Claude Haiku 4.5 - and the official
anthropicPython SDK (latest 0.x release). Model names, SDK versions, and pricing move quickly - verify current specifics at platform.claude.com/docs before relying on them.