SPB Git

Repository Public

python.md 26.0 KB 779 lines markdown

1---2title: Python SDK3url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python4description: Install and configure the Anthropic Python SDK with sync and async client support5---67The 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.89<Info>10  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.11</Info>1213## Installation1415```bash16pip install anthropic17```1819For platform-specific integrations or improved async performance, install with extras:2021```bash22# For Amazon Bedrock support23pip install "anthropic[bedrock]"2425# For Google Cloud support26pip install "anthropic[vertex]"2728# For Claude Platform on AWS support29pip install "anthropic[aws]"3031# Microsoft Foundry support is included in the base package3233# For improved async performance with aiohttp34pip install "anthropic[aiohttp]"35```3637## Requirements3839Python 3.10 or later is required. If you are upgrading from a 0.x release of the SDK, see the [v1 migration guide](https://github.com/anthropics/anthropic-sdk-python/blob/main/MIGRATION.md) for the list of breaking changes.4041## Usage4243```python44import os45from anthropic import Anthropic4647client = Anthropic(48    # This is the default and can be omitted49    api_key=os.environ.get("ANTHROPIC_API_KEY"),50)5152message = client.messages.create(53    max_tokens=1024,54    messages=[55        {56            "role": "user",57            "content": "Hello, Claude",58        }59    ],60    model="claude-opus-5",61)6263for block in message.content:64    if block.type == "text":65        print(block.text)66```6768<Tip>69  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.70</Tip>7172For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) with access to multiple workspaces, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK.7374## Async usage7576```python77import os78import asyncio79from anthropic import AsyncAnthropic8081client = AsyncAnthropic(82    api_key=os.environ.get("ANTHROPIC_API_KEY"),83)848586async def main() -> None:87    message = await client.messages.create(88        max_tokens=1024,89        messages=[90            {91                "role": "user",92                "content": "Hello, Claude",93            }94        ],95        model="claude-opus-5",96    )97    print(message.content)9899100asyncio.run(main())101```102103### Using aiohttp for better concurrency104105For improved async performance, you can use the `aiohttp` HTTP backend instead of the default `httpx2`:106107```python108import os109import asyncio110from anthropic import AsyncAnthropic, DefaultAioHttpClient111112113async def main() -> None:114    async with AsyncAnthropic(115        api_key=os.environ.get("ANTHROPIC_API_KEY"),116        http_client=DefaultAioHttpClient(),117    ) as client:118        message = await client.messages.create(119            max_tokens=1024,120            messages=[121                {122                    "role": "user",123                    "content": "Hello, Claude",124                }125            ],126            model="claude-opus-5",127        )128        print(message.content)129130131asyncio.run(main())132```133134## Streaming responses135136The SDK provides support for streaming responses using Server-Sent Events (SSE).137138```python139client = Anthropic()140141stream = client.messages.create(142    max_tokens=1024,143    messages=[144        {145            "role": "user",146            "content": "Hello, Claude",147        }148    ],149    model="claude-opus-5",150    stream=True,151)152for event in stream:153    print(event.type)154```155156The async client uses the exact same interface:157158```python159client = AsyncAnthropic()160161stream = await client.messages.create(162    max_tokens=1024,163    messages=[164        {165            "role": "user",166            "content": "Hello, Claude",167        }168    ],169    model="claude-opus-5",170    stream=True,171)172async for event in stream:173    print(event.type)174```175176### Streaming helpers177178The SDK also provides streaming helpers that use context managers and provide access to the accumulated text and the final message:179180```python181async def main() -> None:182    async with client.messages.stream(183        max_tokens=1024,184        messages=[185            {186                "role": "user",187                "content": "Say hello there!",188            }189        ],190        model="claude-opus-5",191    ) as stream:192        async for text in stream.text_stream:193            print(text, end="", flush=True)194        print()195196        message = await stream.get_final_message()197        print(message.to_json())198199200asyncio.run(main())201```202203Streaming with `client.messages.stream(...)` exposes various helpers including accumulation and SDK-specific events.204205Alternatively, 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).206207## Token counting208209You can see the exact usage for a given request through the `usage` response property:210211```python212message = client.messages.create(...)213print(message.usage)214# Usage(input_tokens=25, output_tokens=13)215```216217You can also count tokens before making a request:218219```python220count = client.messages.count_tokens(221    model="claude-opus-5", messages=[{"role": "user", "content": "Hello, world"}]222)223print(count.input_tokens)  # 10224```225226## Tool use227228This 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).229230### Tool helpers231232The 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:233234```python235import json236from anthropic import Anthropic, beta_tool237238client = Anthropic()239240241@beta_tool242def get_weather(location: str) -> str:243    """Get the weather for a given location.244245    Args:246        location: The city and state, for example, San Francisco, CA247    Returns:248        A JSON-encoded string with the location, temperature, and weather condition.249    """250    return json.dumps(251        {252            "location": location,253            "temperature": "68°F",254            "condition": "Sunny",255        }256    )257258259# Use the tool_runner to automatically handle tool calls260runner = client.beta.messages.tool_runner(261    max_tokens=1024,262    model="claude-opus-5",263    tools=[get_weather],264    messages=[265        {"role": "user", "content": "What is the weather in SF?"},266    ],267)268for message in runner:269    print(message)270```271272On 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.273274## Message batches275276This SDK provides support for [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) under `client.messages.batches`.277278### Creating a batch279280Message Batches takes an array of requests, where each object has a `custom_id` identifier and the same request `params` as the standard Messages API:281282```python283client.messages.batches.create(284    requests=[285        {286            "custom_id": "my-first-request",287            "params": {288                "model": "claude-opus-5",289                "max_tokens": 1024,290                "messages": [{"role": "user", "content": "Hello, world"}],291            },292        },293        {294            "custom_id": "my-second-request",295            "params": {296                "model": "claude-opus-5",297                "max_tokens": 1024,298                "messages": [{"role": "user", "content": "Hi again, friend"}],299            },300        },301    ]302)303```304305### Getting results from a batch306307Once a Message Batch has been processed, indicated by `.processing_status == 'ended'`, you can access the results with `.batches.results()`:308309```python310client = anthropic.Anthropic()311batch_id = "batch_abc123"312result_stream = client.messages.batches.results(batch_id)313for entry in result_stream:314    if entry.result.type == "succeeded":315        print(entry.result.message.content)316```317318## File uploads319320Request parameters that correspond to file uploads can be passed in many different forms:321322* A `PathLike` object (for example, `pathlib.Path`)323* A tuple of `(filename, content, content_type)`324* A `BinaryIO` file-like object325326```python327from pathlib import Path328from anthropic import Anthropic329330client = Anthropic()331332# Upload using a file path333client.files.upload(334    file=Path("/path/to/file"),335)336337# Upload using bytes338client.files.upload(339    file=("file.txt", b"my bytes", "text/plain"),340)341```342343The async client uses the exact same interface. If you pass a `PathLike` instance, the file contents are read asynchronously automatically.344345## Handling errors346347When the library is unable to connect to the API, or if the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of `APIError` is raised:348349```python350import anthropic351# ...352try:353    message = client.messages.create(354        max_tokens=1024,355        messages=[356            {357                "role": "user",358                "content": "Hello, Claude",359            }360        ],361        model="claude-opus-5",362    )363except anthropic.APIConnectionError as e:364    print("The server could not be reached")365    print(e.__cause__)  # an underlying Exception, likely raised within httpx2366except anthropic.RateLimitError as e:367    print("A 429 status code was received; we should back off a bit.")368except anthropic.APIStatusError as e:369    print("Another non-200-range status code was received")370    print(e.status_code)371    print(e.response)372```373374Error codes are as follows:375376| Status code | Error type                 |377| ----------- | -------------------------- |378| 400         | `BadRequestError`          |379| 401         | `AuthenticationError`      |380| 403         | `PermissionDeniedError`    |381| 404         | `NotFoundError`            |382| 409         | `ConflictError`            |383| 422         | `UnprocessableEntityError` |384| 429         | `RateLimitError`           |385| >=500       | `InternalServerError`      |386| N/A         | `APIConnectionError`       |387388## Request IDs389390> For more information on debugging requests, see [Request ID](https://platform.claude.com/docs/en/api/errors#request-id).391392All object responses in the SDK provide a `_request_id` property which is added from the `request-id` response header so that you can quickly log failing requests and report them back to Anthropic.393394```python395message = client.messages.create(396    max_tokens=1024,397    messages=[{"role": "user", "content": "Hello, Claude"}],398    model="claude-opus-5",399)400print(message._request_id)  # e.g., req_018EeWyXxfu5pfWkrYcMdjWG401```402403<Note>404  Unlike other properties that use an `_` prefix, the `_request_id` property is public. Unless documented otherwise, all other `_` prefix properties, methods, and modules are private.405</Note>406407## Retries408409Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, because of a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default.410411You can use the `max_retries` option to configure or disable this:412413```python414# Configure the default for all requests:415client = Anthropic(416    max_retries=0,  # default is 2417)418419# Or, configure per-request:420client.with_options(max_retries=5).messages.create(421    max_tokens=1024,422    messages=[{"role": "user", "content": "Hello, Claude"}],423    model="claude-opus-5",424)425```426427## Timeouts428429By default requests time out after 10 minutes. You can configure this with a `timeout` option, which accepts a float or an `httpx2.Timeout` object:430431```python432import httpx2433from anthropic import Anthropic434435# Configure the default for all requests:436client = Anthropic(437    timeout=20.0,  # 20 seconds (default is 10 minutes)438)439440# More granular control:441client = Anthropic(442    timeout=httpx2.Timeout(60.0, read=5.0, write=10.0, connect=2.0),443)444445# Override per-request:446client.with_options(timeout=5.0).messages.create(447    max_tokens=1024,448    messages=[{"role": "user", "content": "Hello, Claude"}],449    model="claude-opus-5",450)451```452453On timeout, the SDK throws an `APITimeoutError`.454455Note that requests that time out are [retried twice by default](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python#retries).456457## Long requests458459<Warning>460  Consider using the streaming [Messages API](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python#streaming-responses) for longer running requests.461</Warning>462463Avoid setting a large `max_tokens` value without using streaming. Some networks may drop idle connections after a certain period of time, which can cause the request to fail or [timeout](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python#timeouts) without receiving a response from Anthropic.464465The SDK will throw a `ValueError` if a non-streaming request is expected to take longer than approximately 10 minutes. Passing `stream=True` or overriding the `timeout` option at the client or request level disables this error.466467An expected request latency longer than the [timeout](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python#timeouts) for a non-streaming request will result in the client terminating the connection and retrying without receiving a response.468469The SDK sets a [TCP socket keep-alive](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) option to reduce the impact of idle connection timeouts on some networks. This can be overridden by passing a custom `http_client` option to the client.470471## Auto-pagination472473List methods in the Claude API are paginated. You can use the `for` syntax to iterate through items across all pages:474475```python476client = Anthropic()477478all_batches = []479# Automatically fetches more pages as needed.480for batch in client.messages.batches.list(limit=20):481    all_batches.append(batch)482print(all_batches)483```484485For async iteration:486487```python488async def main() -> None:489    all_batches = []490    async for batch in client.messages.batches.list(limit=20):491        all_batches.append(batch)492    print(all_batches)493494495asyncio.run(main())496```497498Alternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages:499500```python501first_page = await client.messages.batches.list(limit=20)502503if first_page.has_next_page():504    print(f"will fetch next page using these details: {first_page.next_page_info()}")505    next_page = await first_page.get_next_page()506    print(f"number of items we just fetched: {len(next_page.data)}")507508# Remove `await` for non-async usage.509```510511Or work directly with the returned data:512513```python514first_page = await client.messages.batches.list(limit=20)515516print(f"next page cursor: {first_page.last_id}")517for batch in first_page.data:518    print(batch.id)519520# Remove `await` for non-async usage.521```522523## Default headers524525The SDK automatically sends the `anthropic-version` header set to `2023-06-01`.526527If you need to, you can override it by setting default headers on the client object or per-request.528529<Warning>530  Overriding default headers may result in incorrect types and other unexpected or undefined behavior in the SDK.531</Warning>532533```python534# Set default headers for all requests on the client535client = Anthropic(536    default_headers={"anthropic-version": "My-Custom-Value"},537)538539# Or override per-request540client.messages.with_raw_response.create(541    max_tokens=1024,542    messages=[{"role": "user", "content": "Hello, Claude"}],543    model="claude-opus-5",544    extra_headers={"anthropic-version": "My-Custom-Value"},545)546```547548## Type system549550### Request parameters551552Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev) which also have helper methods for things like serializing back into JSON ([`v1`](https://docs.pydantic.dev/1.10/usage/models/), [`v2`](https://docs.pydantic.dev/latest/concepts/serialization/)).553554Typed requests and responses provide autocomplete and documentation within your editor. If you'd like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.555556### Response models557558To convert a Pydantic model to a dictionary, use the helper methods:559560```python561message = client.messages.create(...)562563# Convert to JSON string564json_str = message.to_json()565566# Convert to dictionary567data = message.to_dict()568```569570### Handling null vs missing fields571572In responses, you can distinguish between fields that are explicitly `null` versus fields that were not returned (missing):573574```python575response = client.messages.create(576    model="claude-opus-5",577    max_tokens=1024,578    messages=[{"role": "user", "content": "Hello"}],579)580if response.my_field is None:581    if "my_field" not in response.model_fields_set:582        print("field was not in the response")583    else:584        print("field was null")585```586587## Advanced usage588589### Accessing raw response data (for example, headers)590591The "raw" `Response` returned by `httpx2` can be accessed through the `.with_raw_response` property on the client. This is useful for accessing response headers or other metadata:592593```python594client = Anthropic()595596response = client.messages.with_raw_response.create(597    max_tokens=1024,598    messages=[{"role": "user", "content": "Hello, Claude"}],599    model="claude-opus-5",600)601602print(response.headers.get("request-id"))603message = (604    response.parse()605)  # get the object that `messages.create()` would have returned606print(message.content)607```608609These methods return an `APIResponse` object. On the async client they return an `AsyncAPIResponse`, and `.parse()`, `.read()`, `.text()`, and `.json()` must be awaited.610611### Streaming response body612613The `.with_raw_response` approach eagerly reads the full response body when you make the request. To stream the response body instead, use `.with_streaming_response`, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()`, or `.parse()`. In the async client, these are async methods.614615```python616with client.messages.with_streaming_response.create(617    max_tokens=1024,618    messages=[{"role": "user", "content": "Hello, Claude"}],619    model="claude-opus-5",620) as response:621    print(response.headers.get("request-id"))622623    for line in response.iter_lines():624        print(line)625```626627The context manager is required so that the response will reliably be closed.628629### Logging630631The SDK uses the standard library `logging` module.632633You can enable logging by setting the environment variable `ANTHROPIC_LOG` to `debug` or `info`:634635```bash636export ANTHROPIC_LOG=debug637```638639### Making custom/undocumented requests640641This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.642643#### Undocumented endpoints644645To make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs. Options on the client, such as retries, are respected when making these requests.646647```python648import httpx2649650response = client.post(651    "/foo",652    cast_to=httpx2.Response,653    body={"my_param": True},654)655656print(response.json())657```658659#### Undocumented request params660661If you want to explicitly send an extra parameter, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request options.662663<Warning>664  The `extra_` parameters override documented parameters of the same name. For security reasons, ensure these methods are only used with trusted input data.665</Warning>666667#### Undocumented response properties668669To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You can also get all extra fields on the Pydantic model as a dict with `response.model_extra`.670671### Configuring the HTTP client672673The SDK sends requests with [httpx2](https://httpx2.pydantic.dev), an API-compatible fork of `httpx`. To customize the HTTP client, including proxies and transports, pass your own [httpx2 client](https://httpx2.pydantic.dev/api/#client) as `http_client`:674675```python676import httpx2677from anthropic import Anthropic, DefaultHttpxClient678679client = Anthropic(680    # Or use the `ANTHROPIC_BASE_URL` env var681    base_url="http://my.test.server.example.com:8083",682    http_client=DefaultHttpxClient(683        proxy="http://my.test.proxy.example.com",684        transport=httpx2.HTTPTransport(local_address="0.0.0.0"),685    ),686)687```688689You can also customize the client on a per-request basis by using `with_options()`:690691```python692client.with_options(http_client=DefaultHttpxClient(...))693```694695<Note>696  Use `DefaultHttpxClient` and `DefaultAsyncHttpxClient` instead of raw `httpx2.Client` and `httpx2.AsyncClient` to ensure the SDK's default configuration (such as timeouts and connection limits) is preserved. The `http_client` argument must be an `httpx2` client. Passing a client from the separate `httpx` package raises a `TypeError`.697</Note>698699Tracing and mocking tools that patch `httpx` itself, such as OpenTelemetry's `HTTPXClientInstrumentor`, Sentry's `httpx` integration, `respx`, or `pytest-httpx`, do not see the SDK's requests by default. To use them, call `httpx2.alias_httpx()` once at startup, before anything imports `httpx`. This makes `import httpx` resolve to `httpx2` for the whole process.700701### Managing HTTP resources702703By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.704705```python706with Anthropic() as client:707    message = client.messages.create(...)708709# HTTP client is automatically closed710```711712## Beta features713714Beta features are available before general release to get early feedback and test new functionality. You can check the availability of all of Claude's capabilities and tools in the [build with Claude overview](https://platform.claude.com/docs/en/build-with-claude/overview).715716You can access most beta API features through the `beta` property of the client. To enable a particular beta feature, you need to add the appropriate [beta header](https://platform.claude.com/docs/en/api/beta-headers) to the `betas` field when creating a message.717718For example, to enable [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing):719720```python721client = Anthropic()722723response = client.beta.messages.create(724    model="claude-opus-5",725    max_tokens=1024,726    messages=[{"role": "user", "content": "Hello, Claude"}],727    betas=["context-management-2025-06-27"],728)729```730731## Platform integrations732733<Note>734  For detailed platform setup guides with code examples, see:735736  * [Amazon Bedrock](https://platform.claude.com/docs/en/build-with-claude/claude-in-amazon-bedrock)737  * [Amazon Bedrock (Opus 4.6 and earlier)](https://platform.claude.com/docs/en/build-with-claude/claude-on-amazon-bedrock-legacy)738  * [Claude Platform on AWS](https://platform.claude.com/docs/en/build-with-claude/claude-platform-on-aws)739  * [Google Cloud](https://platform.claude.com/docs/en/build-with-claude/claude-on-vertex-ai)740  * [Microsoft Foundry](https://platform.claude.com/docs/en/build-with-claude/claude-in-microsoft-foundry)741</Note>742743All five client classes are included in the base `anthropic` package:744745| Provider                         | Client                                         | Extra dependencies                 |746| -------------------------------- | ---------------------------------------------- | ---------------------------------- |747| Agent Platform                   | `from anthropic import AnthropicVertex`        | `pip install "anthropic[vertex]"`  |748| Bedrock                          | `from anthropic import AnthropicBedrockMantle` | `pip install "anthropic[bedrock]"` |749| Bedrock (`bedrock-runtime` path) | `from anthropic import AnthropicBedrock`       | `pip install "anthropic[bedrock]"` |750| Claude Platform on AWS           | `from anthropic import AnthropicAWS`           | `pip install "anthropic[aws]"`     |751| Foundry                          | `from anthropic import AnthropicFoundry`       | None                               |752753The `AnthropicAWS` client is in beta. Pass `workspace_id` to the constructor or set the `ANTHROPIC_AWS_WORKSPACE_ID` environment variable.754755Use `AnthropicBedrockMantle` for new projects; `AnthropicBedrock` remains for existing applications using the Bedrock `InvokeModel` API.756757## Semantic versioning758759This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backward-incompatible changes may be released as minor versions:7607611. Changes that only affect static types, without breaking runtime behavior.7622. Changes to library internals which are technically public but not intended or documented for external use.7633. Changes that aren't expected to impact the vast majority of users in practice.764765### Determining the installed version766767If you've upgraded to the latest version but aren't seeing new features you were expecting, your Python environment is likely still using an older version. You can determine the version being used at runtime with:768769```python770print(anthropic.__version__)771```772773## Additional resources774775* [GitHub repository](https://github.com/anthropics/anthropic-sdk-python)776* [API reference](https://platform.claude.com/docs/en/api/overview)777* [Streaming Messages](https://platform.claude.com/docs/en/build-with-claude/streaming)778* [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview)779
Files main
Menu

Theme