Anthropic SDK
Use the official Anthropic SDKs with Spare, see what each request cost, and add fallbacks or the Router.
/v1/messagesChangebase_urlThe Anthropic SDKs work with Spare unchanged: set the base URL and your Spare key. Messages, streaming and tool use work as they do with Anthropic.
Set up
The base URL has no /v1: the SDK adds it.
import os
from anthropic import Anthropic
client = Anthropic(
base_url="https://api.spareinference.ai",
api_key=os.environ["SPARE_API_KEY"],
)
message = client.messages.create(
model="deepseek-v4.1-flash",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)The SDK sends the key in x-api-key, which Spare accepts on every endpoint.
See what a request cost
Each response carries an x-bitrouter-request-id header. Read it with the raw-response helpers, then look
the request up with settlement for its token counts, prices and total, alongside the parsed message:
raw = client.messages.with_raw_response.create(
model="deepseek-v4.1-flash",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)
request_id = raw.headers["x-bitrouter-request-id"]
message = raw.parse()When streaming, the final message_delta event carries usage.
Fallbacks
There's nothing to set up for provider failures: a request moves to the next provider serving the model on its own. To fall back to a different model, such as your Claude model, chain them in the CLI; see Fall back to a different model.
To run a routing preset instead of a fixed model, pass model="@<name>".
Keep Claude, add the Router
Spare's API runs the model you name and doesn't route between models; the Router runs in the CLI on your machine. Set it up following Cost routing, then point the SDK at the CLI
and ask for spare/auto:
client = Anthropic(
base_url="http://127.0.0.1:4356", # the CLI on your machine
api_key=os.environ.get("BITROUTER_API_KEY", "bitrouter-local"),
)
message = client.messages.create(
model="spare/auto",
max_tokens=1024,
messages=messages,
)The CLI holds your Spare and Claude keys. bitrouter-local works when the CLI allows local
requests without a key.
Good to know
- Prompt caching is automatic.
cache_controlblocks are accepted and ignored. - Errors keep Anthropic's shape, so
anthropic.RateLimitErrorand the other exception classes work as before. A 429 carriesRetry-After, which the SDK honors when it retries. - Server tools that run on Anthropic's side, like web search, aren't available on DeepSeek V4.1 Flash. Client tools you define work as usual.
Check it works
raw = client.messages.with_raw_response.create(
model="deepseek-v4.1-flash",
max_tokens=16,
messages=[{"role": "user", "content": "Reply with OK"}],
)
print(raw.headers["x-bitrouter-request-id"])How is this guide?