# OpenAI SDK (/docs/integrations/openai-sdk)

> For AI agents, the [documentation index](https://bitrouter.ai/llms.txt) lists all pages. Append .md to a documentation URL to read its Markdown.

<IntegrationHeader id="openai-sdk" />

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 \[#set-up]

**Python**

```python
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"}],
)
```

**TypeScript**

```ts
import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.spareinference.ai/v1',
  apiKey: process.env.SPARE_API_KEY,
});

const resp = await 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 \[#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](https://bitrouter.ai/docs/api/settlement) for its token counts, prices and total, alongside the parsed result:

**Python**

```python
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()
```

**TypeScript**

```ts
const { data: resp, response } = await client.chat.completions
  .create({ model: 'deepseek-v4.1-flash', messages: [{ role: 'user', content: 'Hello' }] })
  .withResponse();
const requestId = response.headers.get('x-bitrouter-request-id');
```

When streaming, set `stream_options={"include_usage": True}` and the last chunk carries `usage`.

## Fallbacks \[#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](https://bitrouter.ai/docs/fleet/fallbacks).

To run a [routing preset](https://bitrouter.ai/docs/fleet/provider-selection) instead of a fixed model, pass `model="@<name>"`.

## Keep your OpenAI model, add the Router \[#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](https://bitrouter.ai/docs/fleet/cost-routing#set-up), then point the SDK at the CLI
and ask for `spare/auto`:

```python
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 \[#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 \[#check-it-works]

```python
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"])
```