# OpenAI SDK (Python, JS)

Call eWest with the official OpenAI libraries.

The official OpenAI libraries work with eWest: chat (`/v1/chat/completions`), the Responses API (`/v1/responses`), models (`/v1/models` and `/v1/models/{id}`) and the [image](https://ewest.ai/docs/images), [audio](https://ewest.ai/docs/audio) and [embedding](https://ewest.ai/docs/embeddings) endpoints. Install with `pip install openai` or `npm install openai`.

## Setup

Pass `base_url` (Python) or `baseURL` (JavaScript) as `https://api.ewest.ai/v1`, and your eWest key as the API key; it is sent as `Authorization: Bearer`. Or set `OPENAI_BASE_URL` and `OPENAI_API_KEY` and create the client without arguments.

Python:

```python
import os
from openai import OpenAI

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

# GET /v1/models/{id}: free, and proves the key and base URL work.
print(client.models.retrieve("ewest/gemini-flash").id)

```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY });

// GET /v1/models/{id}: free, and proves the key and base URL work.
console.log((await client.models.retrieve("ewest/gemini-flash")).id);

```

Shell:

```bash
# Or leave base_url / api_key out of the code: the SDKs read these.
export OPENAI_BASE_URL=https://api.ewest.ai/v1
export OPENAI_API_KEY="$EWEST_KEY"
```

## Choose a model

`client.models.list()` returns the models your key may use. `client.models.retrieve(id)` returns one, with its `context_window`, `input_modalities`, `supports_tools` and `supports_streaming`. Names need the `ewest/` prefix.

Python:

```python
import os
from openai import OpenAI

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

# Every model your key may call. Use the id as model=...
for model in client.models.list():
    print(model.id)

```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY });

// Every model your key may call. Use the id as model: ...
for await (const model of client.models.list()) console.log(model.id);

```

## Verify it works

A short chat completion. Every response has an `x-request-id` header; paste it into the console under Requests to see the request ([trace IDs](https://ewest.ai/docs/traces)).

Python:

```python
import os
from openai import OpenAI

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

response = client.chat.completions.create(
    model="ewest/gemini-flash",
    max_tokens=512,
    messages=[{"role": "user", "content": "Say hello in five words."}],
)
print(response.choices[0].message.content)

```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY });

const response = await client.chat.completions.create({
  model: "ewest/gemini-flash",
  max_tokens: 512,
  messages: [{ role: "user", content: "Say hello in five words." }],
});
console.log(response.choices[0].message.content);

```

## Streaming and tools

- Stream long answers (`stream=True`): without streaming, the whole answer has to arrive within about 90 seconds.
- Tool calls use the standard `tools` format, on chat completions and on the Responses API.
- `ewest/gemini-flash` does not think by default. When you turn reasoning on (`reasoning_effort` low, medium or high), give it room in `max_tokens` (512 or more): thinking uses output tokens, and a small limit can return empty text or a cut-off tool call.
- On the Responses API, conversations are stored by default: pass the earlier response's `id` as `previous_response_id` and send only the new `input`, or send `store=False` and the full conversation every time. See [Responses](https://ewest.ai/docs/responses).

Python:

```python
import os
from openai import OpenAI

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

# Streaming: print the answer as it arrives.
stream = client.chat.completions.create(
    model="ewest/gemini-flash",
    max_tokens=512,
    messages=[{"role": "user", "content": "Write one sentence about the sea."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
print()

# Tool calling: the model asks for get_weather, your code runs it.
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]
response = client.chat.completions.create(
    model="ewest/claude-haiku",
    max_tokens=512,
    messages=[{"role": "user", "content": "What is the weather in Paris?"}],
    tools=tools,
)
for call in response.choices[0].message.tool_calls or []:
    print("tool call:", call.function.name, call.function.arguments)

```

JavaScript:

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY });

// Streaming: print the answer as it arrives.
const stream = await client.chat.completions.create({
  model: "ewest/gemini-flash",
  max_tokens: 512,
  messages: [{ role: "user", content: "Write one sentence about the sea." }],
  stream: true,
});
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
console.log();

// Tool calling: the model asks for get_weather, your code runs it.
const response = await client.chat.completions.create({
  model: "ewest/claude-haiku",
  max_tokens: 512,
  messages: [{ role: "user", content: "What is the weather in Paris?" }],
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Current weather for a city",
        parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
      },
    },
  ],
});
for (const call of response.choices[0].message.tool_calls ?? []) {
  if (call.type === "function") console.log("tool call:", call.function.name, call.function.arguments);
}

```

Python (Responses):

```python
import os
from openai import OpenAI

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

# /v1/responses: this example sends the whole conversation in input; stored conversations are in https://ewest.ai/docs/responses.
stream = client.responses.create(
    model="ewest/claude-haiku",
    max_output_tokens=256,
    input="Write one sentence about the sea.",
    stream=True,
)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
print()

response = client.responses.create(
    model="ewest/claude-haiku",
    max_output_tokens=512,
    input="What is the weather in Paris?",
    tools=[{
        "type": "function",
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    }],
)
for item in response.output:
    if item.type == "function_call":
        print("tool call:", item.name, item.arguments)

```

JavaScript (Responses):

```javascript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY });

// /v1/responses: this example sends the whole conversation in input; stored conversations are in https://ewest.ai/docs/responses.
const stream = await client.responses.create({
  model: "ewest/claude-haiku",
  max_output_tokens: 256,
  input: "Write one sentence about the sea.",
  stream: true,
});
for await (const event of stream) {
  if (event.type === "response.output_text.delta") process.stdout.write(event.delta);
}
console.log();

const response = await client.responses.create({
  model: "ewest/claude-haiku",
  max_output_tokens: 512,
  input: "What is the weather in Paris?",
  tools: [
    {
      type: "function",
      name: "get_weather",
      description: "Current weather for a city",
      parameters: { type: "object", properties: { city: { type: "string" } }, required: ["city"] },
      strict: false,
    },
  ],
});
for (const item of response.output) {
  if (item.type === "function_call") console.log("tool call:", item.name, item.arguments);
}

```

## Troubleshooting

API errors raise `APIStatusError` with the status and body; the [Errors](https://ewest.ai/docs/errors) page explains each code.

- `401`: the key is missing, mistyped or revoked. Copy it again from [API keys](https://ewest.ai/keys).
- `404` with `model_not_found`: the model name needs the `ewest/` prefix (`ewest/claude-haiku`, not `claude-haiku`) and must be in [Models](https://ewest.ai/docs/models).
- `403`: your key is not allowed to use that model; `402`: the key's budget is used up. See [Errors](https://ewest.ai/docs/errors).
- Empty answer from `ewest/gemini-flash` with reasoning on: raise `max_tokens`, or set `reasoning_effort` to `none`.

Python:

```python
import os
import openai
from openai import OpenAI

client = OpenAI(base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"])
try:
    response = client.chat.completions.create(
        model="ewest/gemini-flash",
        max_tokens=512,
        messages=[{"role": "user", "content": "Say hello in five words."}],
    )
    print(response.choices[0].message.content)
except openai.APIStatusError as e:
    # 401 key, 402 budget, 403 model not allowed for this key, 404 unknown model id.
    print(e.status_code, e.body)
    print("trace:", e.response.headers.get("x-request-id"))

```

Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting).

Source: https://ewest.ai/docs/guides/openai-sdk
