Anthropic Python SDK
The Anthropic Python SDK is the anthropic package that Python apps use to call Claude with the Messages API. Pointed at the Spanway gateway, the same code keeps the Messages format while the gateway checks a virtual key, applies the key's budget and rate limit, records the cost and routes the request to the deployment behind the public model name. That deployment can be Claude on Anthropic, Amazon Bedrock, Vertex AI or Azure, or a model from another provider.
A real-world scenario
A legal team runs a Python job that summarises contracts with client.messages.create. Each team member used to keep a personal Anthropic key in a .env file. The admin creates one virtual key per job, named contract-summaries, with a monthly budget, and sets the public model name claude-sonnet-5-5 in front of Claude on Bedrock in the company's own AWS account. The team changes two environment variables. The job still speaks the Messages API, the Anthropic keys are gone from laptops, and the Logs page shows every summary with its cost.
Prerequisites
- A running gateway and its address, written here as
https://gateway.example.com. - A model registered on the gateway under a public name, for example
claude-sonnet-5-5. - Python 3.10 or later and the SDK, installed with
pip install --upgrade anthropic. Both the 1.x and the 2.x releases work. The 2.x releases send a neweranthropic-versionheader, and the gateway does not check that header, so no gateway change is needed when you upgrade.
Make a key for this app
- In the Admin UI open Virtual Keys (
/ui/api-keys) and click + Create New Key. - Under Key Details, set Key Name to the app's name, such as
contract-summaries, and leave Key Type on AI APIs. - In Models, pick every public name the app calls. Add the fast tier model if the app sends quick side tasks to it, for example
claude-haiku-5-5, or those calls fail with 403 while the main calls work. - Open Optional Settings, set Max Budget (USD) and Reset Budget, for example 200 USD monthly, and Requests per minute Limit (RPM) and Tokens per minute Limit (TPM) for jobs that run unattended. Leave Tags empty unless the gateway has an Enterprise license, because key tags need one and without it the key is not created (
Only premium users can add tags to keys). The key name already keeps this tool's spend apart in Usage. - Click Create Key and copy the key. It is shown once.
The same key from the API:
curl -X POST https://gateway.example.com/key/generate \
-H "Authorization: Bearer $SPANWAY_MASTER_KEY" -H "Content-Type: application/json" \
-d '{"key_alias": "contract-summaries", "key_type": "llm_api", "models": ["claude-sonnet-5-5", "claude-haiku-5-5"], "max_budget": 200, "budget_duration": "30d", "rpm_limit": 60, "tpm_limit": 400000}'
Steps
-
Check the key and the model names. With an
anthropic-versionheader the gateway answers in the Anthropic list shape, the same oneclient.models.list()reads.curl https://gateway.example.com/v1/models -H "x-api-key: $SPANWAY_API_KEY" -H "anthropic-version: 2023-06-01" -
Set the environment variables the SDK reads.
ANTHROPIC_BASE_URLis the gateway address without/v1, because the SDK adds/v1/messagesitself.export ANTHROPIC_BASE_URL="https://gateway.example.com"export ANTHROPIC_API_KEY="sk-...your virtual key..." -
Keep
client = Anthropic()as it is, or passbase_urlandapi_keyin code. -
Use a public model name from step 1 as
model. -
Run the app once and find the request on Logs (
/ui/logs).
To send the key as Authorization: Bearer instead, set ANTHROPIC_AUTH_TOKEN or pass auth_token= and leave the API key unset. The gateway accepts both headers, so pick one. A base URL that ends in /v1 makes the SDK call /v1/v1/messages, which fails with 404. See the /v1 rule.
Configuration
import os
from anthropic import Anthropic
client = Anthropic(
base_url=os.environ.get("ANTHROPIC_BASE_URL", "https://gateway.example.com"),
api_key=os.environ["ANTHROPIC_API_KEY"],
default_headers={"x-spanway-tags": "app:contract-summaries"},
)
message = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Explain a model group in one sentence."}],
)
for block in message.content:
if block.type == "text":
print(block.text)
default_headers sends gateway headers on every request from the client, and extra_headers= does it for one call. Useful ones are x-spanway-tags, x-spanway-session-id, x-spanway-trace-id and x-spanway-timeout, all listed on calling the gateway. The async client is AsyncAnthropic with the same arguments.
Expected result
The script prints the answer, and message.usage holds the token counts the gateway recorded. To read the gateway headers, use with_raw_response:
raw = client.messages.with_raw_response.create(
model="claude-sonnet-5-5",
max_tokens=100,
messages=[{"role": "user", "content": "Hello"}],
)
print(raw.headers.get("x-spanway-call-id"), raw.headers.get("x-spanway-model-group"), raw.headers.get("x-spanway-routing-reason"))
message = raw.parse()
A run against a test gateway printed this.
77b5986f-2790-446c-b68a-846f75018520 claude-sonnet-5-5 strategy=simple-shuffle
x-spanway-call-id is the id to search for on Logs. x-spanway-model-id names the deployment that answered, x-spanway-attempts counts provider calls, x-spanway-response-cost is this call's cost and x-spanway-response-cost-cache-read and x-spanway-response-cost-cache-creation split out the prompt cache share. See routing decision headers.
On Logs (/ui/logs), click Filters, pick Key Alias = contract-summaries and click Apply Filters. Each row shows the model, the tokens, the cost and the status.
Streaming, tools, images, caching and reasoning
| Feature | How to use it through the gateway | Notes |
|---|---|---|
| Streaming | with client.messages.stream(...) as stream: and for text in stream.text_stream:, or stream=True for raw events. | Server-sent events in the Anthropic format, whichever provider answers. |
| Tools | tools=[{"name": ..., "description": ..., "input_schema": {...}}] and tool_choice. | Translated when another provider answers. |
| Images and PDFs | image and document content blocks with base64 data. | The model behind the name must accept them. |
| Prompt caching | cache_control={"type": "ephemeral"} on the blocks to cache. | Reported in usage.cache_read_input_tokens and usage.cache_creation_input_tokens. On Vertex AI and Azure deployments the gateway removes the scope field from cache_control, because those providers do not accept it. |
| Extended thinking | thinking as in the Anthropic API. | Thinking blocks come back from Claude deployments. When another provider answers, the gateway maps the thinking budget to that model's reasoning effort. |
| Beta features | client.beta.messages.create(..., betas=[...]) or an anthropic-beta header. | Passed on to Claude on Anthropic. On Bedrock, Vertex AI and Azure deployments the gateway keeps only the beta values that provider supports. |
| Token counting | client.messages.count_tokens(model=..., messages=...). | Served at /v1/messages/count_tokens, see count tokens. |
| Message Batches and Files | client.messages.batches and client.beta.files. | Not on the unified route. Use a second client with base_url="https://gateway.example.com/anthropic", the Anthropic pass-through. |
The SDK retries connection errors, 408, 409, 429 and 5xx answers twice by default, on top of the gateway's own retries and fallbacks. Set max_retries=0 when the gateway's retries should be the only ones. The default timeout is 10 minutes.
Errors
Every error from /v1/messages comes back in the Anthropic shape {"type": "error", "error": {"type": "...", "message": "..."}}. That covers the key check (a missing or wrong key, a model the key may not use and a spent budget) as well as errors from the request itself, such as an unknown model name or a provider failure. The SDK picks the exception class from the HTTP status, so the classes below hold for every error. Printed, an error reads Error code: <status> - {...body...}.
| Case | Exception | Text the gateway sends | Cause and fix |
|---|---|---|---|
| No key on the request | AuthenticationError (401) | Authentication Error, No api key passed in. | A proxy in between strips x-api-key or Authorization. Check that hop. |
| Wrong or deleted key | AuthenticationError (401) | Authentication Error, Invalid proxy server token passed. key=<hash>, not found in db. | Copy the key again or create a new key. |
| Blocked key | AuthenticationError (401) | Authentication Error, Key is blocked. Update via `/key/unblock` if you're an admin. | Ask the admin to open the key in Virtual Keys and click Unblock Key. |
| Expired key | AuthenticationError (401) | Authentication Error - Expired Key. Key Expiry time <time> and current time <time> | Ask the admin to extend the key or issue a new one. |
| The key may not use the model | PermissionDeniedError (403) | The requested model '<model>' is not available for this API key, or the model name is invalid. | Add the model to the key, including any fast tier model the app uses. |
| The model name is unknown | BadRequestError (400) | Invalid model name passed in model=<name> | The message starts with anthropic_messages:. Use a name from client.models.list(), typed exactly. |
| The budget is spent | UnprocessableEntityError (422) | Budget has been exceeded! Key=<key alias> Current cost: <spend>, Max budget: <max> | Wait for the reset or ask for a higher budget. With budget_exceeded_status_code: 429 it arrives as RateLimitError. |
| Over the key or team rate limit | RateLimitError (429) | Rate limit exceeded for <scope>: <value>. Limit type: <type>. | Slow down or ask for a higher RPM or TPM limit. retry-after says how long to wait. |
| Every deployment is cooling down | RateLimitError (429) | No deployments available for selected model | The providers behind the name failed recently. The message says how many seconds to wait. Ask the admin for a fallback. |
Wrong path, often a doubled /v1 | NotFoundError (404) | Not Found | Remove /v1 from ANTHROPIC_BASE_URL. |
| The provider failed | InternalServerError (500 to 503) | The provider's own message, followed by the model group that failed | Retry later and ask for a fallback deployment. |
| Nothing listens at the address | APIConnectionError | None. The SDK prints Connection error. | Check the address, port and that the gateway runs. In Docker use host.docker.internal. |
| TLS certificate not trusted | APIConnectionError | None. e.__cause__ holds CERTIFICATE_VERIFY_FAILED | See step 4 of troubleshooting. |
| The answer took too long | APITimeoutError | None. The SDK prints Request timed out. | Raise timeout= or stream long answers. |
| No key configured | TypeError | None. Could not resolve authentication method. Expected either api_key or auth_token to be set. | Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN. |
See the client error reference for the same cases in every SDK.
Troubleshooting
-
In
except anthropic.APIStatusError as e:, loge.status_code,e.bodyande.response.headers.get("x-spanway-call-id"). -
Open Logs (
/ui/logs), search for the call id or filter by Key Alias, and open the row for the status, the error, the deployment and the provider's answer. -
If the request is not on Logs, it never reached the gateway. Run with
export ANTHROPIC_LOG=debugto see each URL the SDK calls, which shows a doubled/v1or a wrong host. -
For TLS errors, the SDK trusts the operating system's certificate store since it moved to
httpx2, so installing the company root certificate on the machine fixes it.SSL_CERT_FILEpointing at a PEM bundle also works, or pass the bundle in code.import sslfrom anthropic import Anthropic, DefaultHttpxClientclient = Anthropic(http_client=DefaultHttpxClient(verify=ssl.create_default_context(cafile="/etc/ssl/company-root.pem"))) -
Read
x-spanway-routing-reasonandx-spanway-attemptsfor retries and fallbacks, explained on routing decision headers.
More symptoms are in troubleshooting.
Rotation and removal
Open the key in Virtual Keys, click Regenerate Key, set a Grace Period such as 24h, and deploy the new key in ANTHROPIC_API_KEY before it ends. From the API this is POST /key/{key}/regenerate with {"grace_period": "24h"}, which needs an Enterprise license. Without one, create a new key, switch the app and delete the old key.
Block Key (POST /key/block) stops the app at once and Unblock Key undoes it. Deleting the key (POST /key/delete with {"keys": ["<key>"]}) is permanent and makes later requests fail with 401. To take the app off the gateway, unset ANTHROPIC_BASE_URL and set an Anthropic key again.
Related
- Anthropic TypeScript SDK for the same steps in TypeScript.
- Anthropic Messages API for every request field the gateway accepts.
- Connect any client for base URLs and headers on every API surface.
- Client error reference for every gateway error.
- Coding agent setup for Claude Code, which is built on the same SDK.