# Using the Official OpenAI SDK

> Official SDKs: [openai-python](https://github.com/openai/openai-python), [openai-node](https://github.com/openai/openai-node)

## 📝 Introduction

BeeRoute is compatible with the OpenAI API, so you can call it with the official OpenAI SDKs. Compared with calling OpenAI directly, you change only two things:

1. **API key**: use a key created on the BeeRoute console [API Keys page](https://beeroute.ai/keys) (it looks like `sk-xxx`), not an OpenAI key.
2. **Base URL**: set it to `https://beeroute.ai/v1` (note the trailing `/v1`).

Everything else works exactly as in the official SDKs. The same key can also call models from other providers such as Claude, Gemini, and DeepSeek; see "Calling Models from Other Providers" below.

> **Quick facts**
> - Base URL: `https://beeroute.ai/v1`
> - API keys: [https://beeroute.ai/keys](https://beeroute.ai/keys)
> - Model IDs and prices: [https://beeroute.ai/modellist/](https://beeroute.ai/modellist/)
> - API reference: [OpenAI Chat Format (Chat Completions)](coding/openai-chat.md), [OpenAI Response Format (Responses)](coding/openai-responses.md)

## 📦 Installation

Python (requires Python 3.10 or later):

```bash
pip install openai
```

Node.js (requires Node.js 22 or later):

```bash
npm install openai
```

## 🔑 Configuring the Key and Base URL

You can pass `api_key` and `base_url` in code (as in the examples below), or set environment variables. Both the Python and Node.js SDKs read `OPENAI_API_KEY` and `OPENAI_BASE_URL` automatically.

macOS / Linux:

```bash
export OPENAI_API_KEY="sk-xxx"
export OPENAI_BASE_URL="https://beeroute.ai/v1"
```

Windows PowerShell:

```powershell
$env:OPENAI_API_KEY = "sk-xxx"
$env:OPENAI_BASE_URL = "https://beeroute.ai/v1"
```

With the environment variables set, you can create the client without arguments: `client = OpenAI()` in Python, or `const client = new OpenAI();` in Node.js.

?> Keep your key in environment variables or a `.env` file. Do not hard-code it or commit it to a repository.

## 💡 Request Examples

### Python: Chat Completions ✅

```python
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",  # key created on the BeeRoute console
    base_url="https://beeroute.ai/v1",
)

completion = client.chat.completions.create(
    model="gpt-6.2-sol",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Introduce yourself in one sentence."},
    ],
)

print(completion.choices[0].message.content)
```

### Python: Responses ✅

OpenAI recommends the Responses API for new projects. BeeRoute supports it too; see [OpenAI Response Format (Responses)](coding/openai-responses.md) for the API details.

```python
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://beeroute.ai/v1",
)

response = client.responses.create(
    model="gpt-6.2-sol",
    instructions="You are a concise coding assistant.",
    input="How do I check if a Python object is an instance of a class?",
)

print(response.output_text)
```

### Python: Streaming ✅

Streaming with Chat Completions:

```python
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://beeroute.ai/v1",
)

stream = client.chat.completions.create(
    model="gpt-6.2-sol",
    messages=[{"role": "user", "content": "Write a four-line poem about autumn."}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\nUsage:", chunk.usage)
```

Streaming with Responses (text deltas arrive in `response.output_text.delta` events):

```python
stream = client.responses.create(
    model="gpt-6.2-sol",
    input="Write a four-line poem about autumn.",
    stream=True,
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
```

### Node.js: Chat Completions ✅

The Node.js examples use ES modules and top-level `await`. Save the code as a `.mjs` file (or set `"type": "module"` in `package.json`) and run it with `node`.

```javascript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY, // key created on the BeeRoute console
  baseURL: 'https://beeroute.ai/v1',
});

const completion = await client.chat.completions.create({
  model: 'gpt-6.2-sol',
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'Introduce yourself in one sentence.' },
  ],
});

console.log(completion.choices[0].message.content);
```

### Node.js: Responses ✅

```javascript
import OpenAI from 'openai';

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

const response = await client.responses.create({
  model: 'gpt-6.2-sol',
  instructions: 'You are a concise coding assistant.',
  input: 'Are semicolons optional in JavaScript?',
});

console.log(response.output_text);
```

### Node.js: Streaming ✅

```javascript
import OpenAI from 'openai';

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

const stream = await client.chat.completions.create({
  model: 'gpt-6.2-sol',
  messages: [{ role: 'user', content: 'Write a four-line poem about autumn.' }],
  stream: true,
  stream_options: { include_usage: true },
});

for await (const chunk of stream) {
  const text = chunk.choices[0]?.delta?.content;
  if (text) process.stdout.write(text);
  if (chunk.usage) console.log('\nUsage:', chunk.usage);
}
```

Streaming with Responses works the same way as in Python: pass `stream: true`, iterate over the events with `for await`, and read `event.delta` when `event.type === 'response.output_text.delta'`.

### Listing Available Models ✅

```python
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://beeroute.ai/v1",
)

for model in client.models.list():
    print(model.id)
```

This returns the models your key can use and corresponds to `GET https://beeroute.ai/v1/models`.

## 🔄 Calling Models from Other Providers

With the same key and the same base URL, change `model` to another provider's model ID to call Claude, Gemini, DeepSeek, and other models through Chat Completions. BeeRoute converts the format automatically:

```python
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxx",
    base_url="https://beeroute.ai/v1",
)

for model in ["claude-sonnet-5-5", "gemini-4-hydrogen", "deepseek-flash", "kimi-k3.1-pro"]:
    completion = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": "Hello! Please introduce yourself in one sentence."}],
    )
    print(model, "->", completion.choices[0].message.content)
```

The full list of model IDs is on the [pricing page](https://beeroute.ai/modellist/). Supported parameters differ between models. For Claude or Gemini native features, see [Claude Native API Usage](coding/claude.md) and [Gemini Native API Usage](coding/gemini.md).

## ❓ FAQ

| Symptom | Python SDK exception | What to check |
|------|-----------------|----------|
| 401 with "Invalid token" | `AuthenticationError` | Make sure you are using a BeeRoute key, copied in full, and that the key is not disabled, expired, or out of quota. |
| 403 | `PermissionDeniedError` | Insufficient account balance, or the key is not allowed to use this model. |
| 404, an HTML web page, or an error from api.openai.com | varies | Check that the base URL is `https://beeroute.ai/v1` (including `/v1`) and that the `base_url` argument or the `OPENAI_BASE_URL` environment variable is actually in effect. |
| 429 | `RateLimitError` | Too many requests; retry later. |
| 503 saying no channel is available | `InternalServerError` | The model ID is misspelled or the model is temporarily unavailable; check it against the [pricing page](https://beeroute.ai/modellist/). |

All exceptions inherit from `openai.APIError`. Non-2xx responses raise a subclass of `openai.APIStatusError`, whose `status_code` and `response` attributes hold the details. Include the request id from the error message when you contact support.
