For AI agents, the documentation index lists all pages. Append .md to a documentation URL for Markdown, or request text/markdown.

Skip to Content
spare inference

OpenAI SDK

Use the official OpenAI SDKs with Spare, see what each request cost, and add fallbacks or the Router.

2 min readEdit this page
OpenAI SDKEndpointall threeChangebase_url

The OpenAI SDKs work with Spare unchanged: set the base URL and your Spare key. Chat Completions and Responses both work, with streaming and tool calls.

Set up

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.spareinference.ai/v1",
    api_key=os.environ["SPARE_API_KEY"],
)

resp = client.chat.completions.create(
    model="deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Hello"}],
)

The Responses API works the same way: client.responses.create(model="deepseek-v4.1-flash", input="Hello"). Spare's Responses API is stateless, so send the history with each request rather than previous_response_id.

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 result:

raw = client.chat.completions.with_raw_response.create(
    model="deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Hello"}],
)
request_id = raw.headers["x-bitrouter-request-id"]
resp = raw.parse()

When streaming, set stream_options={"include_usage": True} and the last chunk 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 OpenAI 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 your OpenAI model, 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 = OpenAI(
    base_url="http://127.0.0.1:4356/v1",   # the CLI on your machine
    api_key=os.environ.get("BITROUTER_API_KEY", "bitrouter-local"),
)

resp = client.chat.completions.create(
    model="spare/auto",
    messages=messages,
)

The CLI holds your Spare and OpenAI keys. bitrouter-local works when the CLI allows local requests without a key.

Handle limits

A 429 means the request was rate limited: error.code is rate_limit_exceeded for Spare's limit and upstream_rate_limited when every provider was. Retry-After is set when known, and the SDKs retry 429s on their own, honoring it.

Check it works

raw = client.chat.completions.with_raw_response.create(
    model="deepseek-v4.1-flash",
    messages=[{"role": "user", "content": "Reply with OK"}],
)
print(raw.headers["x-bitrouter-request-id"])

How is this guide?