# eWest documentation > eWest (ewest.ai) gives developers video, image, audio and language models behind one OpenAI-compatible API at https://api.ewest.ai/v1. Model IDs look like `ewest/`; generated media is served from cdn.ewest.ai. --- # Quickstart Make your first eWest request in a few minutes. eWest gives you video, image and language models behind one OpenAI-compatible API. Requests go to `https://api.ewest.ai/v1` with your key in the `Authorization` header. 1. [Request access](https://ewest.ai/contact?topic=access) (eWest is invite-only for now), then [create an API key](https://ewest.ai/keys) and copy it (it is shown once). 2. Set it as an environment variable: `export EWEST_KEY=sk-…` 3. Send your first request (below). Usage appears in the console under Requests and Usage. ## Your first request A streamed chat completion. Every other model type works the same way; see [Chat](https://ewest.ai/docs/chat), [Images](https://ewest.ai/docs/images), [Video jobs](https://ewest.ai/docs/video), [Audio](https://ewest.ai/docs/audio) and [Embeddings](https://ewest.ai/docs/embeddings). cURL: ```bash curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-flash", "stream": true, "messages": [{"role": "user", "content": "Hello!"}]}' ``` Python: ```python import os from openai import OpenAI client = OpenAI(base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"]) stream = client.chat.completions.create( model="ewest/gemini-flash", messages=[{"role": "user", "content": "Hello!"}], stream=True, ) for chunk in stream: print(chunk.choices[0].delta.content or "", end="") ``` JavaScript: ```javascript import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY }); const stream = await client.chat.completions.create({ model: "ewest/gemini-flash", messages: [{ role: "user", content: "Hello!" }], stream: true, }); for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? ""); ``` ## Next steps - Pick a model on the [Models](https://ewest.ai/docs/models) page and use its ID in the `model` field. - Use eWest from your editor or agent: [Developer tools](https://ewest.ai/docs/guides). - When something fails, the [Errors](https://ewest.ai/docs/errors) page explains each code, and a [trace ID](https://ewest.ai/docs/traces) finds the request in the console. - API reference: every endpoint, field and error as an [OpenAPI 3.1 spec](https://ewest.ai/openapi.json), for code generators and AI agents. Source: https://ewest.ai/docs --- # Authentication Send your API key with every request. Every request to `https://api.ewest.ai/v1` carries your API key in the `Authorization` header as `Bearer sk-…`. Clients built for the Anthropic API can send it in the `x-api-key` header instead. ## API keys > Keep your key on your server. Never put it in browser code, a mobile app or a public repository: anyone who finds it can spend your budget. Call eWest from your backend and have your web or mobile client call that instead. - Create keys in the console under [API keys](https://ewest.ai/keys). A key is shown once, so copy it right away. - Keep keys in an environment variable such as `EWEST_KEY` or in your platform's secret store. If a key leaks, revoke it in the console and create a new one. - A key can have a budget and a list of allowed models. Going over the budget returns `402`, a model the key may not use returns `403` (see [Errors](https://ewest.ai/docs/errors)). - A missing, invalid, expired or blocked key returns `401`. Source: https://ewest.ai/docs/authentication --- # Models Every model you can call, with its ID and limits. Use the ID in the `model` field. Machine-readable list: [/v1/catalog](https://api.ewest.ai/v1/catalog). Missing a model? [Request it](https://ewest.ai/model-requests). | Model | ID | Type | Limits | Price | Released | | --- | --- | --- | --- | --- | --- | | [Gemini 3.5 Flash Lite](https://ewest.ai/models/gemini-flash) | `ewest/gemini-flash` | Text | 1M context | $0.30 / $2.50 per M | 2026-07-21 | | [Gemini 3.8 Flash](https://ewest.ai/models/gemini-3.8-flash) | `ewest/gemini-3.8-flash` | Text | 1M context · 65K output · max_tokens 256+ | $0.825 / $4.125 per M, launch price ends 1 Jan 2027, 08:00 UTC | 2026-09-02 | | [Gemini 4 Argon](https://ewest.ai/models/gemini-4-argon) | `ewest/gemini-4-argon` | Text | 1M context · 32K output · max_tokens 256+ | $4.40 / $22 per M | 2026-10-13 | | [Claude Haiku 4.5](https://ewest.ai/models/claude-haiku) | `ewest/claude-haiku` | Text | 200K context | $1 / $5 per M | 2025-10-15 | | [Claude Sonnet 5.5](https://ewest.ai/models/claude-sonnet) | `ewest/claude-sonnet` | Text | 1M context | $2 / $10 per M | 2026-09-28 | | [Claude Opus 5.5](https://ewest.ai/models/claude-opus) | `ewest/claude-opus` | Text | 1M context | $4 / $20 per M | 2026-09-22 | | [Claude Haiku 5.5](https://ewest.ai/models/claude-haiku-5.5) | `ewest/claude-haiku-5.5` | Text | 1M context | $0.10 / $0.50 per M | 2026-10-07 | | [DeepSeek V4.1 Flash](https://ewest.ai/models/deepseek-v4.1-flash) | `ewest/deepseek-v4.1-flash` | Text | 1M context | $0.30 / $1.20 per M | 2026-09-10 | | [gpt-oss-120b](https://ewest.ai/models/gpt-oss-120b) | `ewest/gpt-oss-120b` | Text | 131K context | $0.03 / $0.15 per M | 2025-08-05 | | [Gemma 4 26B A4B](https://ewest.ai/models/gemma-4-26b) | `ewest/gemma-4-26b` | Text | 32K context | $0.06 / $0.33 per M | 2026-04-02 | | [Mistral NeMo 12B](https://ewest.ai/models/mistral-nemo) | `ewest/mistral-nemo` | Text | 32K context | $0.03 / $0.03 per M | 2024-07-18 | | [Beam 1.0](https://ewest.ai/models/beam-1.0) | `ewest/beam-1.0` | Text | 262K context | $0.25 / $1 per M | 2026-10-16 | | [Muse Spark Open](https://ewest.ai/models/muse-spark-open) | `ewest/muse-spark-open` | Text | 32K context | $1.25 / $4.25 per M | 2026-10-15 | | [FLUX.1 [schnell]](https://ewest.ai/models/flux-schnell) | `ewest/flux-schnell` | Image | up to 1536 px | $0.003/megapixel | 2024-08-01 | | [Gemini 2.5 Flash Image](https://ewest.ai/models/gemini-flash-image) | `ewest/gemini-flash-image` | Image | 1024 px | $0.039/image | 2025-10-02 | | [Nano Banana 2.1](https://ewest.ai/models/nano-banana-2.1) | `ewest/nano-banana-2.1` | Image | 1K–4K · 8 aspect ratios | from $0.04/image | 2026-10-06 | | [Nano Banana Pro](https://ewest.ai/models/nano-banana-pro) | `ewest/nano-banana-pro` | Image | 1K–4K · up to 14 reference images | from $0.15/image | 2026-05-28 | | [GPT Image 2.5 Flare](https://ewest.ai/models/gpt-image-2.5) | `ewest/gpt-image-2.5` | Image | up to 2560×1440 · up to 16 reference images | from $0.00402/image | 2026-09-08 | | [Seedream 5.0 Pro](https://ewest.ai/models/seedream-5.0-pro) | `ewest/seedream-5.0-pro` | Image | up to 2560×1440 | from $0.0675/image | 2026-07-08 | | [Qwen Image 3](https://ewest.ai/models/qwen-image-3) | `ewest/qwen-image-3` | Image | up to 2048×2048 · 1 to 6 images · prompts up to 5,000 characters | from $0.04/image | 2026-07-21 | | [Z-Image Turbo](https://ewest.ai/models/z-image-turbo) | `ewest/z-image-turbo` | Image | 10 sizes up to 2048×1152 · 1 to 4 images · English and Chinese text | $0.005/megapixel | 2025-11-26 | | [FLUX 3](https://ewest.ai/models/flux-3) | `ewest/flux-3` | Image | 1K or 2K · 8 aspect ratios | $0.048/megapixel | 2026-10-01 | | [Ideogram 4.0](https://ewest.ai/models/ideogram-4) | `ewest/ideogram-4` | Image | 38 sizes up to 2048×2048 · 3 rendering speeds | from $0.0075/megapixel | 2026-06-03 | | [BiRefNet v2](https://ewest.ai/models/birefnet-v2) | `ewest/birefnet-v2` | Image | one image in · transparent PNG out · no prompt needed | $0.002/image | 2024-10-28 | | [FLUX.1 Kontext [pro]](https://ewest.ai/models/flux-kontext) | `ewest/flux-kontext` | Image | one image in · 1 to 4 edits per call · 9 aspect ratios | $0.04/image | 2025-05-29 | | [FLUX.2 [pro]](https://ewest.ai/models/flux-2-pro) | `ewest/flux-2-pro` | Image | up to 2560×1440 (4 MP) · up to 8 reference images · 14 sizes | from $0.03/image | 2025-11-25 | | [Fibo 2.0 Edit](https://ewest.ai/models/fibo-2-edit) | `ewest/fibo-2-edit` | Image | 1–4 images in · instruction-based edits · optional mask · one image out | $0.04/image | 2026-10-19 | | [Qwen Image Edit Plus](https://ewest.ai/models/qwen-image-edit-plus) | `ewest/qwen-image-edit-plus` | Image | 1–3 images in · 1 to 4 edits per call · 7 sizes up to 1536×1024 · billed per megapixel | $0.03/megapixel | 2025-09-22 | | [MiniMax H3-Image](https://ewest.ai/models/minimax-h3-image) | `ewest/minimax-h3-image` | Image | 10 fixed sizes, 1024×1024 up to 16 MP (6272×2688) · text to image only · one image per request · prompts up to 4,000 characters | from $0.015/image | 2026-11-23 | | [Eleven v4 Turbo](https://ewest.ai/models/eleven-v4-turbo) | `ewest/eleven-v4-turbo` | Speech | up to 5,000 characters · MP3 | $0.04 per 1K characters | 2026-09-28 | | [Eleven v4](https://ewest.ai/models/eleven-v4) | `ewest/eleven-v4` | Speech | up to 3,000 characters · audio tags · MP3 | $0.08 per 1K characters | 2026-09-28 | | [Gemini 3.8 Flash TTS](https://ewest.ai/models/gemini-3.8-flash-tts) | `ewest/gemini-3.8-flash-tts` | Speech | up to 5,000 characters · WAV | $0.045 per 1K characters | 2026-09-22 | | [MiniMax Speech 2.8 HD](https://ewest.ai/models/minimax-speech-2.8-hd) | `ewest/minimax-speech-2.8-hd` | Speech | up to 5,000 characters · MP3 | $0.10 per 1K characters | 2026-01-23 | | [Scribe v2](https://ewest.ai/models/scribe-v2) | `ewest/scribe-v2` | Transcription | up to 20 min · 25 MB | $0.008/minute | 2026-01-09 | | [Cohere Transcribe](https://ewest.ai/models/cohere-transcribe) | `ewest/cohere-transcribe` | Transcription | up to 20 min · 25 MB | $0.004167/minute | 2026-03-26 | | [Veo 3.1 Fast](https://ewest.ai/models/veo-3.1-fast) | `ewest/veo-3.1-fast` | Video | 4–8 s · up to 1080p | from $0.08/s | 2025-11-17 | | [Seedance 2.5](https://ewest.ai/models/seedance-2.5) | `ewest/seedance-2.5` | Video | 4–10 s · up to 1080p | from $0.2056/s | 2026-07-31 | | [Seedance 2.0](https://ewest.ai/models/seedance-2.0) | `ewest/seedance-2.0` | Video | 4–15 s · up to 1080p | from $0.1406/s | 2026-02-12 | | [Seedance 2.0 Fast](https://ewest.ai/models/seedance-2.0-fast) | `ewest/seedance-2.0-fast` | Video | 4–15 s · up to 720p | from $0.1125/s | 2026-04-01 | | [Seedance 2.0 Mini](https://ewest.ai/models/seedance-2.0-mini) | `ewest/seedance-2.0-mini` | Video | 4–15 s · up to 720p | from $0.0703/s | 2026-06-23 | | [MiniMax H3 Max](https://ewest.ai/models/minimax-h3-max) | `ewest/minimax-h3-max` | Video | 5–10 s · up to 768p | from $0.05/s | 2026-08-26 | | [MiniMax H3 Max Turbo](https://ewest.ai/models/minimax-h3-max-turbo) | `ewest/minimax-h3-max-turbo` | Video | 5–10 s · up to 768p | from $0.025/s | 2026-09-02 | | [Kling 3.0 Pro](https://ewest.ai/models/kling-3.0-pro) | `ewest/kling-3.0-pro` | Video | 3–10 s · 1080p | from $0.112/s | 2026-02-05 | | [Kling 3.0 Turbo](https://ewest.ai/models/kling-3.0-turbo) | `ewest/kling-3.0-turbo` | Video | 3–10 s · 1080p · audio always on | $0.14/s | 2026-06-17 | | [Marey](https://ewest.ai/models/marey) | `ewest/marey` | Video | 5 or 10 s · 1080p · no audio | $0.30/s | 2025-08-14 | | [Kling 4.0](https://ewest.ai/models/kling-4.0) | `ewest/kling-4.0` | Video | 3–30 s · up to 1080p | from $0.157/s | 2026-10-15 | | [Kling 4.0 Flash](https://ewest.ai/models/kling-4.0-flash) | `ewest/kling-4.0-flash` | Video | 3–20 s · 720p | $0.094/s | 2026-09-28 | | [Gemini Omni Flash 1.1](https://ewest.ai/models/gemini-omni-flash-1.1) | `ewest/gemini-omni-flash-1.1` | Video | 3–10 s · 360p to 4K | from $0.03/s | 2026-08-27 | | [Gemini Omni Flash 1.2](https://ewest.ai/models/gemini-omni-flash-1.2) | `ewest/gemini-omni-flash-1.2` | Video | 3–15 s · 360p to 4K · PNG/JPEG/WebP image input | from $0.0273/s | 2026-11-05 | | [FLUX 3 Max Video](https://ewest.ai/models/flux-3-max-video) | `ewest/flux-3-max-video` | Video | 5–20 s · up to 1080p | from $0.17/s | 2026-10-19 | | [Ray 3.2](https://ewest.ai/models/ray-3.2) | `ewest/ray-3.2` | Video | 5 or 10 s · up to 1080p · no audio | from $0.03/s | 2026-06-09 | | [Grok Imagine Video 1.5](https://ewest.ai/models/grok-imagine-video-1.5) | `ewest/grok-imagine-video-1.5` | Video | 1–15 s · up to 1080p · JPEG/PNG image input | from $0.08/s | 2026-06-16 | | [Vidu Q4](https://ewest.ai/models/vidu-q4) | `ewest/vidu-q4` | Video | 3–16 s · 540p to 4K | from $0.0315/s | 2026-10-07 | | [Wan 3.0 Prime](https://ewest.ai/models/wan-3.0-prime) | `ewest/wan-3.0-prime` | Video | 2–30 s · up to 1080p | from $0.068/s | 2026-08-20 | | [HappyHorse 1.1](https://ewest.ai/models/happy-horse-1.1) | `ewest/happy-horse-1.1` | Video | 3–15 s · up to 1080p | from $0.14/s | 2026-06-23 | | [LTX 2.5 Fast](https://ewest.ai/models/ltx-2.5-fast) | `ewest/ltx-2.5-fast` | Video | 6–20 s · up to 4K (4K and 1440p up to 10 s) | from $0.09/s | 2026-08-11 | | [LTX 2.5 Pro](https://ewest.ai/models/ltx-2.5-pro) | `ewest/ltx-2.5-pro` | Video | 6–10 s · up to 1080p | from $0.12/s | 2026-08-11 | | [PixVerse V6](https://ewest.ai/models/pixverse-v6) | `ewest/pixverse-v6` | Video | 1–15 s · up to 1080p | from $0.025/s | 2026-03-30 | | [Pika H3 Flex](https://ewest.ai/models/pika-h3-flex) | `ewest/pika-h3-flex` | Video | 4–15 s · 768p (1344×768 at 16:9) · 24 fps · text only | $0.04/s | 2026-10-29 | | [LTX 2.5 Flash](https://ewest.ai/models/ltx-2.5-flash) | `ewest/ltx-2.5-flash` | Video | 4–15 s · 720p or 1080p · 24 fps · stereo audio · text only | from $0.03/s | 2026-08-11 | | [Eleven Music v2.5](https://ewest.ai/models/eleven-music-v2.5) | `ewest/eleven-music-v2.5` | Audio | 10 s – 5 min · MP3 | $0.60/minute | 2026-09-11 | | [Lyria 3.5](https://ewest.ai/models/lyria-3.5) | `ewest/lyria-3.5` | Audio | about 3 min · MP3 | $0.10/track | 2026-09-03 | | [MiniMax Music 2.6](https://ewest.ai/models/minimax-music-2.6) | `ewest/minimax-music-2.6` | Audio | up to 5 min · MP3 | $0.15/track | 2026-04-10 | | [Eleven Sound Effects v2](https://ewest.ai/models/eleven-sound-effects-v2) | `ewest/eleven-sound-effects-v2` | Audio | 1–22 s · MP3 | $0.002/second | 2025-09-02 | | [Eleven Sound Effects v3](https://ewest.ai/models/eleven-sfx-v3) | `ewest/eleven-sfx-v3` | Audio | 1–30 s · MP3 | $0.002/second | 2026-11-02 | | [Hunyuan 3D 3.1 Pro](https://ewest.ai/models/hunyuan-3d-3.1-pro) | `ewest/hunyuan-3d-3.1-pro` | 3D | text or image input · GLB + OBJ · 40K–1.5M faces | from $0.225/generation | 2026-01-27 | | [Tripo H3.1](https://ewest.ai/models/tripo-h3.1) | `ewest/tripo-h3.1` | 3D | text or image input · GLB (FBX for quad) · 1K–2M faces | from $0.10/generation | 2026-02-11 | | [Gemini Embedding 2](https://ewest.ai/models/gemini-embedding) | `ewest/gemini-embedding` | Embeddings | 8K tokens per input | $0.20 per M tokens | 2026-04-22 | | [Semantic Ranker](https://ewest.ai/models/semantic-ranker) | `ewest/semantic-ranker` | Rerank | up to 100 documents | $1 per 1,000 requests | 2026-09-01 | Source: https://ewest.ai/docs/models --- # Chat Chat completions, compatible with the OpenAI SDKs. `POST /v1/chat/completions`, compatible with the OpenAI SDKs. Set `"stream": true` for long answers: without streaming, the whole answer has to arrive within about 90 seconds. More: [Streaming](https://ewest.ai/docs/streaming), [Tool calling](https://ewest.ai/docs/tool-calling) and [Structured output](https://ewest.ai/docs/structured-output). To send pictures, PDFs or audio in a message, see [Files](https://ewest.ai/docs/files). cURL: ```bash curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-flash", "stream": true, "messages": [{"role": "user", "content": "Hello!"}]}' ``` Python: ```python import os from openai import OpenAI client = OpenAI(base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"]) stream = client.chat.completions.create( model="ewest/gemini-flash", messages=[{"role": "user", "content": "Hello!"}], stream=True, ) for chunk in stream: print(chunk.choices[0].delta.content or "", end="") ``` JavaScript: ```javascript import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY }); const stream = await client.chat.completions.create({ model: "ewest/gemini-flash", messages: [{ role: "user", content: "Hello!" }], stream: true, }); for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta?.content ?? ""); ``` Source: https://ewest.ai/docs/chat --- # Streaming Get a chat answer piece by piece as it is written, with token usage and errors. Add `"stream": true` to a [chat completions](https://ewest.ai/docs/chat) request and the answer arrives as Server-Sent Events while the model writes it, instead of as one JSON body at the end. You see the first words sooner, and long answers are not held up by the time limit on a normal response. The OpenAI libraries do this with `stream=True`. ## The chat stream The response has `Content-Type: text/event-stream`. Each event is one line starting with `data: ` and holding a JSON chunk, followed by a blank line. Every chunk has `"object": "chat.completion.chunk"`, the same `id` for the whole answer, and the `ewest/*` name in `model`. - The first chunk's `choices[0].delta` usually has `role: "assistant"` and often the first words in `content`. - Each following chunk's `delta.content` holds the next piece of text. Add the pieces together in order. A chunk can also carry no text at all, so check that `content` is set. - A chunk whose `finish_reason` is set ends the answer: `stop` (finished), `length` (hit `max_tokens`), `tool_calls` (the model wants a [tool](https://ewest.ai/docs/tool-calling) run) or `error` (see below). - The last event is the literal line `data: [DONE]`, which is not JSON. ## Token usage Streamed answers carry token counts only if you ask: send `"stream_options": {"include_usage": true}`. The counts then arrive in one extra chunk after the one with `finish_reason` and before `[DONE]`. That chunk has a `usage` object with `prompt_tokens`, `completion_tokens` and `total_tokens` and no text. Without the option no chunk has `usage`. ## Reading the stream The examples below read the stream by hand, so you can see the format. They print the text as it arrives, return the usage, stop at `[DONE]`, and raise an error if the answer fails part-way. With the OpenAI libraries you can skip all of that: they do the same for you. cURL: ```bash # -N turns off curl's output buffering so chunks print as they arrive. curl -N https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-flash", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Write a haiku about the sea."}]}' ``` Python: ```python import json, os, requests def stream_chat(payload, on_text): """Calls on_text() with each piece of the answer; returns the token usage.""" usage = None finished = False with requests.post( "https://api.ewest.ai/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"}, json={**payload, "stream": True, "stream_options": {"include_usage": True}}, stream=True, timeout=(10, 100), # connect, then at most 100 s of silence ) as res: if not res.ok: # a problem found before the answer starts is a normal error response raise RuntimeError(f"{res.status_code}: {res.text}") for raw in res.iter_lines(): line = raw.decode("utf-8") if not line.startswith("data:"): continue # blank separators and comments data = line[5:].strip() if data == "[DONE]": finished = True break chunk = json.loads(data) if chunk.get("error"): # the answer failed after it started; the stream ends here raise RuntimeError(chunk["error"].get("message", "stream failed")) usage = chunk.get("usage") or usage # arrives in the last chunk before [DONE] for choice in chunk.get("choices", []): text = choice.get("delta", {}).get("content") if text: on_text(text) if not finished: # the connection dropped: the answer may be incomplete raise RuntimeError("stream ended before [DONE]") return usage usage = stream_chat( dict( model="ewest/gemini-flash", messages=[{"role": "user", "content": "Write a haiku about the sea."}], ), lambda text: print(text, end="", flush=True), ) print("\n", usage) ``` JavaScript: ```javascript async function streamChat(payload, onText) { // Give up after 100 s without any data (the timer restarts on every read). const controller = new AbortController(); let timer; const idle = () => { clearTimeout(timer); timer = setTimeout(() => controller.abort(), 100_000); }; idle(); try { const res = await fetch("https://api.ewest.ai/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ ...payload, stream: true, stream_options: { include_usage: true } }), signal: controller.signal, }); // A problem found before the answer starts is a normal error response. if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`); return await readStream(res, onText, idle); } finally { clearTimeout(timer); } } async function readStream(res, onText, idle) { let usage = null; let finished = false; const handle = (line) => { if (!line.startsWith("data:")) return; // blank separators and comments const data = line.slice(5).trim(); if (data === "[DONE]") { finished = true; return; } const chunk = JSON.parse(data); // The answer failed after it started; the stream ends here. if (chunk.error) throw new Error(chunk.error.message ?? "stream failed"); usage = chunk.usage ?? usage; // arrives in the last chunk before [DONE] for (const choice of chunk.choices ?? []) { if (choice.delta?.content) onText(choice.delta.content); } }; // A chunk can end in the middle of a line, so keep the unfinished part for the next read. const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; for (;;) { const { done, value } = await reader.read(); idle(); buffer += decoder.decode(value, { stream: !done }); const lines = buffer.split("\n"); buffer = done ? "" : lines.pop(); lines.forEach(handle); if (done) { // The connection dropped: the answer may be incomplete. if (!finished) throw new Error("stream ended before [DONE]"); return usage; } } } const usage = await streamChat( { model: "ewest/gemini-flash", messages: [{ role: "user", content: "Write a haiku about the sea." }], }, (text) => process.stdout.write(text), ); console.log("\n", usage); ``` - A network read can end in the middle of a line. Keep the unfinished part and add the next read to it, as the JavaScript example does. - Browsers' `EventSource` cannot send a POST body or an `Authorization` header. Read the stream with `fetch`, and call eWest from your server, not from the page, so the key stays private (see [Authentication](https://ewest.ai/docs/authentication)). - Set a read timeout on the connection (not only a total time), so a stalled stream does not hang for ever. ## Errors and time limits A problem found before the answer starts, such as a wrong key or an unknown model, is a normal HTTP error and the body is not a stream: check `res.ok` first. Once the answer has started the status is already `200`, so a later failure arrives inside the stream. For chat, the last chunk then has `finish_reason: "error"` and an `error` object, and the stream ends. Text you already received stays valid. To try again, send the whole request again. [Errors](https://ewest.ai/docs/errors#streams) lists this for all three stream formats. A chat request has to produce its first byte within about 90 seconds. Without streaming the first byte is the finished answer, so the whole answer has to arrive within that time. With streaming the first chunk normally comes within seconds, so use it for long answers, and for any model or prompt that may take a while. See [Rate limits and retries](https://ewest.ai/docs/rate-limits) for what to retry. ## Messages and Responses streams The other two text endpoints stream too, with `"stream": true` and the event names of their own formats. Token usage is part of the stream there and needs no option. - **Messages** (`POST /v1/messages`): events with an `event:` line, in this order: `message_start`, then for each content block `content_block_start`, many `content_block_delta` and `content_block_stop`, then `message_delta` (with `stop_reason` and the output tokens) and `message_stop`. `ping` events can appear in between and can be ignored. A failure is an `error` event. - **Responses** (`POST /v1/responses`): read the `type` field in each `data:` line (do not rely on `event:` lines being present): `response.created`, `response.in_progress`, `response.output_item.added`, `response.content_part.added`, many `response.output_text.delta`, then `response.output_text.done`, `response.content_part.done`, `response.output_item.done` and `response.completed`, which holds the full response with its `usage`. A normal stream ends with `data: [DONE]`; a failure ends it with an `error` event and no `[DONE]`. > Whether a model can stream is the `supports_streaming` field in `GET /v1/models/{id}` (see [Models](https://ewest.ai/docs/models)). It is true for every chat model today. Source: https://ewest.ai/docs/streaming --- # Tool calling Let a model call your functions: define tools, run what it asks for, send the results back. With tool calling (also called function calling) a model can ask your code to do something it cannot do itself, such as look up an order or read the weather. You describe your functions in the request. The model answers with the function to call and its arguments. You run it and send the result back, and the model writes the final answer. eWest never runs your functions: the model only asks, and your code does the work. ## Which models A chat model supports tools when `supports_tools` is `true` in `GET /v1/models/{id}` (the Tool use row in model comparisons). Every chat model in the catalog sets it today. Tools work on [chat completions](https://ewest.ai/docs/chat), on `POST /v1/messages` and on `POST /v1/responses`, and with streaming. ## The loop 1. Send your `messages` and a `tools` list. Each tool is `{"type": "function", "function": {"name", "description", "parameters"}}`, where `parameters` is a JSON Schema for the arguments. Good descriptions matter: the model chooses tools by them. 2. If the model wants a tool, the answer has `finish_reason: "tool_calls"` and `message.tool_calls`. Each call has an `id`, `function.name` and `function.arguments`. 3. Run the function. `arguments` is a JSON **string**: parse it, and expect that it can be invalid or miss a field, because the model writes it. 4. Add the assistant message to `messages` exactly as it came back, then one message per call with `role: "tool"`, the call's `tool_call_id` and your result as a string. 5. Send the request again, with the same `tools`. The model either answers in text (`finish_reason: "stop"`) or asks for more tools. Repeat, and put a limit on the number of rounds. cURL: ```bash # 1. Describe the tools. The answer has finish_reason "tool_calls" and a tool_calls list. curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-flash", "max_tokens": 1024, "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"]}}}]}' # 2. Run the function yourself, then send the conversation back: your first message, the # assistant message as it came back (with its tool_calls), and one "tool" message per call. # Put the id from step 1 where this example says CALL_ID. curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-flash", "max_tokens": 1024, "messages": [ {"role": "user", "content": "What is the weather in Paris?"}, {"role": "assistant", "content": null, "tool_calls": [ {"id": "CALL_ID", "type": "function", "function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}}]}, {"role": "tool", "tool_call_id": "CALL_ID", "content": "{\"temp_c\": 18, \"sky\": \"sunny\"}"} ], "tools": [{"type": "function", "function": { "name": "get_weather", "description": "Current weather for a city.", "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}}]}' ``` Python: ```python import json, os, requests TOOLS = [{ "type": "function", "function": { "name": "get_weather", "description": "Current weather for a city.", "parameters": { "type": "object", "properties": {"city": {"type": "string", "description": "For example Paris"}}, "required": ["city"], }, }, }] def get_weather(city): # your own code: call a real weather service here return {"city": city, "temp_c": 18, "sky": "sunny"} FUNCTIONS = {"get_weather": get_weather} def chat(messages): res = requests.post( "https://api.ewest.ai/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"}, json={"model": "ewest/gemini-flash", "max_tokens": 1024, "messages": messages, "tools": TOOLS}, timeout=100, ) res.raise_for_status() return res.json()["choices"][0] messages = [{"role": "user", "content": "What is the weather in Paris and in Rome?"}] for _ in range(5): # a limit, so a model that keeps asking cannot loop forever choice = chat(messages) message = choice["message"] messages.append(message) # keep the assistant message as it came back calls = message.get("tool_calls") or [] if not calls: # a text answer: done break for call in calls: # there can be several in one answer try: args = json.loads(call["function"]["arguments"]) result = FUNCTIONS[call["function"]["name"]](**args) except Exception as err: # tell the model, so it can correct itself result = {"error": str(err)} messages.append({"role": "tool", "tool_call_id": call["id"], "content": json.dumps(result)}) else: # the loop ended without a text answer raise RuntimeError("gave up after 5 tool rounds") print(message["content"]) ``` JavaScript: ```javascript const tools = [{ type: "function", function: { name: "get_weather", description: "Current weather for a city.", parameters: { type: "object", properties: { city: { type: "string", description: "For example Paris" } }, required: ["city"], }, }, }]; // Your own code: call a real weather service here. const functions = { get_weather: ({ city }) => ({ city, temp_c: 18, sky: "sunny" }), }; async function chat(messages) { const res = await fetch("https://api.ewest.ai/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ model: "ewest/gemini-flash", max_tokens: 1024, messages, tools }), }); if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`); return (await res.json()).choices[0]; } const messages = [{ role: "user", content: "What is the weather in Paris and in Rome?" }]; let message; let answered = false; for (let turn = 0; turn < 5 && !answered; turn++) { // a limit, so a model that keeps asking cannot loop forever message = (await chat(messages)).message; messages.push(message); // keep the assistant message as it came back const calls = message.tool_calls ?? []; answered = calls.length === 0; // a text answer: done for (const call of calls) { // there can be several in one answer let result; try { result = functions[call.function.name](JSON.parse(call.function.arguments)); } catch (err) { // tell the model, so it can correct itself result = { error: String(err) }; } messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) }); } } if (!answered) throw new Error("gave up after 5 tool rounds"); console.log(message.content); ``` ## Choosing when a tool is used `tool_choice` controls it: - `"auto"` (the default): the model decides. - `"none"`: the model does not call a tool. The `tools` still count as part of the prompt. - `"required"`: the model must call at least one tool. - `{"type": "function", "function": {"name": "get_weather"}}`: the model must call that tool. A name that is not in `tools` is a `400` `invalid_request_error`. ## Several calls at once A model can ask for more than one tool in the same answer, for example the weather in two cities. Answer every call, each with its own `tool_call_id`, before you send the request again. You can run them at the same time. `"parallel_tool_calls": false` asks the model for at most one call per answer. Treat the `id` as an opaque string: send it back unchanged, and do not parse it or rely on its length or format. ## Tool calls while streaming With `"stream": true` the calls arrive as `delta.tool_calls` ([Streaming](https://ewest.ai/docs/streaming)). Each entry has an `index`. The first chunk for an index carries the call's `id` and `function.name`; the later ones carry pieces of `function.arguments`. Join the pieces for each index, and parse the result only when the stream has ended with `finish_reason: "tool_calls"`. ## Getting good results - Give models that think before they answer room in `max_tokens`. With a small limit the model can use it all on thinking and return nothing or a cut-off call. 1024 is a good start; use more if you set `reasoning_effort`, and if the limit is too small for it the `400` names the minimum. - When a function fails, send the error back as the tool's result instead of stopping. The model can usually correct the arguments. - Other formats: on `POST /v1/messages` a tool has `name`, `description` and `input_schema`, the answer has `tool_use` blocks and `stop_reason: "tool_use"`, and you reply with a `tool_result` block in the next user message. On `POST /v1/responses` the answer has `function_call` items that you answer with `function_call_output` items, as in the OpenAI Responses API. - Coding tools use all of this for you; see [Developer tools](https://ewest.ai/docs/guides). For schema-shaped answers without tools, see [Structured output](https://ewest.ai/docs/structured-output). Source: https://ewest.ai/docs/tool-calling --- # Structured output Get answers as JSON that follows your schema. When code reads the answer, ask for JSON. On [chat completions](https://ewest.ai/docs/chat), `response_format` tells the model to answer in JSON, and with a schema, in JSON of the shape you describe. The answer is then in `choices[0].message.content` as a string that you parse. ## The two formats | response_format | What you get | Use it when | | --- | --- | --- | | `{"type": "json_schema", "json_schema": {...}}` | JSON that follows your schema. `json_schema` needs a `name` (1 to 64 letters, digits, `_` or `-`) and a `schema` (a JSON Schema object). `strict: true` is recommended. | You know the fields you need. This is the one to use. | | `{"type": "json_object"}` | A JSON object, but with no fixed shape. Describe the fields you want in the prompt, and the word JSON helps. | You cannot write a schema. Expect a code fence around the JSON from some models, and fields of the wrong type. | cURL: ```bash curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-flash", "max_tokens": 1024, "messages": [{"role": "user", "content": "Extract the person: Ana is 31 years old."}], "response_format": { "type": "json_schema", "json_schema": { "name": "person", "strict": true, "schema": { "type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, "required": ["name", "age"], "additionalProperties": false}}}}' ``` Python: ```python import json, os, requests PERSON = { "name": "person", "strict": True, "schema": { "type": "object", "properties": {"name": {"type": "string"}, "age": {"type": "integer"}}, "required": ["name", "age"], "additionalProperties": False, }, } def extract(text): res = requests.post( "https://api.ewest.ai/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"}, json={ "model": "ewest/gemini-flash", "max_tokens": 1024, "messages": [{"role": "user", "content": f"Extract the person: {text}"}], "response_format": {"type": "json_schema", "json_schema": PERSON}, }, timeout=100, ) res.raise_for_status() choice = res.json()["choices"][0] if choice["finish_reason"] != "stop": # "length" means the JSON was cut off: raise max_tokens raise RuntimeError(f"incomplete answer: {choice['finish_reason']}") data = json.loads(choice["message"]["content"]) # Check what your code relies on, even when the schema is strict. if not isinstance(data.get("name"), str) or not isinstance(data.get("age"), int): raise ValueError(f"unexpected shape: {data}") return data print(extract("Ana is 31 years old.")) ``` JavaScript: ```javascript const person = { name: "person", strict: true, schema: { type: "object", properties: { name: { type: "string" }, age: { type: "integer" } }, required: ["name", "age"], additionalProperties: false, }, }; async function extract(text) { const res = await fetch("https://api.ewest.ai/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ model: "ewest/gemini-flash", max_tokens: 1024, messages: [{ role: "user", content: `Extract the person: ${text}` }], response_format: { type: "json_schema", json_schema: person }, }), }); if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`); const choice = (await res.json()).choices[0]; // "length" means the JSON was cut off: raise max_tokens. if (choice.finish_reason !== "stop") throw new Error(`incomplete answer: ${choice.finish_reason}`); const data = JSON.parse(choice.message.content); // Check what your code relies on, even when the schema is strict. if (typeof data.name !== "string" || !Number.isInteger(data.age)) throw new Error(`unexpected shape: ${JSON.stringify(data)}`); return data; } console.log(await extract("Ana is 31 years old.")); ``` ## Which models There is no `supports_*` flag for structured output in the catalog, so it cannot be read from the model data. We ran the `json_schema` request above against these chat models, and each returned JSON that matched: `ewest/claude-haiku`, `ewest/claude-sonnet`, `ewest/claude-opus`, `ewest/claude-haiku-5.5`, `ewest/gemini-flash` and `ewest/deepseek-v4.1-flash`. A schema with an enum, an array and nested objects also matched on `ewest/claude-haiku`, `ewest/gemini-flash` and `ewest/deepseek-v4.1-flash`. Not yet tested: `ewest/gemini-3.8-flash` and `ewest/gemini-4-argon`, so do not assume they behave the same. A model may write the keys in a different order than your schema. With `json_object`, the Claude models answered with the JSON inside a Markdown code fence, and `ewest/gemini-flash` wrote a number as a string, so parse defensively. Test your own schema on the model you plan to use before you rely on it. ## Strict schemas - Set `strict: true`, list every property under `required`, and set `additionalProperties: false` on each object. - Stay with plain types: object, array, string, number, integer, boolean, `enum` and nesting. Rules such as `minimum` or `pattern` are hints at best: models can ignore them, so check those values in your code. - A schema does not make the content true. The model can fill a valid field with a wrong value, so validate what matters to you. - Streaming works with `response_format`: the JSON arrives in pieces, and is complete only at the end, so parse it once the stream is done. ## When it goes wrong - **Cut off:** if the answer hits `max_tokens` it has `finish_reason: "length"` and the JSON stops half-way, so it will not parse. Check `finish_reason` first and raise `max_tokens`. Models that think first use part of the limit for it; 1024 is a good start, and more if you set `reasoning_effort` (a limit that is too small for it is a `400` that names the minimum). - **Not valid or not the right shape:** wrap `JSON.parse` / `json.loads` in a try, check the fields you use, and on failure retry once or twice. A retry can give a different answer. Do not retry a `400`, which means the request itself must change (see [Errors](https://ewest.ai/docs/errors)). - **A malformed format:** `type` must be `text` (the default), `json_object` or `json_schema`. We check the format before any model is called and answer `400` with `param` pointing at the problem, such as `response_format.json_schema.schema`, and code `invalid_value`, `invalid_type` or `missing_required_parameter`. Fix the request; do not retry it. The same checks apply to `text.format` on Responses, where the fields are flat (`param` such as `text.format.schema`). We do not check the schema itself, so parse every answer, even when the request looked right. - **Other endpoints:** `POST /v1/responses` takes the same schema as `text.format` (`{"type": "json_schema", "name", "strict", "schema"}`). For tool arguments in a fixed shape, see [Tool calling](https://ewest.ai/docs/tool-calling). Source: https://ewest.ai/docs/structured-output --- # Responses The Responses API, with conversations you can continue, read and delete. `POST /v1/responses`, compatible with the OpenAI SDKs and agent frameworks. Each answer has an `id`; pass it as `previous_response_id` on the next request to continue the conversation, and send only the new `input`. ## Stored conversations - eWest keeps Responses conversations so you can continue them with `previous_response_id`. By default (`store: true`) we keep each conversation's inputs and outputs for 30 days after its last turn, encrypted. - Any API key of your organization can continue, read or delete them; keys of other organizations can't. - Send `store: false` to keep nothing; then send the full conversation in `input`. When the organization's switch is off, every request is treated as `store: false` whatever you send, and the final response object shows `store: false`. Owners and admins can turn storing off for the whole organization in the console (**API keys → Responses conversations**), which also deletes the conversations already stored (after a confirmation; this can't be undone). The change takes effect within about a minute. During that minute, continuing a response made in it can return 404 `not_found` instead of 400 `previous_response_not_stored`. - Instructions and tool definitions are never kept: send `instructions`, `tools`, `tool_choice`, `reasoning` and `text` on each turn. - The final response object is authoritative: `response.created` shows whether eWest intends to store the turn, and `response.completed` (or the JSON body) says whether it was stored. A turn over 8 MB is answered with `store: false`. - Replayed history counts as input tokens on each turn, as on OpenAI; storage is free. Any model may continue a conversation started with another. ## Retrieve and delete | Request | Returns | | --- | --- | | `GET /v1/responses/{id}` | The stored response: `output`, `usage`, `status`, `model`, `previous_response_id`. `instructions` is null and `tools` is empty, because they aren't kept. | | `GET /v1/responses/{id}/input_items` | That turn's input items, newest first. Query: `limit` (1-100, default 20), `order` (`asc` or `desc`), `after` or `before` (an item id). | | `DELETE /v1/responses/{id}` | Deletes the response **and every response continued from it**; earlier turns stay. | Right after an API key's first stored conversation, a `GET` or `DELETE` can return 404 for up to 30 seconds when it reaches another edge location or connection. Retry after a short wait. ## Errors | Status | Code | Meaning | | --- | --- | --- | | `400` | `previous_response_not_stored` | That response wasn't stored (`store: false`, storing turned off for the organization, or an id from before eWest kept conversations). Send the full conversation in `input`. | | `400` | `conversation_too_large` | The conversation has 500 turns or 20 MB of history. Start a new one. | | `404` | `not_found` | No such response for your organization: unknown, deleted, expired, or another organization's. A wrong API key also gets this on GET and DELETE. | | `503` | `store_unavailable` | Stored conversations are briefly unavailable; retry. | Source: https://ewest.ai/docs/responses --- # Files Send images, PDFs and audio to eWest models, and get generated files back. A file always travels inside the request that uses it. There is no separate upload step and no file IDs to manage: you either put the file in the request body, or give the address of a file that is already on the public internet. This page lists what each endpoint takes, the limits, and what happens when a file cannot be used. Generated images, video and audio come back as links on `cdn.ewest.ai`. ## Three ways to send a file | Way | How it looks | Where it works | | --- | --- | --- | | Public https URL | The address of the file, such as `https://example.com/photo.jpg`. | Images in chat completions, `image_urls` on `/v1/images/edits` and `/v1/images/generations`, `image_url` and `end_image_url` on `/v1/videos/generations`, and `audio_url` on `/v1/audio/transcriptions`. We (or the model) download it when the request runs, so it must be readable without signing in. Messages and Responses take base64 only. | | Base64 data URI | `data:image/png;base64,` followed by the file's bytes, base64-encoded, inside the JSON body. | Chat completions (images and PDFs), Responses (images and PDFs) and, as a `source` block, Messages. Audio goes in as plain base64 (see below). | | Multipart upload | A `multipart/form-data` request with the file as a form field, like the OpenAI libraries send. | `POST /v1/images/edits` (field `image`) and `POST /v1/audio/transcriptions` (field `file`). | > You cannot upload a file once and refer to it by ID: `POST /v1/files` does not exist and returns `404 not_found`. To reuse a file, send it again, or host it and send its URL. If you use [stored Responses conversations](https://ewest.ai/docs/responses#stored-conversations), the files in earlier turns are part of the stored conversation and are replayed to the model on each later turn (turns with very large files are not stored). ## What each endpoint takes | Endpoint | Input | Field | How to send it | | --- | --- | --- | --- | | ``/v1/chat/completions`` | Images, PDFs, audio (models that list them) | `messages[].content` parts | URL or data URI for an image; data URI for a PDF; base64 for audio | | ``/v1/messages`` | Images, and PDFs for models that list `pdf` | `image` and `document` content blocks | A base64 `source`: `{"type": "base64", "media_type": "image/png", "data": "..."}` | | ``/v1/responses`` | Images, and PDFs for models that list `pdf` | `input_image` and `input_file` parts | A data URI in `image_url` (images) or `file_data` (PDFs) | | ``/v1/images/edits`` | 1 or more images (the model page says how many) | `image` or `image[]`; or `image_urls` | Multipart upload, or public https URLs in JSON | | ``/v1/images/generations`` | Input images, for models that edit | `image_urls` | Public https URLs | | ``/v1/videos/generations`` | A start image, and for some models an end image | `image_url`, `end_image_url` | Public https URLs only | | ``/v1/audio/transcriptions`` | One audio file | `file`, or `audio_url` | Multipart upload, or a public https URL in JSON | | ``/v1/audio/generations`, `/v1/audio/speech`, `/v1/embeddings`, `/v1/rerank`` | Text only | — | — | | ``/v1/3d/generations`` | One image (Hunyuan 3D: plus optional extra views) | `image_url`, `view_images` | Public https URLs in JSON | Which kinds of file a model accepts is in its `input_modalities` (`text`, `image`, `pdf` and `audio` are covered on this page), shown on the model page and returned by `GET /v1/models/{id}`. A model that does not list a kind either ignores that part of your message or answers with a `400`, so check the list before you send. ## Files in a chat message Make `content` a list of parts instead of a string. A text part is `{"type": "text", "text": "..."}`. For a picture use an `image_url` part, whose `url` is either a public https address or a data URI. For a PDF use a `file` part with `file_data` set to a data URI (`data:application/pdf;base64,...`) and a `filename`. For sound, models that list `audio` take an `input_audio` part: `{"type": "input_audio", "input_audio": {"data": "", "format": "wav"}}`, with the bytes as plain base64 (no `data:` prefix). Several files can go in one message. cURL: ```bash # 1. A public https URL curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-flash", "messages": [{"role": "user", "content": [ {"type": "text", "text": "What is in this picture?"}, {"type": "image_url", "image_url": {"url": "https://example.com/photo.jpg"}}]}]}' # 2. A local file as a base64 data URI. The body is piped in, so a large file # does not run into the shell's argument limit. { printf '{"model": "ewest/gemini-flash", "messages": [{"role": "user", "content": [{"type": "text", "text": "What is in this picture?"}, {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,' base64 < photo.jpg | tr -d "\n" printf '"}}]}]}' } | curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ --data-binary @- ``` Python: ```python import base64, mimetypes, os, requests mimetypes.add_type("image/webp", ".webp") # older Pythons do not know WebP def content_part(source): """A message part for a public https image URL, or for a local image or PDF file.""" if source.startswith("https://"): return {"type": "image_url", "image_url": {"url": source}} mime = mimetypes.guess_type(source)[0] if mime not in ("image/jpeg", "image/png", "image/webp", "application/pdf"): raise ValueError(f"unsupported file type: {source}") with open(source, "rb") as f: uri = f"data:{mime};base64," + base64.b64encode(f.read()).decode() if mime == "application/pdf": return {"type": "file", "file": {"filename": os.path.basename(source), "file_data": uri}} return {"type": "image_url", "image_url": {"url": uri}} SOURCE = "photo.jpg" # or "https://example.com/photo.jpg", or "report.pdf" res = requests.post( "https://api.ewest.ai/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"}, json={ "model": "ewest/gemini-flash", "messages": [{"role": "user", "content": [ {"type": "text", "text": "What is in this picture?"}, content_part(SOURCE), ]}], }, timeout=100, ) if not res.ok: raise RuntimeError(f"{res.status_code}: {res.text}") print(res.json()["choices"][0]["message"]["content"]) ``` JavaScript: ```javascript const { readFile } = await import("node:fs/promises"); const MIME = { jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", webp: "image/webp", pdf: "application/pdf" }; // A message part for a public https image URL, or for a local image or PDF file. async function contentPart(source) { if (source.startsWith("https://")) return { type: "image_url", image_url: { url: source } }; const mime = MIME[source.split(".").pop().toLowerCase()]; if (!mime) throw new Error(`unsupported file type: ${source}`); const uri = `data:${mime};base64,${(await readFile(source)).toString("base64")}`; if (mime === "application/pdf") return { type: "file", file: { filename: source.split("/").pop(), file_data: uri } }; return { type: "image_url", image_url: { url: uri } }; } const SOURCE = "photo.jpg"; // or "https://example.com/photo.jpg", or "report.pdf" const res = await fetch("https://api.ewest.ai/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ model: "ewest/gemini-flash", messages: [{ role: "user", content: [{ type: "text", text: "What is in this picture?" }, await contentPart(SOURCE)] }], }), signal: AbortSignal.timeout(100_000), }); if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`); console.log((await res.json()).choices[0].message.content); ``` - Base64 makes a file about a third bigger, and the whole request must stay under the body limit below. - Files in a message count as input tokens, so large images and PDFs cost more. The `usage` object in the answer shows how many. - Send the file again in every request that needs it. The model only sees what is in the request, so a follow-up question about a picture needs the picture in `messages` again. ## Uploading a file Image editing and transcription take real file uploads, with the same fields as OpenAI's `images.edit` and `audio.transcriptions`, so the OpenAI libraries work as they are. To use the model on a file you already host, send its public https address instead: `image_urls` for images and `audio_url` for audio, in a JSON body. cURL: ```bash # 1. Upload a file (multipart/form-data; curl adds the content type) curl https://api.ewest.ai/v1/images/edits \ -H "Authorization: Bearer $EWEST_KEY" \ -F model=ewest/nano-banana-2.1 \ -F prompt="Make the sky a deep sunset orange" \ -F image=@photo.png # 2. Or a public https URL in a JSON body curl https://api.ewest.ai/v1/images/edits \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/nano-banana-2.1", "prompt": "Make the sky a deep sunset orange", "image_urls": ["https://example.com/photo.png"]}' # → {"data": [{"url": "https://cdn.ewest.ai/img/…"}]} ``` Python: ```python import os, requests def edit_image(image, prompt): """image: a local file path, or a public https URL. Returns the edited image's URL.""" url = "https://api.ewest.ai/v1/images/edits" headers = {"Authorization": f"Bearer {os.environ['EWEST_KEY']}"} fields = {"model": "ewest/nano-banana-2.1", "prompt": prompt} if image.startswith("https://"): res = requests.post(url, headers=headers, json={**fields, "image_urls": [image]}, timeout=120) else: with open(image, "rb") as f: # requests builds the multipart body and boundary res = requests.post(url, headers=headers, data=fields, files={"image": f}, timeout=120) if not res.ok: raise RuntimeError(f"{res.status_code}: {res.text}") return res.json()["data"][0]["url"] print(edit_image("photo.png", "Make the sky a deep sunset orange")) ``` JavaScript: ```javascript // openAsBlob needs Node 19.8 or newer. const { openAsBlob } = await import("node:fs"); // image: a local file path, or a public https URL. Returns the edited image's URL. async function editImage(image, prompt) { const url = "https://api.ewest.ai/v1/images/edits"; const auth = { Authorization: `Bearer ${process.env.EWEST_KEY}` }; let res; if (image.startsWith("https://")) { res = await fetch(url, { method: "POST", headers: { ...auth, "Content-Type": "application/json" }, body: JSON.stringify({ model: "ewest/nano-banana-2.1", prompt, image_urls: [image] }), signal: AbortSignal.timeout(120_000), }); } else { const form = new FormData(); form.set("model", "ewest/nano-banana-2.1"); form.set("prompt", prompt); form.set("image", await openAsBlob(image), image.split("/").pop()); // fetch sets the multipart content type and boundary itself. res = await fetch(url, { method: "POST", headers: auth, body: form, signal: AbortSignal.timeout(120_000) }); } if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`); return (await res.json()).data[0].url; } console.log(await editImage("photo.png", "Make the sky a deep sunset orange")); ``` The audio version is on the [Audio](https://ewest.ai/docs/audio#transcription) page. A file you upload is kept on `cdn.ewest.ai` for about 7 days so the model can read it, then deleted. Its address is not returned in the API response (it appears in your request details in the console) and cannot be guessed, but it is not behind a login, so do not upload anything you would not want a person holding that address to see. ## Size and format limits | What | Limit | Formats | | --- | --- | --- | | Chat request, files included | The whole request, files included, must stay under about 32 MB. Each model also has its own limit per image or document, shown by the error when you go over it. | Use PNG, JPEG or WebP for images. A model that cannot read a file says so in the error. | | Image edit upload | 20 MB per image, but the whole request (all images and fields) is still held to the 32 MB limit, so two 17 MB images are refused. The number of images is limited per model; the model page shows it. | PNG, JPEG or WebP, detected from the file's content, not its name. | | Video start and end image | The model's own limits. | Some models take only JPEG and PNG; the error says which. | | Transcription audio | 25 MB per file (26 MB for the request) and 20 minutes. | mp3, wav, m4a, ogg, flac or webm, detected from the content. | ## Public URLs - Use `https://` addresses. Image edits, video and `audio_url` refuse other schemes at once with a `400`, and image edits and `audio_url` also refuse addresses with a user name or password in them. Only chat completions, Responses and Messages take a file inline (a data URI, or a base64 `source` in Messages) instead of an address. - The host must be reachable from the public internet. Image edits and `audio_url` refuse addresses on private networks, `localhost` and names ending in `.local` or `.internal` with a `400`. - The file must download without signing in or any cookie. A link to a page that shows the file, an expiring link that has run out, and a link that needs a header or token will all fail. Open the address in a private browser window first. - Use the direct address of the file. For some video models we check the start image before the job is created, and that check does not follow redirects. - Make sure the link stays valid until your request has finished. For a video job that includes the time the job waits to start. - Cloud Storage links are refused with a `400` on every endpoint, images and video included, even when signed or public. Host the file elsewhere (any public https URL). ## When a file cannot be used These are all `invalid_request_error`, so do not retry them unchanged: fix the file or the address first. The `param` field names the field at fault. [Errors](https://ewest.ai/docs/errors) has the full list and what is safe to retry. | Situation | Status | `param` | What to do | | --- | --- | --- | --- | | The whole request is over about 32 MB, on any endpoint and uploads included | `413` | `—` | Send smaller or fewer files. Use a URL instead of base64 for big files, which also saves a third of the bytes. | | One uploaded image is over 20 MB (and the request is still under 32 MB) | `413` | ``image`` | Resize or compress it. | | One uploaded audio file is over 25 MB (and the request is still under 26 MB) | `413` | ``file`` | Cut it into parts or compress it. | | An uploaded image is not PNG, JPEG or WebP | `400` | ``image`` | Convert it. A GIF is refused here. | | An audio file (uploaded, or downloaded from `audio_url`) is not a supported audio format, or its length cannot be read | `400` | ``file`` | Use mp3, wav, m4a, ogg, flac or webm. | | The audio (uploaded, or from `audio_url`) is longer than the model allows (20 minutes) | `400` | ``file`` | Split it and transcribe the parts. | | `audio_url` is not a public https address | `400` | ``audio_url`` | Use a public https address. | | `audio_url` cannot be downloaded, or the file is over 25 MB | `400` | ``audio_url`` | Check the address in a browser, or upload the file. | | On `/v1/images/edits`, `image_urls` has an address that is not public https (a data URI too) | `400` | ``image_urls`` | Use public https addresses, or upload the file. | | More input images than the model takes | `400` | ``image_urls`` | Send fewer. The model page lists the number. | | `mask_url` or `mask` on a model without `supports_mask`, with more than one image, not public https, in another format than PNG, JPEG or WebP, or of another size than the image | `400` | ``mask_url`` | Masks work for one image on models with `supports_mask`: white is changed, black is kept, same size as the image. | | `image_url` or `end_image_url` is not an https address (a data URI too) | `400` | ``image_url` or `end_image_url`` | Host the image and send its https address. | | A video model cannot use the start image (wrong format, unreadable, or redirects) | `400` | ``image_url` or `end_image_url`` | Use the format the message names, at its direct address. | | An image or document in a chat message is too large for the model | `usually 400` | `—` | Shrink it. The message names the limit. | | A file URL in a chat message cannot be downloaded | `usually 400` | `—` | Check the address, or send the file as a data URI. | | A file address is a Cloud Storage link, signed or public, on any endpoint | `400` | `the field with the link` | Host the file elsewhere (any public https URL). | A public https address that cannot be read (a 404, for example) is not always caught up front. At the time of writing, image edits can answer `400 content_policy` with the message that the request was rejected by the model's safety filters, although nothing is wrong with the prompt. Video models that do not check the start image first accept the job (`202`) and it then ends as a failed job whose error says the model failed to generate; a failed job is not charged. If you see either for an otherwise fine request, test the file address first. This behaviour may change. ## Files you get back Generated files are copied to `cdn.ewest.ai`, so you always get an eWest address, and stay there for 7 days. After that the link stops working: download what you need to keep. | Endpoint | What comes back | | --- | --- | | ``/v1/images/generations`, `/v1/images/edits`` | `data[].url` on `cdn.ewest.ai`. Add `"response_format": "b64_json"` to get the bytes in the response as well. | | ``/v1/videos/generations`` | A job. When it has `succeeded`, `output.url` is the video on `cdn.ewest.ai`. | | ``/v1/audio/generations`` | A job. `output.url` is the audio file. | | ``/v1/3d/generations`` | A job. `output.url` is the GLB file and `output.files` lists every format. See [3D jobs](https://ewest.ai/docs/3d). | | ``/v1/audio/speech`` | The audio bytes, or with `"response_format": "url"` a link on `cdn.ewest.ai`. | | ``/v1/audio/transcriptions`, chat, embeddings` | Text or JSON. No file. | If a model finishes but we cannot store its result, an image request gets a `502 api_error`, and a video or audio job ends as a failed job. Try again. See [Rate limits and retries](https://ewest.ai/docs/rate-limits) for how to retry. ## Where to go next - [Chat](https://ewest.ai/docs/chat), for the messages that carry files, and [Structured output](https://ewest.ai/docs/structured-output) to get data out of a document as JSON. - [Images](https://ewest.ai/docs/images) for editing, [Video jobs](https://ewest.ai/docs/video) for image-to-video, and [Audio](https://ewest.ai/docs/audio) for transcription. - [Errors](https://ewest.ai/docs/errors) for every status and type, and [Models](https://ewest.ai/docs/models) for which model takes which kind of file. Source: https://ewest.ai/docs/files --- # Images Generate and edit images. `POST /v1/images/generations` returns image URLs on `cdn.ewest.ai`, kept for 7 days. Ask for `"response_format": "b64_json"` to also get the bytes. Some models take extra options listed on their model page: `aspect_ratio`, `resolution` and `quality`. Models with image editing accept input images as `image_urls` (public https URLs), or as files on `POST /v1/images/edits` like OpenAI's images.edit. Input images must be PNG, JPEG or WebP, up to 20 MB each when you upload them. Image addresses must be public `https://` URLs; a base64 data URI is not accepted here. See [Files](https://ewest.ai/docs/files) for the limits, what the errors mean and how generated images are stored. cURL: ```bash curl https://api.ewest.ai/v1/images/generations \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/flux-schnell", "prompt": "a cozy cabin in the snow"}' # → {"data": [{"url": "https://cdn.ewest.ai/img/…"}]} ``` Python: ```python import os from openai import OpenAI client = OpenAI(base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"]) image = client.images.generate(model="ewest/flux-schnell", prompt="a cozy cabin in the snow") print(image.data[0].url) ``` JavaScript: ```javascript import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY }); const image = await client.images.generate({ model: "ewest/flux-schnell", prompt: "a cozy cabin in the snow" }); console.log(image.data[0].url); ``` Source: https://ewest.ai/docs/images --- # Video jobs Generate video as a job, with live progress. Video takes from seconds to minutes, so it runs as a job. `POST /v1/videos/generations` returns `202` with a job; then follow it in one of three ways: - `GET /v1/jobs/{id}/events`: Server-Sent Events with live `progress` and `eta_seconds`. - `GET /v1/jobs/{id}`: poll every few seconds. - `"webhook_url"` in the request: we POST the finished job to it. Deliveries are not signed or retried yet, so also poll or follow the events as a backup. `eta_seconds` is `null` when a job runs longer than usual. Finished videos are on `cdn.ewest.ai` for 7 days. For image-to-video, send `image_url` (and `end_image_url` on models that take a last frame) as a public `https://` address. Uploads and data URIs are not accepted, and some models take only JPEG and PNG. [Files](https://ewest.ai/docs/files#urls) explains how to make an address work and which errors you can get. cURL: ```bash # 1. Create the job curl https://api.ewest.ai/v1/videos/generations \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/veo-3.1-fast", "prompt": "A red fox walks through fresh snow"}' # → 202 {"id": "job_…", "status": "queued", "progress": 0, "eta_seconds": …} # 2. Follow live progress (Server-Sent Events), or poll GET /v1/jobs/job_… curl -N https://api.ewest.ai/v1/jobs/job_…/events -H "Authorization: Bearer $EWEST_KEY" ``` Python: ```python import os, time, requests H = {"Authorization": f"Bearer {os.environ['EWEST_KEY']}"} job = requests.post("https://api.ewest.ai/v1/videos/generations", headers=H, json={"model": "ewest/veo-3.1-fast", "prompt": "A red fox walks through fresh snow"}).json() while job["status"] not in ("succeeded", "failed"): time.sleep(3) job = requests.get(f"https://api.ewest.ai/v1/jobs/{job['id']}", headers=H).json() print(job["status"], job["progress"], job["eta_seconds"]) print(job["output"]["url"] if job["output"] else job["error"]) ``` JavaScript: ```javascript const H = { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }; let job = await (await fetch("https://api.ewest.ai/v1/videos/generations", { method: "POST", headers: H, body: JSON.stringify({ model: "ewest/veo-3.1-fast", prompt: "A red fox walks through fresh snow" }), })).json(); while (!["succeeded", "failed"].includes(job.status)) { await new Promise((r) => setTimeout(r, 3000)); job = await (await fetch(`https://api.ewest.ai/v1/jobs/${job.id}`, { headers: H })).json(); } console.log(job.output?.url ?? job.error); ``` Source: https://ewest.ai/docs/video --- # Audio Music and sound effects, speech, and transcription. ## Music and sound `POST /v1/audio/generations` with `model`, `prompt` and, where the model allows it, `duration` (seconds), `instrumental` or `loop`. It runs as a job, exactly like [video](https://ewest.ai/docs/video): follow `/v1/jobs/{id}/events`, poll, or pass a `webhook_url`. The finished MP3 is on `cdn.ewest.ai` for 7 days. cURL: ```bash # 1. Create the job curl https://api.ewest.ai/v1/audio/generations \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/eleven-music-v2.5", "prompt": "upbeat lo-fi beat with warm piano", "duration": 30}' # → 202 {"id": "job_…", "type": "audio", "status": "queued", "progress": 0, …} # 2. Follow it (Server-Sent Events), or poll GET /v1/jobs/job_… curl -N https://api.ewest.ai/v1/jobs/job_…/events -H "Authorization: Bearer $EWEST_KEY" # → … "output": {"url": "https://cdn.ewest.ai/aud/….mp3"} ``` Python: ```python import os, time, requests H = {"Authorization": f"Bearer {os.environ['EWEST_KEY']}"} job = requests.post("https://api.ewest.ai/v1/audio/generations", headers=H, json={"model": "ewest/eleven-music-v2.5", "prompt": "upbeat lo-fi beat with warm piano", "duration": 30}).json() while job["status"] not in ("succeeded", "failed"): time.sleep(2) job = requests.get(f"https://api.ewest.ai/v1/jobs/{job['id']}", headers=H).json() print(job["output"]["url"] if job["output"] else job["error"]) ``` JavaScript: ```javascript const H = { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }; let job = await (await fetch("https://api.ewest.ai/v1/audio/generations", { method: "POST", headers: H, body: JSON.stringify({"model": "ewest/eleven-music-v2.5", "prompt": "upbeat lo-fi beat with warm piano", "duration": 30}), })).json(); while (!["succeeded", "failed"].includes(job.status)) { await new Promise((r) => setTimeout(r, 2000)); job = await (await fetch(`https://api.ewest.ai/v1/jobs/${job.id}`, { headers: H })).json(); } console.log(job.output?.url ?? job.error); ``` ## Speech `POST /v1/audio/speech` with `model`, `input` (the text) and `voice` returns the audio file, like OpenAI's API. Voices differ per model (see the model page). With `"response_format": "url"` you get a `cdn.ewest.ai` link instead, kept for 7 days. cURL: ```bash curl https://api.ewest.ai/v1/audio/speech \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/eleven-v4-turbo", "input": "Welcome to eWest."}' \ --output speech.audio # Add "response_format": "url" to get {"url": "https://cdn.ewest.ai/aud/…"} instead of the bytes. ``` Python: ```python import os from openai import OpenAI client = OpenAI(base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"]) audio = client.audio.speech.create(model="ewest/eleven-v4-turbo", voice="Rachel", input="Welcome to eWest.") audio.write_to_file("speech.audio") ``` JavaScript: ```javascript import fs from "node:fs"; import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY }); const audio = await client.audio.speech.create({ model: "ewest/eleven-v4-turbo", voice: "Rachel", input: "Welcome to eWest." }); fs.writeFileSync("speech.audio", Buffer.from(await audio.arrayBuffer())); ``` ## Transcription `POST /v1/audio/transcriptions` takes an audio `file` (multipart, up to 25 MB and 20 minutes) or a public `audio_url` in JSON. `response_format` is `json` (default), `text` or `verbose_json` (language, duration and word timestamps where the model provides them). The file must be mp3, wav, m4a, ogg, flac or webm; [Files](https://ewest.ai/docs/files#problems) lists the errors for files that are too big, too long or in another format. cURL: ```bash curl https://api.ewest.ai/v1/audio/transcriptions \ -H "Authorization: Bearer $EWEST_KEY" \ -F model=ewest/scribe-v2 \ -F file=@meeting.mp3 \ -F response_format=verbose_json # → {"text": "…", "language": "en", "duration": 92.4, "words": [{"word": "Hello", "start": 0.1, "end": 0.4}, …]} ``` Python: ```python import os from openai import OpenAI client = OpenAI(base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"]) with open("meeting.mp3", "rb") as f: result = client.audio.transcriptions.create(model="ewest/scribe-v2", file=f) print(result.text) ``` JavaScript: ```javascript import fs from "node:fs"; import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY }); const result = await client.audio.transcriptions.create({ model: "ewest/scribe-v2", file: fs.createReadStream("meeting.mp3") }); console.log(result.text); ``` Source: https://ewest.ai/docs/audio --- # 3D jobs Generate 3D models from text or images as a job, and download GLB, OBJ or FBX files. A 3D model takes a few minutes, so it runs as a job, exactly like [video](https://ewest.ai/docs/video). `POST /v1/3d/generations` returns `202` with a job; follow it with `GET /v1/jobs/{id}/events`, poll `GET /v1/jobs/{id}`, or pass a `webhook_url`. ## The request | Field | What it does | | --- | --- | | ``model`` | The model id, for example `ewest/hunyuan-3d-3.1-pro`. | | ``prompt`` | Text to 3D. Send `prompt` or `image_url`, never both. | | ``image_url`` | Image to 3D: a public `https://` address of the front view (JPEG, PNG or WebP). Hunyuan 3D: 128 to 5,000 px, up to 8 MB. Tripo H3.1: up to 20 MB. | | ``view_images`` | Hunyuan 3D only. Extra views as an object: `back`, `left`, `right`, `top`, `bottom`, `left_front`, `right_front`, each a public https address (JPEG or PNG). Needs `image_url`. | | ``generate_type`` | `normal` (textured, default) or `geometry` (untextured). | | ``enable_pbr`` | Add PBR material textures. Not with `geometry`. Default: off for Hunyuan 3D (a fixed extra charge), on for Tripo H3.1 (no extra charge). | | ``face_count`` | Target polygon count. Hunyuan 3D: 40,000 to 1,500,000 (default 500,000). Tripo H3.1: 1,000 to 2,000,000, chosen by the model when left out; above 1,500,000 needs `geometry_quality: detailed`, and a quad mesh has at most 150,000. | | ``texture_quality`` | Tripo H3.1 only. `standard` (default) or `detailed` (HD, higher-resolution textures, costs more). Not with `geometry`. | | ``geometry_quality`` | Tripo H3.1 only. `standard` (default) or `detailed` (finer geometry, costs more). | | ``quad`` | Tripo H3.1 only. A quad (four-sided) mesh instead of triangles, costs more. The mesh comes as an FBX file and there is no GLB; without `face_count` it has 10,000 faces. | | ``negative_prompt`` | Tripo H3.1 only, with `prompt`. What to avoid, up to 255 characters. | | ``seed`` | Tripo H3.1 only. An integer from 0 to 2,147,483,647 that makes the result repeatable. | | ``auto_size`` | Tripo H3.1 only. Scale the model to real-world size in meters. | | ``orientation`` | Tripo H3.1 only, with `image_url`. `default` or `align_image` (turn the model to match the image). | | ``texture_alignment`` | Tripo H3.1 only, with `image_url`. `original_image` (default) or `geometry`. | A `geometry` model is cheaper than a textured one. On Hunyuan 3D, `view_images`, `enable_pbr` and a `face_count` other than the default each add a fixed amount to the price of a generation, however many views you send. On Tripo H3.1 the price depends on text or image input, the texture level, `geometry_quality: detailed` and `quad`; PBR, face count and the other options are free. An option a model does not take is a `400`. The model page lists the exact prices. ## The result When the job has `succeeded`, `output.url` is the GLB file (the FBX file for a quad mesh) and `output.files` lists every file by format (`glb`, `pbr_glb` for Tripo H3.1, `fbx`, and as the model returns them `obj` with its `mtl` and `texture`, and others), each with its `url`, `content_type` and `size`. `output.thumbnail_url` is a preview image. All files are on `cdn.ewest.ai` for 7 days. Files are tens of megabytes: download them, do not hotlink them. If any file cannot be stored, the job ends as `failed` with `storage_error` and is not billed. cURL: ```bash # 1. Create the job (text to 3D; send "image_url" instead of "prompt" to build from an image) curl https://api.ewest.ai/v1/3d/generations \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/hunyuan-3d-3.1-pro", "prompt": "a ceramic teapot with a bamboo handle", "enable_pbr": true}' # → 202 {"id": "job_…", "type": "3d", "status": "queued", "progress": 0, …} # 2. Follow it (Server-Sent Events), or poll GET /v1/jobs/job_… curl -N https://api.ewest.ai/v1/jobs/job_…/events -H "Authorization: Bearer $EWEST_KEY" # → … "output": {"url": "https://cdn.ewest.ai/3d/….glb", "files": {"glb": {…}, "obj": {…}}} ``` Python: ```python import os, time, requests H = {"Authorization": f"Bearer {os.environ['EWEST_KEY']}"} job = requests.post("https://api.ewest.ai/v1/3d/generations", headers=H, json={"model": "ewest/hunyuan-3d-3.1-pro", "prompt": "a ceramic teapot with a bamboo handle", "enable_pbr": True}).json() while job["status"] not in ("succeeded", "failed"): time.sleep(5) job = requests.get(f"https://api.ewest.ai/v1/jobs/{job['id']}", headers=H).json() print(job["status"], job["progress"]) print(job["output"]["files"] if job["output"] else job["error"]) # the files by format (glb, ...) ``` JavaScript: ```javascript const H = { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }; let job = await (await fetch("https://api.ewest.ai/v1/3d/generations", { method: "POST", headers: H, body: JSON.stringify({ "model": "ewest/hunyuan-3d-3.1-pro", "prompt": "a ceramic teapot with a bamboo handle", enable_pbr: true }), })).json(); while (!["succeeded", "failed"].includes(job.status)) { await new Promise((r) => setTimeout(r, 5000)); job = await (await fetch(`https://api.ewest.ai/v1/jobs/${job.id}`, { headers: H })).json(); } console.log(job.output?.files ?? job.error); ``` Source: https://ewest.ai/docs/3d --- # Embeddings and rerank Vectors for search, and ordering documents by relevance. ## Embeddings `POST /v1/embeddings`, compatible with the OpenAI SDKs. Pass one string or a list in `input`; each comes back as a vector in `data`, in the same order. Add `"encoding_format": "base64"` to get each vector as base64-encoded float32 instead of a list of numbers, as in the OpenAI API. cURL: ```bash curl https://api.ewest.ai/v1/embeddings \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-embedding", "input": ["How do I reset my password?", "Billing questions"]}' # → {"data": [{"embedding": [0.012, -0.034, …], "index": 0}, …], "usage": {…}} ``` Python: ```python import os from openai import OpenAI client = OpenAI(base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"]) res = client.embeddings.create(model="ewest/gemini-embedding", input=["How do I reset my password?"]) print(len(res.data[0].embedding)) ``` JavaScript: ```javascript import OpenAI from "openai"; const client = new OpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY }); const res = await client.embeddings.create({ model: "ewest/gemini-embedding", input: ["How do I reset my password?"] }); console.log(res.data[0].embedding.length); ``` ## Rerank `POST /v1/rerank` takes a `query` and a list of `documents` (strings) and returns `results` ordered by `relevance_score`, each with the `index` of the document. Use `top_n` to keep only the best matches. cURL: ```bash curl https://api.ewest.ai/v1/rerank \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/semantic-ranker", "query": "How do I get a refund?", "top_n": 2, "documents": ["Refunds are issued within 5 days.", "Our office is in Yerevan.", "Contact support to cancel an order."]}' # → {"results": [{"index": 0, "relevance_score": 0.91}, {"index": 2, "relevance_score": 0.42}]} ``` Python: ```python import os, requests res = requests.post( "https://api.ewest.ai/v1/rerank", headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"}, json={"model": "ewest/semantic-ranker", "query": "How do I get a refund?", "top_n": 2, "documents": ["Refunds are issued within 5 days.", "Our office is in Yerevan."]}, ).json() for r in res["results"]: print(r["index"], r["relevance_score"]) ``` JavaScript: ```javascript const res = await (await fetch("https://api.ewest.ai/v1/rerank", { method: "POST", headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ model: "ewest/semantic-ranker", query: "How do I get a refund?", top_n: 2, documents: ["Refunds are issued within 5 days.", "Our office is in Yerevan."], }), })).json(); console.log(res.results); ``` Source: https://ewest.ai/docs/embeddings --- # Trace IDs Find any request in the console. Every response carries an `x-request-id` header (for video, the job ID). Paste it into **Console → Requests** to see the request's timing and cost. Chat prompts and answers aren't stored; media job inputs are kept 7 days for your traces, then deleted. Usage and cost are kept permanently. Source: https://ewest.ai/docs/traces --- # Errors What each error means, whether to retry, and what to do. Errors use the OpenAI shape: `{"error": {"message", "type", "code", "param"}}`. `code` is the HTTP status as a string unless a more specific one applies (for example `model_not_found`), and `param` names the field at fault when there is one. The one exception is the Anthropic Messages endpoints (`/v1/messages` and `/v1/messages/count_tokens`), which use [Anthropic's envelope](#messages-envelope). > Branch on the HTTP status and the stable `type` or `code`, never on `message`. Messages are written for people and can change wording at any time. ## Errors on the Messages endpoints The status codes, `code` and `param` are the same everywhere, but `/v1/messages` and `/v1/messages/count_tokens` wrap the error the way Anthropic does, so the Anthropic libraries read it: `{"type": "error", "error": {"type", "message", "code", "param"}, "request_id": "..."}`. Only `error.type` changes, to Anthropic's name for the status. `code` and `param` stay inside `error` (the libraries ignore them), so `model_not_found` and `param: model` work as on the other endpoints. `request_id` is the same as the `x-request-id` header. | Status | Messages endpoints | Other endpoints | | --- | --- | --- | | `400` | `invalid_request_error` | `invalid_request_error` | | `401` | `authentication_error` | `invalid_api_key` | | `402` | `billing_error` | `insufficient_budget or insufficient_balance` | | `403` | `permission_error` | `permission_error` | | `404` | `not_found_error` | `not_found_error` | | `429` | `rate_limit_error` | `rate_limit_error` | | `500` | `api_error` | `api_error` | | `502` | `api_error` | `model_unavailable or api_error` | | `503` | `overloaded_error` | `api_error` | | `504` | `timeout_error` | `timeout_error` | > On the Messages endpoints branch on the status, or on `code` for the specific cases such as `insufficient_budget`. The rest of this page uses the OpenAI-style types; read it together with the table above when you call `/v1/messages`. ## Request errors These are about the key, the account or the service, not about what you sent. The same request can succeed later, after you change the key or the account, or after a short wait. | Status | Type | Meaning | Retry? | What to do | | --- | --- | --- | --- | --- | | `401` | `invalid_api_key` | The key is missing, invalid, expired or blocked. | No | Check the `Authorization` header and the key under [API keys](https://ewest.ai/keys). Create a new key if it expired or was blocked. | | `402` | `insufficient_budget` | The key's own budget would be exceeded by this request. This is a 402 on every endpoint, chat included. | No, not until the budget changes | Raise the key's budget, or use another key. See [budget or rate](https://ewest.ai/docs/rate-limits#budget-vs-rate). | | `402` | `insufficient_balance` | The organisation's prepaid balance is too low for this request. Only returned when prepaid billing is enforced for your account. | No, not until funds are added | Add funds in the console under Billing, then send the request again. | | `403` | `permission_error` | The key is not allowed to use this model. | No | Use a model on the key's list, or change the list in the console. | | `429` | `rate_limit_error` | The key's own limit on requests or tokens per minute (code `rate_limit_exceeded`). Decide by the status `429`. | Yes, with backoff | Wait the seconds in the `retry-after` header, then retry with growing, randomised delays. See [Rate limits and retries](https://ewest.ai/docs/rate-limits). | | `429` | `rate_limit_error` | This model is busy right now (code `model_busy`, with a `retry-after` header). Some models run on a limited number of machines; over that limit a request is turned away at once instead of waiting. | Yes, after `retry-after` | Wait the seconds in `retry-after`, then retry. Your own limits are not the cause. For video and music, submit again later. | | `500` | `api_error` | An unexpected error on our side. | Yes, a few times | Retry with backoff. If it keeps failing, contact support with the [trace ID](https://ewest.ai/docs/traces). | | `502` | `model_unavailable or api_error` | The model could not answer right now. This includes a model that was busy, rate limited or too slow behind the scenes. | Yes, with backoff | Retry with backoff. Keep the `x-request-id` if it keeps happening. | | `503` | `api_error` | Our own service is briefly unavailable. | Yes, with backoff | Retry with backoff. | | `504` | `timeout_error` | An image or speech request took too long. Chat requests that time out end as `502 model_unavailable` instead. | Yes, once or twice | Retry. For video and music use [jobs](https://ewest.ai/docs/video), which have no such limit on the request. | ## Model and validation errors These say the request itself is the problem. Sending the same request again returns the same error, so fix it first. | Status | Type or code | Meaning | Retry? | What to do | | --- | --- | --- | --- | --- | | `400` | `invalid_request_error` | A parameter is missing, has the wrong type or is out of range. `param` names it. A missing `model` has code `missing_required_parameter` on chat/completions, completions, messages, responses and rerank; other endpoints still use code `400` for it. | No | Fix the parameter named in `param`, and check the model's page for what it accepts. | | `400` | `invalid_type` | A field has the wrong kind of value, such as `response_format` that is not an object. `param` names it with dots (for example `response_format.json_schema.schema`). | No | Send the kind of value `param` asks for. | | `400` | `invalid_value` | A field has a value that is not allowed, such as a `response_format.type` other than `text`, `json_object` or `json_schema`, or a schema `name` that is not 1 to 64 letters, digits, underscores or dashes. | No | Use one of the allowed values named in the message. | | `400` | `missing_required_parameter` | A required field is missing. For structured output, `json_schema` needs both a `name` and a `schema` (chat: `response_format.json_schema.*`; Responses: `text.format.*`). A missing `model` has this code too. | No | Add the field named in `param`. | | `400` | `unsupported_parameter` | The model does not take that parameter. | No | Remove the parameter, or choose a model that supports it. | | `400` | `unsupported_value` | The model does not take that value. For `reasoning_effort` (Responses: `reasoning.effort`) the message lists the supported efforts, which are also in the model's `reasoning_efforts` in `GET /v1/models`. On Claude Haiku 4.5 it is also returned when `max_tokens` is too small for the effort; the message names the smallest that works: 1025 for `low`, 1366 for `medium` and `high` (only `ewest/claude-haiku`; on `/v1/messages` it takes no `output_config.effort` at all). | No | Use one of the listed values, or raise the output limit. | | `400` | `model_not_supported` | The model is the wrong type for this endpoint, such as a video model on the chat endpoint, whatever models the key is limited to. This is checked before the model runs and covers every endpoint, including embedding and image models sent to a chat endpoint. A wrong-type model listed in `models` is the same error with `param: models`. | No | Use the endpoint for that kind of model ([Chat](https://ewest.ai/docs/chat), [Images](https://ewest.ai/docs/images), and so on). | | `400` | `content_policy` | The prompt or input was rejected by the model's safety filters (image and audio endpoints; a job reports it as a failed job, below). | No | Change the prompt or input. | | `404` | `model_not_found` | No model has that ID. | No | Copy the ID from the [Models](https://ewest.ai/docs/models) page. It starts with `ewest/`. | | `404` | `not_found_error` | Unknown job ID, or a job that belongs to another key. | No | Check the job ID, and use the key that created the job. | | `413` | `invalid_request_error` | The request body or an uploaded file is too large. | No | Send a smaller body or file. Uploaded images can be up to 20 MB each and audio files up to 25 MB. [Files](https://ewest.ai/docs/files#limits) lists all the limits. | | `415` | `invalid_request_error` | The body is not JSON. | No | Send `Content-Type: application/json` with a JSON body. | ## Failed jobs A video or music job that cannot finish is not an HTTP error. The job ends with `status: "failed"` and an `error` object holding a `code` (`generation_failed` when the model failed to generate, or for example `content_policy` or `timeout`) and a fixed message. A failed job is not charged. To try again, submit a new job; see [Rate limits and retries](https://ewest.ai/docs/rate-limits#async-jobs) for how to avoid double submits. A job you stop with `POST /v1/jobs/{id}/cancel` before it starts ends the same way, with code `cancelled`; once a job has started it can no longer be cancelled (409 `job_running`) and finishes as usual. ## Errors inside a stream Problems found before the answer starts come back as a normal HTTP error. Once a streamed answer has begun the status is already `200`, so a later failure arrives as an event in the stream, and then the stream ends. Check every event for an error instead of relying on the status. [Streaming](https://ewest.ai/docs/streaming) shows how to read a stream. - **Chat completions:** a final chunk has `finish_reason: "error"` and an `error` object with `message`, `type` (`model_error`) and `code`. - **Anthropic Messages:** an `event: error` whose data is `{"type": "error", "error": {"type": "api_error", "message": ...}}`. - **Responses:** an `event: error` with `code: "model_error"` and a `message`. - Text you already received stays valid. To try again, send the whole request again; the model does not pick up where it stopped. - Chat responses have to start within about 90 seconds, which is another reason to stream long answers. Image and audio models have their own time limits, and no response can take longer than 100 seconds to start. ## Trace IDs Every response, errors included, has an `x-request-id` header. Keep it when you log a failure: you can find the request in **Console → Requests**, and support can use it too. See [Trace IDs](https://ewest.ai/docs/traces). Source: https://ewest.ai/docs/errors --- # Troubleshoot a request A short checklist for when a request fails: what to check first, and what to send support. Work down this list in order. Most failures are one of the first four. [Errors](https://ewest.ai/docs/errors) has every status and code in detail. ## 1. Read the status and code Look at the HTTP status and the `code` or `type` in the body, not the message wording. `4xx` (except `429`) means something about the request, key or account needs to change; `5xx` and `429` can succeed on a retry. Check every event of a stream too: a failure after the answer starts arrives as an event, not a status ([errors inside a stream](https://ewest.ai/docs/errors#streams)). ## 2. Check the key and the base URL - `401`: the key is missing, mistyped, expired or blocked. Send it as `Authorization: Bearer sk-…` (or `x-api-key` for Anthropic clients) and copy it again from [API keys](https://ewest.ai/keys). - OpenAI libraries and tools use the base URL `https://api.ewest.ai/v1`. The Anthropic libraries and Claude Code use `https://api.ewest.ai` **without** `/v1`, because they add `/v1/messages` themselves. - Set only one key variable in a tool. If a tool still fails, send the same request with cURL: it uses the same key and model without the tool. ## 3. Check the model - `404 model_not_found`: the ID must start with `ewest/` and be listed under [Models](https://ewest.ai/docs/models). - `400 model_not_supported`: the model is the wrong type for the endpoint, for example a video model sent to chat. - `403 permission_error`: your key is limited to a list of models that does not include this one. Change the list in the console. - `400 unsupported_parameter` or `unsupported_value`: this model does not take that parameter or value. `param` names it. ## 4. Check the budget and balance `402 insufficient_budget` means the key's own budget is used up: raise it or use another key. `402 insufficient_balance` means the organisation's prepaid balance is too low: add funds under Billing. See [budget or rate](https://ewest.ai/docs/rate-limits#budget-vs-rate). ## 5. Rate limits and busy models On `429`, wait the seconds in the `retry-after` header and retry with growing, randomised delays. A `429` with code `model_busy` is not your rate limit: that model is busy right now, so the same wait-and-retry applies. On `502`, `503` and `504` the model or the service was briefly unavailable: retry with backoff. If it keeps failing, check [status.ewest.ai](https://status.ewest.ai). See [Rate limits and retries](https://ewest.ai/docs/rate-limits). ## 6. Video and music jobs A job that cannot finish ends with `status: "failed"` and an `error.code`; it is not an HTTP error and is not charged. Read the code under [Failed jobs](https://ewest.ai/docs/errors#jobs), change the input if it says so, and submit a new job. ## 7. Still stuck? Send support the trace ID Every response, errors included, has an `x-request-id` header. Keep it when you log a failure. You can find the request in **Console → Requests**, and support can use the same ID. Send it with the endpoint, the model and the time. Never send your API key. See [Trace IDs](https://ewest.ai/docs/traces). Source: https://ewest.ai/docs/troubleshooting --- # Rate limits and retries How 429 and 5xx errors work, and how to retry without making things worse. Two different things can stop a request: a **rate** problem (too many requests too fast, or no spare capacity on a model right now) and a **budget** problem (the key or the account has no money left). Rate problems pass if you wait. Budget problems do not. ## Limits - **Per key:** every API key has its own limits per minute, listed in [Limits per key](#key-limits). A rate limit is not something you set in the console today. Write clients that cope with a `429` at any time. - **Per model:** a model that is short of capacity does not show up as a `429`. You get a `502` (`model_unavailable`), which is also worth retrying. A `429` always comes from your own key: its request or token limit. It is the same for every model, so a `models` list is not tried further. - **Size:** uploaded images can be up to 20 MB each and audio files up to 25 MB (see [Errors](https://ewest.ai/docs/errors#model-errors)). - **Time:** a chat response has to start within about 90 seconds; image and audio models have their own limits, and the edge ends any response that has not started after 100 seconds. Use streaming for long chat answers and [jobs](https://ewest.ai/docs/video) for video and music. ## Limits per key Limits apply to each API key separately, not to your IP address or your whole account. Counts reset every minute. A short burst at the peak can occasionally get through slightly above the stated number, so treat the numbers as a guide for sizing your client, not as an exact meter. Chat, responses, messages and embeddings calls count against the first table: | Per API key | Limit per minute | | --- | --- | | Requests | 600 | | Tokens | 2,000,000 | Image, image edit, speech and transcription requests, job creation and job reads have their own per-key limits: | Per API key | Limit per minute | | --- | --- | | Images, image edits, speech and transcription (requests) | 60 | | Creating video, audio and 3D jobs, counted together (new jobs) | 10 | | Reading jobs, `GET /v1/jobs` and `GET /v1/jobs/{id}` (job reads) | 600 | Keys used in the console playground have lower limits than API keys. If you need higher limits for an API key, contact support at [support@ewest.ai](mailto:support@ewest.ai) with your use case and the expected request rate. ## What a limit response looks like Going over a limit returns HTTP `429` with type `rate_limit_error`, code `rate_limit_exceeded` and a `retry-after` header: the number of seconds to wait. The body uses the usual [error shape](https://ewest.ai/docs/errors). On chat endpoints it is `{"error": {"message": "Rate limit reached for this API key. Retry after the time in the retry-after header.", "type": "rate_limit_error", "param": null, "code": "rate_limit_exceeded"}}`. On image, audio, video and 3D job requests the message also names the limit, for example `Rate limit reached for this API key: 10 new jobs per minute. Try again in 23 s.` Branch on the status and the code, never on the message. Back off for the `retry-after` seconds, and poll jobs no faster than you need: a slower poll interval, or the job's event stream, keeps you well under the read limit. ## Response headers When a key has a request or token limit, responses on the chat endpoints can carry OpenAI's header names: `x-ratelimit-limit-requests`, `x-ratelimit-remaining-requests` and the matching `-tokens` headers. Read them if they are there, but do not require them: they can be missing, for example on streamed answers. A `429` for the key's limit carries `retry-after`, in seconds; the example below honours it. ## Budget or rate? 402 versus 429 | You see | It means | Retry? | | --- | --- | --- | | `402 insufficient_budget` | This key's budget is used up. | No. Raise the budget or use another key. | | `402 insufficient_balance` | The organisation's prepaid balance is too low. Only returned once prepaid billing is enforced for your account. | No. Add funds in the console. | | `429 rate_limit_error` | The key's own request or token limit. | Yes, after the `retry-after` seconds. | A `402` is final: retrying a budget error never succeeds. A `429` is a rate problem and passes if you wait. To check before a large request, `GET /v1/key` returns what the calling key may still spend: its budget, spend, remaining amount and limits, and the organisation's prepaid balance. It is free and sees only the key that calls it. ## Retrying with backoff - Retry only `429` (rate), `500`, `502`, `503`, `504` and network errors such as a dropped connection or a timeout. Never retry `400`, `401`, `402`, `403` or `404`. - Wait longer after each failure: for example 1 s, 2 s, 4 s, 8 s, up to a ceiling of 30 s. - Add jitter, a random part of each wait, so clients that failed together do not all come back together. - If a `retry-after` header is present, wait at least that long. - Stop after a few attempts (five is plenty) and report the error together with its `x-request-id`. - Set a client timeout of about 100 seconds, and stream long answers instead of waiting on one big response. cURL: ```bash # curl retries 429 and 5xx on its own: it waits 1 s, 2 s, 4 s, ... and honours a retry-after # header. It never retries a 402 (out of budget). The Python and JavaScript tabs add jitter and a time limit. curl --retry 5 --retry-max-time 60 https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "Content-Type: application/json" \ -d '{"model": "ewest/gemini-flash", "messages": [{"role": "user", "content": "Hello!"}]}' ``` Python: ```python import os, random, time, requests from datetime import datetime, timezone from email.utils import parsedate_to_datetime RETRY_STATUS = {429, 500, 502, 503, 504} def retry_after_seconds(value): # a number of seconds, or an HTTP date try: return max(0.0, float(value)) except (TypeError, ValueError): try: return max(0.0, (parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds()) except (TypeError, ValueError): return 0.0 def pause(attempt, retry_after=0.0): cap = min(30, 2 ** attempt) # 1 s, 2 s, 4 s, ... at most 30 s time.sleep(max(retry_after, random.uniform(cap / 2, cap))) def chat(payload, max_attempts=5): for attempt in range(max_attempts): last = attempt == max_attempts - 1 try: res = requests.post( "https://api.ewest.ai/v1/chat/completions", headers={"Authorization": f"Bearer {os.environ['EWEST_KEY']}"}, json=payload, timeout=100, ) except (requests.ConnectionError, requests.Timeout): if last: raise pause(attempt) continue if res.ok: return res.json() try: error = res.json().get("error") except (ValueError, AttributeError): error = None if not isinstance(error, dict): error = {} retryable = res.status_code in RETRY_STATUS if not retryable or last: raise RuntimeError(f"{res.status_code} {error.get('type')}: {error.get('message')}") pause(attempt, retry_after_seconds(res.headers.get("retry-after"))) answer = chat(dict( model="ewest/gemini-flash", messages=[{"role": "user", "content": "Hello!"}], )) print(answer["choices"][0]["message"]["content"]) ``` JavaScript: ```javascript const RETRY_STATUS = new Set([429, 500, 502, 503, 504]); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // Wait 1 s, 2 s, 4 s, ... (at most 30 s) with jitter, and at least as long as retry-after says. const pause = (attempt, retryAfter = 0) => { const cap = Math.min(30, 2 ** attempt); return sleep(Math.max(retryAfter, cap / 2 + Math.random() * (cap / 2)) * 1000); }; async function chat(payload, maxAttempts = 5) { for (let attempt = 0; ; attempt++) { const last = attempt + 1 >= maxAttempts; let res; try { res = await fetch("https://api.ewest.ai/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.EWEST_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify(payload), signal: AbortSignal.timeout(100_000), }); } catch (err) { // A dropped connection (TypeError) or the 100 s client timeout: worth another try. if (last || !(err instanceof TypeError || err?.name === "TimeoutError")) throw err; await pause(attempt); continue; } if (res.ok) return res.json(); const body = await res.json().catch(() => null); const error = body?.error; const retryable = RETRY_STATUS.has(res.status); if (!retryable || last) throw new Error(`${res.status} ${error?.type}: ${error?.message}`); await pause(attempt, Number(res.headers.get("retry-after")) || 0); } } const answer = await chat({ model: "ewest/gemini-flash", messages: [{ role: "user", content: "Hello!" }], }); console.log(answer.choices[0].message.content); ``` The OpenAI and Anthropic client libraries already retry some errors with backoff, and they retry every `429`, but never a `402`. Check their retry setting before you add a second layer on top. ## Async jobs: do not submit twice Video and music requests create a job and answer `202`. There is no idempotency key, so every accepted submit creates a new job, and a job that succeeds is billed. After an error response no billable job was started, so retrying that submit is safe (a failed, uncharged record may appear in `GET /v1/jobs`). The risky case is a lost connection or timeout after you sent the request, because you cannot tell whether it was accepted. - Before you resubmit after a lost response, call `GET /v1/jobs` and look for a recent job with the same model and prompt. - Keep the job `id` from the `202` response and poll or stream that job. Do not submit again just because a job is slow. - A job that ends as `failed` is not charged, so submitting a replacement is safe. - Retry the status call (`GET /v1/jobs/{id}`) freely, with the same backoff. Responses: continuing a response that wasn't stored (`store: false`, or an id issued before eWest kept conversations) is a 400 with code `previous_response_not_stored`; send the full conversation in `input`. An unknown or deleted response id is a 404 with code `not_found`. Source: https://ewest.ai/docs/rate-limits --- # Developer tools Use eWest from coding agents, editors and SDKs. eWest speaks the OpenAI and Anthropic API formats, so tools that let you set a base URL and a key can use `ewest/*` models. Each guide covers setup, choosing a model, a first request, streaming and tools, and troubleshooting. - [Claude Code](https://ewest.ai/docs/guides/claude-code): Use eWest models in the Claude Code terminal agent. - [Cursor](https://ewest.ai/docs/guides/cursor): Add eWest as a model provider in the Cursor editor. - [Cline](https://ewest.ai/docs/guides/cline): Point the Cline coding agent at eWest. - [Codex CLI](https://ewest.ai/docs/guides/codex): Run the Codex command-line agent on eWest models. - [OpenClaw](https://ewest.ai/docs/guides/openclaw): Connect the OpenClaw agent to eWest. - [OpenAI SDK (Python, JS)](https://ewest.ai/docs/guides/openai-sdk): Call eWest with the official OpenAI libraries. - [Anthropic SDK (Python, TS)](https://ewest.ai/docs/guides/anthropic-sdk): Call eWest with the official Anthropic libraries. - [Vercel AI SDK](https://ewest.ai/docs/guides/vercel-ai-sdk): Use eWest models with generateText, streamText, tools and embed. - [LangChain (Python, JS)](https://ewest.ai/docs/guides/langchain): Point LangChain's chat and embedding models at eWest. - [LlamaIndex (Python)](https://ewest.ai/docs/guides/llamaindex): Use eWest as the LLM and embedding model in LlamaIndex. - [GitHub Copilot (VS Code)](https://ewest.ai/docs/guides/github-copilot): Add eWest models to Copilot Chat in VS Code with a custom endpoint. - [Zed](https://ewest.ai/docs/guides/zed): Use eWest models in Zed's agent panel as an OpenAI- or Anthropic-compatible provider. - [Continue](https://ewest.ai/docs/guides/continue): Use eWest models for chat, edit, apply and embeddings in Continue. Source: https://ewest.ai/docs/guides --- # Claude Code Use eWest models in the Claude Code terminal agent. Claude Code talks to eWest over the Anthropic Messages API (`/v1/messages`). Point it at `https://api.ewest.ai`, give it your eWest key, and pick `ewest/claude-*` models. ## Setup Set `ANTHROPIC_BASE_URL` to `https://api.ewest.ai`, **without** `/v1`, and your key in `ANTHROPIC_AUTH_TOKEN`, which Claude Code sends as `Authorization: Bearer`. `ANTHROPIC_API_KEY` works too (sent as `x-api-key`); in an interactive session Claude Code asks once before using it. Set one of the two, not both. Shell exports last for one terminal. To keep the settings, put them in the `env` block of `~/.claude/settings.json`. Never put your key in a project's `.claude/settings.json`: that file is committed. Shell: ```bash # ANTHROPIC_AUTH_TOKEN is sent as "Authorization: Bearer". No /v1 on the base URL. export ANTHROPIC_BASE_URL=https://api.ewest.ai export ANTHROPIC_AUTH_TOKEN="$EWEST_KEY" export ANTHROPIC_MODEL=ewest/claude-sonnet claude ``` ~/.claude/settings.json: ```json { "env": { "ANTHROPIC_BASE_URL": "https://api.ewest.ai", "ANTHROPIC_AUTH_TOKEN": "YOUR_EWEST_KEY", "ANTHROPIC_MODEL": "ewest/claude-sonnet", "ANTHROPIC_DEFAULT_OPUS_MODEL": "ewest/claude-opus", "ANTHROPIC_DEFAULT_SONNET_MODEL": "ewest/claude-sonnet", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "ewest/claude-haiku" } } ``` ## Choose a model `ANTHROPIC_MODEL` is the main model. The `ANTHROPIC_DEFAULT_OPUS_MODEL`, `_SONNET_` and `_HAIKU_` variables decide what the opus, sonnet and haiku aliases mean; the haiku one also runs background tasks such as session titles, so a cheap model there saves money. - Every name needs the `ewest/` prefix: `ewest/claude-sonnet` works, `claude-sonnet` returns `404`. - `ewest/claude-opus` for the hardest tasks, `ewest/claude-sonnet` for everyday coding, `ewest/claude-haiku` for fast, cheap work. The full list is in [Models](https://ewest.ai/docs/models). - With `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1`, the `/model` picker also lists the `ewest/claude-*` models your key may use (Claude Code reads them from `GET /v1/models`). Shell: ```bash # The main model, and what the opus / sonnet / haiku aliases and background tasks use. export ANTHROPIC_MODEL=ewest/claude-sonnet export ANTHROPIC_DEFAULT_OPUS_MODEL=ewest/claude-opus export ANTHROPIC_DEFAULT_SONNET_MODEL=ewest/claude-sonnet export ANTHROPIC_DEFAULT_HAIKU_MODEL=ewest/claude-haiku # One session on another model: claude --model ewest/claude-opus ``` ## Verify it works `claude -p` sends one prompt and prints the answer. In an interactive session, `/status` shows the `Anthropic base URL` and which key variable is active. If Claude Code fails, try the cURL request: it uses the same key and model without Claude Code. 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)). Claude Code: ```bash export ANTHROPIC_BASE_URL=https://api.ewest.ai export ANTHROPIC_AUTH_TOKEN="$EWEST_KEY" claude -p "Reply with the single word OK" --model ewest/claude-sonnet ``` cURL: ```bash # The same request without Claude Code: if this fails, the key or model is the problem. curl https://api.ewest.ai/v1/messages \ -H "x-api-key: $EWEST_KEY" \ -H "anthropic-version: 2023-06-01" \ -H "content-type: application/json" \ -d '{"model": "ewest/claude-haiku", "max_tokens": 32, "messages": [{"role": "user", "content": "Reply with the single word OK"}]}' ``` ## Streaming and tools Nothing to set up: Claude Code always streams, and runs its tools (reading and editing files, shell commands) through tool calling on `/v1/messages`. In scripts, `--output-format stream-json --verbose` prints every event, including tool calls, as a JSON line. Claude Code: ```bash export ANTHROPIC_BASE_URL=https://api.ewest.ai export ANTHROPIC_AUTH_TOKEN="$EWEST_KEY" # Streams every event (text, tool calls, tool results) as JSON lines. claude -p "How many files are in this folder? Use ls." \ --model ewest/claude-sonnet \ --allowedTools "Bash(ls:*)" \ --output-format stream-json --verbose ``` ## Troubleshooting - `401`: the key is missing, mistyped or revoked. Copy it again from [API keys](https://ewest.ai/keys). Run `/status` to see which variable Claude Code uses, and set only one of `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY`. - `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). - `400` naming `context_management`, `output_config` or `Extra inputs are not permitted`: set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`. - `400` with `output_config.effort is not supported by this model`: Claude Code sends an effort setting that `ewest/claude-haiku` does not take on `/v1/messages`. Use `ewest/claude-sonnet` or `ewest/claude-opus` as the main model. `ewest/claude-haiku` is the exception on `/v1/messages`, even though its `reasoning_efforts` list effort values for other endpoints. - Claude Code asks you to log in although the key is set: put `ANTHROPIC_AUTH_TOKEN` in your shell or in `~/.claude/settings.json`, not only in a project settings file. - Harmless, nothing to fix: the first request of a session can get a `400` saying role `system` is not supported, which Claude Code retries by itself; a warning that the model is not recognized; and a cost estimate inside Claude Code that differs from your eWest usage. Your real cost is in the console under Usage. Shell: ```bash # 400 errors naming context_management, output_config or "Extra inputs are not permitted": export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 # 401 errors: your key is in a header eWest does not read. Use one of these, not both: export ANTHROPIC_AUTH_TOKEN="$EWEST_KEY" # sent in the Authorization header # export ANTHROPIC_API_KEY="$EWEST_KEY" # sent as x-api-key (approve it once in /config) # See what Claude Code uses: run /status inside Claude Code, or list the models your key may call: curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/claude-code --- # Cursor Add eWest as a model provider in the Cursor editor. Cursor can send chat requests to eWest through its OpenAI key setting (`/v1/chat/completions`). > We haven't tested this setup ourselves; it follows the tool's own documentation. If something doesn't work, contact support. > Cursor sends these requests from its own servers, your key works for chat only (Tab completion always uses Cursor's models), and some Cursor features ignore the custom base URL (see Streaming and tools). Using your own key needs a Cursor plan that includes it. ## Setup 1. Open **Cursor Settings → Models**. 2. Paste your eWest key into **OpenAI API Key**, turn on **Override OpenAI Base URL** and enter `https://api.ewest.ai/v1`. 3. Turn off the built-in models, then add the `ewest/*` models you want (for example `ewest/claude-sonnet`) by name. 4. Click **Verify**. ## Choose a model Cursor doesn't read eWest's model list, so add each id by hand, exactly as in [Models](https://ewest.ai/docs/models) and with the `ewest/` prefix. For coding, use a model that supports tools: `ewest/claude-sonnet`, `ewest/claude-opus`, `ewest/claude-haiku` or `ewest/gemini-flash`. ## Verify it works Pick an `ewest/*` model in the chat and send a message. The cURL request below is what Cursor sends, without Cursor: if it works and Cursor doesn't, the problem is in Cursor's settings. 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)). cURL: ```bash # The request Cursor sends for a chat message, without Cursor: curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "content-type: application/json" \ -d '{"model": "ewest/claude-haiku", "stream": true, "messages": [{"role": "user", "content": "Reply with the single word OK"}]}' ``` ## Streaming and tools Cursor streams answers and sends its tools over `/v1/chat/completions`; there is nothing to set. Known Cursor limits with your own key: Agent mode can switch back to a built-in model, and subagents can ignore the base URL override. For agent work, [Claude Code](https://ewest.ai/docs/guides/claude-code) or [Cline](https://ewest.ai/docs/guides/cline) are more reliable. ## Troubleshooting - **Verify** fails with `404`: Cursor checks the key with one of its built-in model names, which eWest doesn't serve. Turn off the built-in models, add an `ewest/*` model, then verify again. - `401`: the key is missing, mistyped or revoked. Copy it again from [API keys](https://ewest.ai/keys). Also check that **Override OpenAI Base URL** is on. - `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). cURL: ```bash # The models your key may call (use these ids exactly, with the ewest/ prefix): curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models # One model, with its context window and whether it supports tools and images: curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models/ewest/claude-haiku ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/cursor --- # Cline Point the Cline coding agent at eWest. Cline uses eWest through its **OpenAI Compatible** provider (`/v1/chat/completions`). > We haven't tested this setup ourselves; it follows the tool's own documentation. If something doesn't work, contact support. ## Setup 1. Open Cline's settings (the gear icon) and choose **OpenAI Compatible** as the API Provider. 2. **Base URL**: `https://api.ewest.ai/v1`. **API Key**: your eWest key. **Model ID**: an `ewest/*` id such as `ewest/claude-sonnet`. 3. Under **Model Configuration**, set **Context Window Size** to the model's context window from [Models](https://ewest.ai/docs/models) (200000 for `ewest/claude-haiku`, 1000000 for `ewest/claude-sonnet`), **Max Output Tokens** to what you need (8192 is a good start), and turn on image support for models that take images. Cline's **Anthropic** provider also has **Use custom base URL** (`https://api.ewest.ai`, no `/v1`), but its model list only offers Anthropic's own model names, which eWest answers with `404`. Use OpenAI Compatible. ## Choose a model Enter the id with its prefix: `ewest/claude-sonnet`, not `claude-sonnet`. Cline relies on tool calling, so use a model that supports tools: any `ewest/claude-*` model or `ewest/gemini-flash`. Change the context window when you change the model. ## Verify it works Click **Verify**, or give Cline a short task. The cURL request below is the one Cline sends, including `stream_options.include_usage`, so the last event carries the token counts Cline shows. 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)). cURL: ```bash # The request Cline sends, without Cline. The last event carries the token usage. curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "content-type: application/json" \ -d '{"model": "ewest/claude-haiku", "stream": true, "stream_options": {"include_usage": true}, "messages": [{"role": "user", "content": "Reply with the single word OK"}]}' ``` ## Streaming and tools Cline always streams and uses tool calling over `/v1/chat/completions`; there is nothing to set. ## Troubleshooting - `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). - Cline trims the conversation early, or the model says the prompt is too long: check **Context Window Size** against the model's limit in [Models](https://ewest.ai/docs/models). cURL: ```bash # The models your key may call (use these ids exactly, with the ewest/ prefix): curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models # One model, with its context window and whether it supports tools and images: curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models/ewest/claude-haiku ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/cline --- # Codex CLI Run the Codex command-line agent on eWest models. Codex CLI talks to eWest over the Responses API (`/v1/responses`), set up as a custom model provider. ## Setup Add an `ewest` provider to `~/.codex/config.toml` and make it the default with `model_provider`. Keep `wire_api = "responses"`. Don't call the provider `openai`, `ollama` or `lmstudio`: Codex reserves those ids. Codex reads the key from the environment variable named in `env_key`, so export `EWEST_KEY` in the shell where you run Codex. ~/.codex/config.toml: ```toml # Codex reads the key from the environment variable named in env_key. model = "ewest/claude-sonnet" model_provider = "ewest" # eWest doesn't offer web search yet; without this line Codex's requests are refused. web_search = "disabled" [model_providers.ewest] name = "eWest" base_url = "https://api.ewest.ai/v1" env_key = "EWEST_KEY" wire_api = "responses" ``` Shell: ```bash # Put this in ~/.zshrc or ~/.bashrc so every terminal has it. export EWEST_KEY="YOUR_EWEST_KEY" codex ``` ## Choose a model Set `model` in config.toml, or pass `--model` for one run, always with the `ewest/` prefix. `ewest/claude-sonnet` is a good default for coding; `ewest/claude-haiku` and `ewest/gemini-flash` are faster and cheaper. Shell: ```bash # For one session (or change model in ~/.codex/config.toml): codex --model ewest/claude-opus codex exec --model ewest/gemini-flash "Summarize README.md" ``` ## Verify it works `codex exec` runs one task without the interactive UI; `--skip-git-repo-check` lets it run outside a Git repository. A warning that model metadata for the `ewest/*` id was not found is harmless. 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)). Shell: ```bash # Needs EWEST_KEY in the environment and the config.toml above. codex exec --skip-git-repo-check --model ewest/claude-haiku "Reply with the single word OK" ``` ## Streaming and tools Codex streams over `/v1/responses` and calls its own tools (shell commands, file edits) with function calling; nothing to set. Codex sends the whole conversation in `input` every turn, which works with any setting; eWest also keeps Responses conversations by default, so `previous_response_id` and fetching a stored response by id work too (see [Responses](https://ewest.ai/docs/responses)). Shell: ```bash # Codex streams over /v1/responses and runs its shell tool; --json prints every event. codex exec --skip-git-repo-check --json --model ewest/claude-haiku \ "How many files are in this folder? Use ls." ``` ## Troubleshooting - Codex says the key or `EWEST_KEY` is missing: export it in the same shell, or add it to `~/.zshrc` / `~/.bashrc`. - `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). - To rule Codex out, send the request below: it is a `/v1/responses` call with the same key and model. cURL: ```bash # The request Codex makes, without Codex: if this fails, the key or model is the problem. curl https://api.ewest.ai/v1/responses \ -H "Authorization: Bearer $EWEST_KEY" \ -H "content-type: application/json" \ -d '{"model": "ewest/claude-haiku", "input": "Reply with the single word OK"}' ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/codex --- # OpenClaw Connect the OpenClaw agent to eWest. OpenClaw connects to eWest as a custom OpenAI-compatible provider (`/v1/chat/completions`). > We haven't tested this setup ourselves; it follows the tool's own documentation. If something doesn't work, contact support. ## Setup Add an `ewest` provider under `models.providers` in `~/.openclaw/openclaw.json` with `api: "openai-completions"` and base URL `https://api.ewest.ai/v1`. `"${EWEST_KEY}"` reads the key from your environment. List each model you want in `models`, with its context window from [Models](https://ewest.ai/docs/models). ~/.openclaw/openclaw.json: ```json { "models": { "mode": "merge", "providers": { "ewest": { "baseUrl": "https://api.ewest.ai/v1", "apiKey": "${EWEST_KEY}", "api": "openai-completions", "models": [ { "id": "ewest/claude-sonnet", "name": "Claude Sonnet (eWest)", "contextWindow": 1000000 }, { "id": "ewest/claude-haiku", "name": "Claude Haiku (eWest)", "contextWindow": 200000 }, { "id": "ewest/gemini-flash", "name": "Gemini Flash (eWest)", "contextWindow": 1048576 } ] } } }, "agents": { "defaults": { "model": { "primary": "ewest/ewest/claude-sonnet" } } } } ``` ## Choose a model OpenClaw names models `/`. With the provider called `ewest`, that is the provider name followed by the full eWest id: `ewest/ewest/claude-haiku`. Set the default in `agents.defaults.model.primary`, or with `openclaw models set`. Shell: ```bash # Refs are /, so eWest models get a double prefix. openclaw models list openclaw models set ewest/ewest/claude-haiku ``` ## Verify it works `openclaw models list` should show the eWest models. Send a message, then find it in the console under Requests. The cURL request below is what OpenClaw sends, without OpenClaw. 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)). cURL: ```bash # The request OpenClaw sends, without OpenClaw: curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "content-type: application/json" \ -d '{"model": "ewest/claude-haiku", "stream": true, "messages": [{"role": "user", "content": "Reply with the single word OK"}]}' ``` ## Streaming and tools OpenClaw streams and calls tools over `/v1/chat/completions`; there is nothing to set. Use models that support tools: any `ewest/claude-*` model or `ewest/gemini-flash`. ## Troubleshooting - Unknown model: the ref needs both parts, `ewest/` (the provider) and the full id (`ewest/claude-haiku`), and the id must be listed under the provider's `models`. - `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). cURL: ```bash # The models your key may call (use these ids exactly, with the ewest/ prefix): curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models # One model, with its context window and whether it supports tools and images: curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models/ewest/claude-haiku ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/openclaw --- # 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 --- # Anthropic SDK (Python, TS) Call eWest with the official Anthropic libraries. The official Anthropic libraries work with eWest's Messages API: `/v1/messages`, `/v1/messages/count_tokens` and `/v1/models`. Install with `pip install anthropic` or `npm install @anthropic-ai/sdk`. ## Setup Set the base URL to `https://api.ewest.ai`, **without** `/v1`: the SDK adds `/v1/messages` itself. Pass your eWest key as the API key; eWest accepts it as `x-api-key` or `Authorization: Bearer`. Or set `ANTHROPIC_BASE_URL` and `ANTHROPIC_API_KEY` and create the client without arguments. `client.models.retrieve("ewest/claude-haiku")` is a free first check that the key and base URL work. Python: ```python import os import anthropic # No /v1 on the base URL: the SDK adds /v1/messages itself. client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"]) # Looking up a model is free, and proves the key and base URL work. print(client.models.retrieve("ewest/claude-haiku").id) ``` TypeScript: ```javascript import Anthropic from "@anthropic-ai/sdk"; // No /v1 on the base URL: the SDK adds /v1/messages itself. const client = new Anthropic({ baseURL: "https://api.ewest.ai", apiKey: process.env.EWEST_KEY }); // Looking up a model is free, and proves the key and base URL work. console.log((await client.models.retrieve("ewest/claude-haiku")).id); ``` Shell: ```bash # Or leave base_url / api_key out of the code: the SDKs read these. export ANTHROPIC_BASE_URL=https://api.ewest.ai export ANTHROPIC_API_KEY="$EWEST_KEY" ``` ## Choose a model `client.models.list()` returns the models your key may use. Claude models are `ewest/claude-opus`, `ewest/claude-sonnet` and `ewest/claude-haiku`, always with the `ewest/` prefix. `max_tokens` is required on every message, as in Anthropic's API. Python: ```python import os import anthropic # No /v1 on the base URL: the SDK adds /v1/messages itself. client = anthropic.Anthropic(base_url="https://api.ewest.ai", 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) ``` TypeScript: ```javascript import Anthropic from "@anthropic-ai/sdk"; // No /v1 on the base URL: the SDK adds /v1/messages itself. const client = new Anthropic({ baseURL: "https://api.ewest.ai", 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 message. 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 import anthropic # No /v1 on the base URL: the SDK adds /v1/messages itself. client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"]) message = client.messages.create( model="ewest/claude-haiku", max_tokens=512, messages=[{"role": "user", "content": "Say hello in five words."}], ) print(message.content[0].text) ``` TypeScript: ```javascript import Anthropic from "@anthropic-ai/sdk"; // No /v1 on the base URL: the SDK adds /v1/messages itself. const client = new Anthropic({ baseURL: "https://api.ewest.ai", apiKey: process.env.EWEST_KEY }); const message = await client.messages.create({ model: "ewest/claude-haiku", max_tokens: 512, messages: [{ role: "user", content: "Say hello in five words." }], }); for (const block of message.content) if (block.type === "text") console.log(block.text); ``` ## Streaming and tools `messages.stream()` yields the text as it arrives. Tools use Anthropic's format (`input_schema`); the answer contains `tool_use` blocks, and you send each result back as a `tool_result` block in the next user message. Python: ```python import os import anthropic # No /v1 on the base URL: the SDK adds /v1/messages itself. client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"]) # Streaming: print the answer as it arrives. with client.messages.stream( model="ewest/claude-haiku", max_tokens=512, messages=[{"role": "user", "content": "Write one sentence about the sea."}], ) as stream: for text in stream.text_stream: print(text, end="", flush=True) print() # Tool calling: the model asks for get_weather, your code runs it. message = client.messages.create( model="ewest/claude-haiku", max_tokens=512, tools=[{ "name": "get_weather", "description": "Current weather for a city", "input_schema": { "type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"], }, }], messages=[{"role": "user", "content": "What is the weather in Paris?"}], ) for block in message.content: if block.type == "tool_use": print("tool call:", block.name, block.input) ``` TypeScript: ```javascript import Anthropic from "@anthropic-ai/sdk"; // No /v1 on the base URL: the SDK adds /v1/messages itself. const client = new Anthropic({ baseURL: "https://api.ewest.ai", apiKey: process.env.EWEST_KEY }); // Streaming: print the answer as it arrives. const stream = client.messages.stream({ model: "ewest/claude-haiku", max_tokens: 512, messages: [{ role: "user", content: "Write one sentence about the sea." }], }); stream.on("text", (text) => process.stdout.write(text)); await stream.finalMessage(); console.log(); // Tool calling: the model asks for get_weather, your code runs it. const message = await client.messages.create({ model: "ewest/claude-haiku", max_tokens: 512, tools: [ { name: "get_weather", description: "Current weather for a city", input_schema: { type: "object", properties: { city: { type: "string" } }, required: ["city"] }, }, ], messages: [{ role: "user", content: "What is the weather in Paris?" }], }); for (const block of message.content) { if (block.type === "tool_use") console.log("tool call:", block.name, JSON.stringify(block.input)); } ``` ## Troubleshooting API errors raise `APIStatusError` with the status and body, in Anthropic's own error envelope (`{"type": "error", "error": {"type", "message"}}`), so the library's typed errors (`AuthenticationError`, `NotFoundError`, `RateLimitError`, ...) work as with Anthropic. The [Errors](https://ewest.ai/docs/errors#messages-envelope) page maps the types and explains each code. - `404` on every request: the base URL ends in `/v1`. Use `https://api.ewest.ai`. - `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). Python: ```python import os import anthropic # No /v1 on the base URL: the SDK adds /v1/messages itself. client = anthropic.Anthropic(base_url="https://api.ewest.ai", api_key=os.environ["EWEST_KEY"]) try: message = client.messages.create( model="ewest/claude-haiku", max_tokens=512, messages=[{"role": "user", "content": "Say hello in five words."}], ) print(message.content[0].text) except anthropic.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/anthropic-sdk --- # Vercel AI SDK Use eWest models with generateText, streamText, tools and embed. The AI SDK reaches eWest through its OpenAI-compatible provider, so `generateText`, `streamText`, tools, `embed` and the UI hooks work with every `ewest/*` chat and embedding model. Examples are plain JavaScript and need Node 22 or newer (the AI SDK packages require it); they work unchanged in TypeScript and in Next.js route handlers. ## Setup Install the AI SDK, the OpenAI-compatible provider and zod (for tool inputs): npm: ```bash npm install ai @ai-sdk/openai-compatible zod ``` [Create an API key](https://ewest.ai/keys) and put it in the `EWEST_KEY` environment variable (`export EWEST_KEY=sk-…`). The examples read it from there; never put the key in browser code. Create the provider once with the base URL `https://api.ewest.ai/v1` and your key. `includeUsage` asks for token counts on streamed responses as well. JavaScript: ```javascript import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; const ewest = createOpenAICompatible({ name: "ewest", baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY, includeUsage: true, // token usage on streamed responses too }); export default ewest; ``` Already using the OpenAI or Anthropic provider? Both work with eWest too: set `baseURL` to `https://api.ewest.ai/v1` in either. With `@ai-sdk/openai`, `ewest.chat(id)` sends chat completions and `ewest(id)` uses the Responses API. @ai-sdk/openai: ```javascript import { createOpenAI } from "@ai-sdk/openai"; import { generateText } from "ai"; const ewest = createOpenAI({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY }); // ewest.chat() uses /v1/chat/completions; ewest() uses /v1/responses. const { text } = await generateText({ model: ewest.chat("ewest/claude-haiku"), prompt: "Say hello in one short sentence.", maxOutputTokens: 256, }); console.log(text); ``` @ai-sdk/anthropic: ```javascript import { createAnthropic } from "@ai-sdk/anthropic"; import { generateText } from "ai"; // This provider adds /messages to the base URL, so keep /v1 here. const ewest = createAnthropic({ baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY }); const { text } = await generateText({ model: ewest("ewest/claude-haiku"), prompt: "Say hello in one short sentence.", maxOutputTokens: 256, }); console.log(text); ``` ## Choose a model Use the full model ID, including the `ewest/` prefix. The table has good starting points; [Models](https://ewest.ai/docs/models) lists every model with its context window and limits, and `GET /v1/models` returns the models your key may use. Chat models go in `ewest(id)`, embedding models in `ewest.embeddingModel(id)`. | Use | Model ID | | --- | --- | | Fast and cheap chat, tools | `ewest/claude-haiku` | | Stronger reasoning and coding | `ewest/claude-sonnet` | | Long context (1M tokens), images, audio and video input | `ewest/gemini-flash` | | Embeddings for search and RAG | `ewest/gemini-embedding` | ## Verify it works A first request with `generateText`. It prints the answer and the token usage. JavaScript: ```javascript import { generateText } from "ai"; import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; const ewest = createOpenAICompatible({ name: "ewest", baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY, includeUsage: true, // token usage on streamed responses too }); const { text, usage } = await generateText({ model: ewest("ewest/claude-haiku"), prompt: "Say hello in one short sentence.", maxOutputTokens: 256, }); console.log(text); console.log(usage); ``` The request shows up in the console under **Requests** within a few seconds, with its tokens and cost. Every response carries an `x-request-id` header, its [trace ID](https://ewest.ai/docs/traces). ## Streaming and tools `streamText` returns text as it is generated. Read `textStream` in Node, or return `result.toUIMessageStreamResponse()` from a Next.js route for `useChat`. JavaScript: ```javascript import { streamText } from "ai"; import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; const ewest = createOpenAICompatible({ name: "ewest", baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY, includeUsage: true, // token usage on streamed responses too }); const result = streamText({ model: ewest("ewest/claude-haiku"), prompt: "Write a haiku about the sea.", maxOutputTokens: 256, }); for await (const text of result.textStream) process.stdout.write(text); console.log("\n", await result.usage); ``` Tools are defined with a zod schema and an `execute` function. With `stopWhen`, the SDK sends the tool result back to the model so it can answer in the same call. JavaScript: ```javascript import { generateText, stepCountIs, tool } from "ai"; import { z } from "zod"; import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; const ewest = createOpenAICompatible({ name: "ewest", baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY, includeUsage: true, // token usage on streamed responses too }); const { text, steps } = await generateText({ model: ewest("ewest/claude-haiku"), tools: { getWeather: tool({ description: "Get the current weather for a city", inputSchema: z.object({ city: z.string() }), execute: async ({ city }) => ({ city, temperatureC: 18, sky: "cloudy" }), }), }, stopWhen: stepCountIs(3), // call the tool, then answer with its result prompt: "What is the weather in Yerevan?", maxOutputTokens: 256, }); console.log(steps.flatMap((s) => s.toolCalls.map((c) => c.toolName))); console.log(text); ``` Embeddings use `embed` (one value) or `embedMany` (a list) with an embedding model: JavaScript: ```javascript import { embed } from "ai"; import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; const ewest = createOpenAICompatible({ name: "ewest", baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY, includeUsage: true, // token usage on streamed responses too }); const { embedding } = await embed({ model: ewest.embeddingModel("ewest/gemini-embedding"), value: "How do I reset my password?", }); console.log(embedding.length); ``` ## Troubleshooting - **404 `model_not_found`:** the model name needs the `ewest/` prefix (`ewest/claude-haiku`, not `claude-haiku`). Check the spelling against [Models](https://ewest.ai/docs/models). - **Empty answer from `ewest/gemini-flash`:** `ewest/gemini-flash` does not think unless reasoning is on (low, medium or high); then thinking uses output tokens and a small output limit can be used up. Allow at least 256 output tokens, or turn reasoning off (below). This is a known limitation. - **Follow-up turns forget the conversation:** on the Responses API, pass the earlier response's `id` as `previous_response_id` (conversations are stored by default), or send the full message history with every request; chat completions and Messages are always stateless. See [Responses](https://ewest.ai/docs/responses). - **401, 402 or 403:** the key is missing or wrong, out of budget, or not allowed to use this model. [Errors](https://ewest.ai/docs/errors) explains each code; a [trace ID](https://ewest.ai/docs/traces) finds the request in the console. - **No usage on streamed responses:** set `includeUsage: true` on the provider. Turning reasoning off: pass `reasoningEffort: "none"` in `providerOptions`, under the provider's `name`. Most chat models accept `none`; a few don't (their lowest is `low`) and answer 400 `unsupported_value`. Check the model's `reasoning_efforts` in `GET /v1/models/{id}` or the catalog. JavaScript: ```javascript import { generateText } from "ai"; import { createOpenAICompatible } from "@ai-sdk/openai-compatible"; const ewest = createOpenAICompatible({ name: "ewest", baseURL: "https://api.ewest.ai/v1", apiKey: process.env.EWEST_KEY, includeUsage: true, // token usage on streamed responses too }); const { text } = await generateText({ model: ewest("ewest/gemini-flash"), prompt: "Say hello in one short sentence.", maxOutputTokens: 256, providerOptions: { ewest: { reasoningEffort: "none" } }, // answer without thinking first }); console.log(text); ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/vercel-ai-sdk --- # LangChain (Python, JS) Point LangChain's chat and embedding models at eWest. LangChain's OpenAI integration works with eWest once you change the base URL, in Python and in JavaScript. Chains, agents and LangGraph use the model like any other chat model. ## Setup Install the integration packages (Python 3.10 or newer, or Node 22 or newer for JavaScript): Python: ```bash pip install langchain-openai langchain-anthropic ``` JavaScript: ```bash npm install @langchain/openai @langchain/core ``` [Create an API key](https://ewest.ai/keys) and put it in the `EWEST_KEY` environment variable (`export EWEST_KEY=sk-…`). The examples read it from there; never put the key in browser code. Create `ChatOpenAI` with the base URL `https://api.ewest.ai/v1` (`base_url` in Python, `configuration.baseURL` in JavaScript): Python: ```python import os from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="ewest/claude-haiku", base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], max_tokens=256, ) ``` JavaScript: ```javascript import { ChatOpenAI } from "@langchain/openai"; const llm = new ChatOpenAI({ model: "ewest/claude-haiku", apiKey: process.env.EWEST_KEY, configuration: { baseURL: "https://api.ewest.ai/v1" }, maxTokens: 256, }); export default llm; ``` Prefer the Anthropic format for Claude models? `ChatAnthropic` works too. Its base URL is `https://api.ewest.ai` without `/v1`, because the Anthropic client adds the path itself. Python: ```python import os from langchain_anthropic import ChatAnthropic llm = ChatAnthropic( model="ewest/claude-haiku", base_url="https://api.ewest.ai", # no /v1: the Anthropic client adds it api_key=os.environ["EWEST_KEY"], max_tokens=256, ) print(llm.invoke("Say hello in one short sentence.").content) ``` ## Choose a model Use the full model ID, including the `ewest/` prefix. The table has good starting points; [Models](https://ewest.ai/docs/models) lists every model with its context window and limits, and `GET /v1/models` returns the models your key may use. Pass it as `model`. | Use | Model ID | | --- | --- | | Fast and cheap chat, tools | `ewest/claude-haiku` | | Stronger reasoning and coding | `ewest/claude-sonnet` | | Long context (1M tokens), images, audio and video input | `ewest/gemini-flash` | | Embeddings for search and RAG | `ewest/gemini-embedding` | ## Verify it works A first request with `invoke`. It prints the answer and the token usage. Python: ```python import os from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="ewest/claude-haiku", base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], max_tokens=256, ) reply = llm.invoke("Say hello in one short sentence.") print(reply.content) print(reply.usage_metadata) ``` JavaScript: ```javascript import { ChatOpenAI } from "@langchain/openai"; const llm = new ChatOpenAI({ model: "ewest/claude-haiku", apiKey: process.env.EWEST_KEY, configuration: { baseURL: "https://api.ewest.ai/v1" }, maxTokens: 256, }); const reply = await llm.invoke("Say hello in one short sentence."); console.log(reply.content); console.log(reply.usage_metadata); ``` The request shows up in the console under **Requests** within a few seconds, with its tokens and cost. Every response carries an `x-request-id` header, its [trace ID](https://ewest.ai/docs/traces). ## Streaming and tools `stream` yields the answer in chunks. In Python, `stream_usage=True` adds token usage to the last chunk. Python: ```python import os from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="ewest/claude-haiku", base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], max_tokens=256, stream_usage=True, ) for chunk in llm.stream("Write a haiku about the sea."): print(chunk.content, end="", flush=True) print() ``` JavaScript: ```javascript import { ChatOpenAI } from "@langchain/openai"; const llm = new ChatOpenAI({ model: "ewest/claude-haiku", apiKey: process.env.EWEST_KEY, configuration: { baseURL: "https://api.ewest.ai/v1" }, maxTokens: 256, }); for await (const chunk of await llm.stream("Write a haiku about the sea.")) process.stdout.write(String(chunk.content)); console.log(); ``` Tools: describe them with `@tool` (Python) or `tool()` (JavaScript) and attach them with `bind_tools` / `bindTools`. The model returns `tool_calls`; run them and send the results back, or let a LangGraph agent do the loop. Python: ```python import os from langchain_core.tools import tool from langchain_openai import ChatOpenAI @tool def get_weather(city: str) -> str: """Get the current weather for a city.""" return f"18 C and cloudy in {city}" llm = ChatOpenAI( model="ewest/claude-haiku", base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], max_tokens=256, ) msg = llm.bind_tools([get_weather]).invoke("What is the weather in Yerevan?") for call in msg.tool_calls: print(call["name"], call["args"]) print(get_weather.invoke(call["args"])) ``` JavaScript: ```javascript import { tool } from "@langchain/core/tools"; import { ChatOpenAI } from "@langchain/openai"; import { z } from "zod"; const getWeather = tool(async ({ city }) => `18 C and cloudy in ${city}`, { name: "get_weather", description: "Get the current weather for a city.", schema: z.object({ city: z.string() }), }); const llm = new ChatOpenAI({ model: "ewest/claude-haiku", apiKey: process.env.EWEST_KEY, configuration: { baseURL: "https://api.ewest.ai/v1" }, maxTokens: 256, }); const msg = await llm.bindTools([getWeather]).invoke("What is the weather in Yerevan?"); for (const call of msg.tool_calls ?? []) { console.log(call.name, call.args); const result = await getWeather.invoke(call); // a ToolMessage to send back to the model console.log(result.content); } ``` Embeddings use `OpenAIEmbeddings` with the same base URL. In Python, set `check_embedding_ctx_length=False` so it sends plain text. This avoids sending token ids that non-OpenAI embedding models can't read. Python: ```python import os from langchain_openai import OpenAIEmbeddings embeddings = OpenAIEmbeddings( model="ewest/gemini-embedding", base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], check_embedding_ctx_length=False, # send text, not token ids ) vector = embeddings.embed_query("How do I reset my password?") print(len(vector)) ``` JavaScript: ```javascript import { OpenAIEmbeddings } from "@langchain/openai"; const embeddings = new OpenAIEmbeddings({ model: "ewest/gemini-embedding", apiKey: process.env.EWEST_KEY, configuration: { baseURL: "https://api.ewest.ai/v1" }, }); const vector = await embeddings.embedQuery("How do I reset my password?"); console.log(vector.length); ``` ## Troubleshooting - **404 `model_not_found`:** the model name needs the `ewest/` prefix (`ewest/claude-haiku`, not `claude-haiku`). Check the spelling against [Models](https://ewest.ai/docs/models). - **Empty answer from `ewest/gemini-flash`:** `ewest/gemini-flash` does not think unless reasoning is on (low, medium or high); then thinking uses output tokens and a small output limit can be used up. Allow at least 256 output tokens, or turn reasoning off (below). This is a known limitation. - **Follow-up turns forget the conversation:** on the Responses API, pass the earlier response's `id` as `previous_response_id` (conversations are stored by default), or send the full message history with every request; chat completions and Messages are always stateless. See [Responses](https://ewest.ai/docs/responses). - **401, 402 or 403:** the key is missing or wrong, out of budget, or not allowed to use this model. [Errors](https://ewest.ai/docs/errors) explains each code; a [trace ID](https://ewest.ai/docs/traces) finds the request in the console. Turning reasoning off: pass `reasoning_effort="none"` to `ChatOpenAI`. Most chat models accept `none`; a few don't (their lowest is `low`) and answer 400 `unsupported_value`. Check the model's `reasoning_efforts` in `GET /v1/models/{id}` or the catalog. `use_responses_api=True` works as well; send the full message history each turn, or use `previous_response_id` (see [Responses](https://ewest.ai/docs/responses)). Python: ```python import os from langchain_openai import ChatOpenAI llm = ChatOpenAI( model="ewest/gemini-flash", base_url="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], max_tokens=256, reasoning_effort="none", # answer without thinking first ) print(llm.invoke("Say hello in one short sentence.").content) ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/langchain --- # LlamaIndex (Python) Use eWest as the LLM and embedding model in LlamaIndex. LlamaIndex talks to eWest through its OpenAI-compatible classes: `OpenAILike` for chat and `OpenAILikeEmbedding` for embeddings. Indexes, query engines and agents then use them like any other model. ## Setup Install the two integrations (Python 3.10 or newer): pip: ```bash pip install llama-index-llms-openai-like llama-index-embeddings-openai-like ``` [Create an API key](https://ewest.ai/keys) and put it in the `EWEST_KEY` environment variable (`export EWEST_KEY=sk-…`). The examples read it from there; never put the key in browser code. Create the models with `api_base="https://api.ewest.ai/v1"`. `is_chat_model=True` sends chat requests, `is_function_calling_model=True` turns on tool calling, and `context_window` (from the model page) tells LlamaIndex how much text fits. Python: ```python import os from llama_index.core import Settings from llama_index.embeddings.openai_like import OpenAILikeEmbedding from llama_index.llms.openai_like import OpenAILike llm = OpenAILike( model="ewest/claude-haiku", api_base="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], is_chat_model=True, is_function_calling_model=True, context_window=200000, # from the model page max_tokens=256, ) embed_model = OpenAILikeEmbedding( model_name="ewest/gemini-embedding", api_base="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], ) # Use them everywhere (indexes, query engines, agents): Settings.llm = llm Settings.embed_model = embed_model ``` ## Choose a model Use the full model ID, including the `ewest/` prefix. The table has good starting points; [Models](https://ewest.ai/docs/models) lists every model with its context window and limits, and `GET /v1/models` returns the models your key may use. Chat models go in `OpenAILike(model=…)`, embedding models in `OpenAILikeEmbedding(model_name=…)`. Set `context_window` to the model's value (200,000 for Claude models, 1,048,576 for `ewest/gemini-flash`). | Use | Model ID | | --- | --- | | Fast and cheap chat, tools | `ewest/claude-haiku` | | Stronger reasoning and coding | `ewest/claude-sonnet` | | Long context (1M tokens), images, audio and video input | `ewest/gemini-flash` | | Embeddings for search and RAG | `ewest/gemini-embedding` | ## Verify it works A first chat request: Python: ```python import os from llama_index.core.llms import ChatMessage from llama_index.llms.openai_like import OpenAILike llm = OpenAILike( model="ewest/claude-haiku", api_base="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], is_chat_model=True, is_function_calling_model=True, context_window=200000, # from the model page max_tokens=256, ) response = llm.chat([ChatMessage(role="user", content="Say hello in one short sentence.")]) print(response.message.content) ``` The request shows up in the console under **Requests** within a few seconds, with its tokens and cost. Every response carries an `x-request-id` header, its [trace ID](https://ewest.ai/docs/traces). ## Streaming and tools `stream_chat` (or `stream_complete`) yields the answer as it is generated; each chunk has the new text in `delta`. Python: ```python import os from llama_index.core.llms import ChatMessage from llama_index.llms.openai_like import OpenAILike llm = OpenAILike( model="ewest/claude-haiku", api_base="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], is_chat_model=True, is_function_calling_model=True, context_window=200000, # from the model page max_tokens=256, ) for chunk in llm.stream_chat([ChatMessage(role="user", content="Write a haiku about the sea.")]): print(chunk.delta, end="", flush=True) print() ``` Tools: wrap a Python function in `FunctionTool`. `predict_and_call` lets the model pick a tool and runs it; agents such as `FunctionAgent` use the same tools. Python: ```python import os from llama_index.core.tools import FunctionTool from llama_index.llms.openai_like import OpenAILike def get_weather(city: str) -> str: """Get the current weather for a city.""" return f"18 C and cloudy in {city}" llm = OpenAILike( model="ewest/claude-haiku", api_base="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], is_chat_model=True, is_function_calling_model=True, context_window=200000, # from the model page max_tokens=256, ) # Picks the tool, runs it and returns its output. result = llm.predict_and_call([FunctionTool.from_defaults(fn=get_weather)], "What is the weather in Yerevan?") print(result) ``` Embeddings for indexes and retrieval: Python: ```python import os from llama_index.embeddings.openai_like import OpenAILikeEmbedding embed_model = OpenAILikeEmbedding( model_name="ewest/gemini-embedding", api_base="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], ) vector = embed_model.get_text_embedding("How do I reset my password?") print(len(vector)) ``` ## Troubleshooting - **404 `model_not_found`:** the model name needs the `ewest/` prefix (`ewest/claude-haiku`, not `claude-haiku`). Check the spelling against [Models](https://ewest.ai/docs/models). - **Empty answer from `ewest/gemini-flash`:** `ewest/gemini-flash` does not think unless reasoning is on (low, medium or high); then thinking uses output tokens and a small output limit can be used up. Allow at least 256 output tokens, or turn reasoning off (below). This is a known limitation. - **Follow-up turns forget the conversation:** on the Responses API, pass the earlier response's `id` as `previous_response_id` (conversations are stored by default), or send the full message history with every request; chat completions and Messages are always stateless. See [Responses](https://ewest.ai/docs/responses). - **401, 402 or 403:** the key is missing or wrong, out of budget, or not allowed to use this model. [Errors](https://ewest.ai/docs/errors) explains each code; a [trace ID](https://ewest.ai/docs/traces) finds the request in the console. - **Tools are ignored:** set `is_function_calling_model=True`. **Plain completions instead of chat:** set `is_chat_model=True`. Turning reasoning off: pass `reasoning_effort` in `additional_kwargs`. Most chat models accept `none`; a few don't (their lowest is `low`) and answer 400 `unsupported_value`. Check the model's `reasoning_efforts` in `GET /v1/models/{id}` or the catalog. Python: ```python import os from llama_index.llms.openai_like import OpenAILike llm = OpenAILike( model="ewest/gemini-flash", api_base="https://api.ewest.ai/v1", api_key=os.environ["EWEST_KEY"], is_chat_model=True, is_function_calling_model=True, context_window=1048576, max_tokens=256, additional_kwargs={"reasoning_effort": "none"}, # answer without thinking first ) print(llm.complete("Say hello in one short sentence.")) ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/llamaindex --- # GitHub Copilot (VS Code) Add eWest models to Copilot Chat in VS Code with a custom endpoint. Copilot Chat in VS Code can use your own model endpoint ("bring your own key"). Add eWest as a **Custom Endpoint** and its `ewest/*` models appear in the model picker for Ask, Edit and Agent modes. > We haven't tested this setup ourselves; it follows the tool's own documentation. If something doesn't work, contact support. > Only chat uses your endpoint. Inline code suggestions, semantic search and anything built on embeddings stay on GitHub's own models, and still need a GitHub sign-in. On Copilot Business or Enterprise, an administrator must first turn on the "Bring Your Own Language Model Key in VS Code" policy on GitHub.com. ## Setup 1. Use a current VS Code. Open the model picker in the Chat view and click the gear icon, or run **Chat: Manage Language Models** from the Command Palette. 2. Choose **Add Models**, then **Custom Endpoint**. Enter a group name (for example `eWest`), a display name and your eWest key, then pick the API type **Chat Completions**. 3. VS Code opens `chatLanguageModels.json`. Replace its contents with the file below (keep any other groups you already have), then save. 4. Pick an eWest model in the model picker. If it doesn't show up, restart VS Code. [Create an API key](https://ewest.ai/keys) and keep it in the `EWEST_KEY` environment variable (`export EWEST_KEY=sk-…`). Never commit it to a repository. The file defines one group with three models. `apiType` `chat-completions` makes VS Code call `https://api.ewest.ai/v1/chat/completions`, and every model has `toolCalling` on, which Agent mode needs. The key is read through an input variable, so VS Code asks for it instead of storing it in the file. `contextWindow` and `maxOutputTokens` are the values from the model page. chatLanguageModels.json: ```json [ { "name": "eWest", "vendor": "customendpoint", "apiKey": "${input:EWEST_KEY}", "apiType": "chat-completions", "models": [ { "id": "ewest/claude-sonnet", "name": "Claude Sonnet (eWest)", "url": "https://api.ewest.ai/v1/chat/completions", "toolCalling": true, "vision": true, "contextWindow": 1000000, "maxOutputTokens": 128000 }, { "id": "ewest/claude-haiku", "name": "Claude Haiku (eWest)", "url": "https://api.ewest.ai/v1/chat/completions", "toolCalling": true, "vision": true, "contextWindow": 200000, "maxOutputTokens": 64000 }, { "id": "ewest/gemini-flash", "name": "Gemini Flash (eWest)", "url": "https://api.ewest.ai/v1/chat/completions", "toolCalling": true, "vision": true, "contextWindow": 1048576, "maxOutputTokens": 65536 } ] } ] ``` Two other API types work as well. **Messages** suits Claude models: its base URL is `https://api.ewest.ai` without `/v1` (VS Code adds `/v1/messages`) and eWest accepts the key as `x-api-key` or as a Bearer token, so either way of sending it works. **Responses** works too. The example sets `statefulResponses` to `false`, so VS Code resends the whole conversation every turn and does not use `previous_response_id`. That does not stop eWest from storing the turns: `/v1/responses` keeps conversations by default (`store: true`, 30 days, encrypted) unless the request says `store: false` or an owner or admin has turned storing off for the organization. See [Responses](https://ewest.ai/docs/responses). Chat Completions is the simplest choice. Messages (Claude): ```json [ { "name": "eWest (Messages)", "vendor": "customendpoint", "apiKey": "${input:EWEST_KEY}", "apiType": "messages", "models": [ { "id": "ewest/claude-sonnet", "name": "Claude Sonnet (eWest, Messages)", "url": "https://api.ewest.ai", "toolCalling": true, "vision": true, "contextWindow": 1000000, "maxOutputTokens": 128000 } ] } ] ``` Responses: ```json [ { "name": "eWest (Responses)", "vendor": "customendpoint", "apiKey": "${input:EWEST_KEY}", "apiType": "responses", "models": [ { "id": "ewest/claude-sonnet", "name": "Claude Sonnet (eWest, Responses)", "url": "https://api.ewest.ai/v1/responses", "statefulResponses": false, "toolCalling": true, "vision": true, "contextWindow": 1000000, "maxOutputTokens": 128000 } ] } ] ``` ## Choose a model Use the full model ID, including the `ewest/` prefix: `ewest/claude-sonnet` for everyday coding, `ewest/claude-haiku` for fast and cheap work, `ewest/gemini-flash` when you need a very long context. [Models](https://ewest.ai/docs/models) lists every model with its context window and limits; `GET /v1/models` returns the models your key may use. | Use | Model ID | | --- | --- | | Everyday coding and Agent mode | `ewest/claude-sonnet` | | Fast and cheap chat | `ewest/claude-haiku` | | Long context (1M tokens), images | `ewest/claude-sonnet, ewest/gemini-flash` | To add a model, copy one entry in `models`, change `id` and `name`, and set `contextWindow` and `maxOutputTokens` to the values on the model page. Set `vision` to `false` for a model that doesn't take images. ## Verify it works Open Copilot Chat, choose an eWest model and send a short message. If nothing answers, send the same request without VS Code to rule out the key and model: cURL: ```bash # The request Copilot Chat sends for a message, without VS Code: curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "content-type: application/json" \ -d '{"model": "ewest/claude-haiku", "stream": true, "messages": [{"role": "user", "content": "Reply with the single word OK"}]}' ``` The request shows up in the console under **Requests** within a few seconds, with its tokens and cost. Every response carries an `x-request-id` header, its [trace ID](https://ewest.ai/docs/traces). ## Streaming and tools Chat streams by default. A model is only offered in Agent mode when it supports tool calling, so keep `toolCalling` on for the `ewest/*` chat models (all current ones support tools; the model page says so). Agent mode then reads and edits files and runs commands through tool calls on the same endpoint. ## Troubleshooting - **404 `model_not_found`:** the model name needs the `ewest/` prefix (`ewest/claude-sonnet`, not `claude-sonnet`). Check the spelling against [Models](https://ewest.ai/docs/models). - **401, 402 or 403:** the key is missing or wrong, out of budget, or not allowed to use this model. [Errors](https://ewest.ai/docs/errors) explains each code; a [trace ID](https://ewest.ai/docs/traces) finds the request in the console. - **Empty answer from `ewest/gemini-flash`:** `ewest/gemini-flash` does not think unless reasoning is on (low, medium or high); then thinking uses output tokens and a small output limit can be used up. Allow at least 256 output tokens in the editor's model settings, or turn reasoning off. - **The model is missing from the picker:** restart VS Code, check that `chatLanguageModels.json` is valid JSON, and on Business or Enterprise ask your administrator about the bring-your-own-key policy. - **The model is missing in Agent mode:** `toolCalling` must be `true` for it. - **Responses API and stored turns:** with `statefulResponses` set to `false`, VS Code sends the full history each time and does not use `previous_response_id`. eWest still stores the turns unless the request has `store: false` or storing is off for your organization (see [Responses](https://ewest.ai/docs/responses)). - **Inline suggestions don't use eWest:** this is expected; they stay on GitHub. List the models your key may use and copy the ids exactly: cURL: ```bash # The models your key may call (use these ids exactly, with the ewest/ prefix): curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models # One model, with its context window and whether it supports tools and images: curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models/ewest/claude-haiku ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/github-copilot --- # Zed Use eWest models in Zed's agent panel as an OpenAI- or Anthropic-compatible provider. Zed's agent panel can use any OpenAI-compatible or Anthropic-compatible endpoint as a language model provider. Add eWest as one, list the `ewest/*` models you want, and they appear in the model dropdown. > We haven't tested this setup ourselves; it follows the tool's own documentation. If something doesn't work, contact support. ## Setup Open the agent settings (command palette: `agent: open settings`) and use **Add Provider** under LLM Providers, or edit `settings.json` yourself. The OpenAI-compatible provider below sends chat completions to `https://api.ewest.ai/v1`. Zed only shows the models you list; `max_tokens` is the context window. settings.json (OpenAI-compatible): ```json { "language_models": { "openai_compatible": { "ewest": { "api_url": "https://api.ewest.ai/v1", "available_models": [ { "name": "ewest/claude-sonnet", "display_name": "Claude Sonnet (eWest)", "max_tokens": 1000000, "max_output_tokens": 128000, "capabilities": { "tools": true, "images": true } }, { "name": "ewest/claude-haiku", "display_name": "Claude Haiku (eWest)", "max_tokens": 200000, "max_output_tokens": 64000, "capabilities": { "tools": true, "images": true } }, { "name": "ewest/gemini-flash", "display_name": "Gemini Flash (eWest)", "max_tokens": 1048576, "max_output_tokens": 65536, "capabilities": { "tools": true, "images": true } } ] } } } } ``` The key: enter it in the provider's settings screen and Zed stores it in the system keychain, or set an environment variable named after the provider id in upper snake case plus `_API_KEY`. The provider here is `ewest`, so it is `EWEST_API_KEY`. A non-empty environment variable wins over the keychain. Never put the key in `settings.json`. [Create an API key](https://ewest.ai/keys) and keep it in the `EWEST_KEY` environment variable (`export EWEST_KEY=sk-…`). Never commit it to a repository. Shell: ```bash # The provider id "ewest" becomes EWEST_API_KEY. Start Zed from this shell so it sees the variable. export EWEST_API_KEY="$EWEST_KEY" ``` Claude models can also use Zed's Anthropic-compatible provider, which speaks the Messages API. Its base URL is `https://api.ewest.ai` without `/v1`. Prompt caching is off in the example; leave it off unless you have tested it. settings.json (Anthropic-compatible): ```json { "language_models": { "anthropic_compatible": { "ewest-claude": { "api_url": "https://api.ewest.ai", "available_models": [ { "name": "ewest/claude-sonnet", "display_name": "Claude Sonnet (eWest, Messages)", "max_tokens": 1000000, "max_output_tokens": 128000, "capabilities": { "tools": true, "images": true, "prompt_caching": false } } ] } } } } ``` Shell: ```bash # The provider id "ewest-claude" becomes EWEST_CLAUDE_API_KEY. export EWEST_CLAUDE_API_KEY="$EWEST_KEY" ``` ## Choose a model Use the full model ID, including the `ewest/` prefix: `ewest/claude-sonnet` for everyday coding, `ewest/claude-haiku` for fast and cheap work, `ewest/gemini-flash` when you need a very long context. [Models](https://ewest.ai/docs/models) lists every model with its context window and limits; `GET /v1/models` returns the models your key may use. Each entry in `available_models` needs `name` (the full `ewest/` id), a `display_name` and `max_tokens`. Set `images` to `false` for a model without image input, and `tools` to `false` for one without tool calling; Zed's agent needs tools. ## Verify it works Open the agent panel, pick the eWest model in the dropdown and send a short message. To rule out the key and model, send the same request without Zed: cURL: ```bash # The request Zed sends for a message, without Zed: curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "content-type: application/json" \ -d '{"model": "ewest/claude-haiku", "stream": true, "messages": [{"role": "user", "content": "Reply with the single word OK"}]}' ``` The request shows up in the console under **Requests** within a few seconds, with its tokens and cost. Every response carries an `x-request-id` header, its [trace ID](https://ewest.ai/docs/traces). ## Streaming and tools Zed streams answers and runs the agent's tools (reading and editing files, terminal) through tool calling, which is on by default (`capabilities.tools`). All current `ewest/*` chat models support it. ## Troubleshooting - **404 `model_not_found`:** the model name needs the `ewest/` prefix (`ewest/claude-sonnet`, not `claude-sonnet`). Check the spelling against [Models](https://ewest.ai/docs/models). - **401, 402 or 403:** the key is missing or wrong, out of budget, or not allowed to use this model. [Errors](https://ewest.ai/docs/errors) explains each code; a [trace ID](https://ewest.ai/docs/traces) finds the request in the console. - **Empty answer from `ewest/gemini-flash`:** `ewest/gemini-flash` does not think unless reasoning is on (low, medium or high); then thinking uses output tokens and a small output limit can be used up. Allow at least 256 output tokens in the editor's model settings, or turn reasoning off. - **Zed says the provider has no key:** the variable must be named after the provider id (`EWEST_API_KEY` for `ewest`, `EWEST_CLAUDE_API_KEY` for `ewest-claude`), and Zed must be started from an environment that has it. Or enter the key in the provider settings. - **404 on every request with the Anthropic-compatible provider:** its `api_url` must be `https://api.ewest.ai`, without `/v1`. For the OpenAI-compatible provider it must end in `/v1`. - **A model doesn't appear:** it is not in `available_models`, or `settings.json` has a syntax error. - **Responses-only setting:** eWest models work on chat completions, so leave `chat_completions` at its default (`true`). List the models your key may use and copy the ids exactly: cURL: ```bash # The models your key may call (use these ids exactly, with the ewest/ prefix): curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models # One model, with its context window and whether it supports tools and images: curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models/ewest/claude-haiku ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/zed --- # Continue Use eWest models for chat, edit, apply and embeddings in Continue. Continue (the VS Code and JetBrains extension) talks to eWest through its `openai` provider with a custom `apiBase`. Chat, edit and apply use eWest chat models; the embeddings role can use `ewest/gemini-embedding`. > We haven't tested this setup ourselves; it follows the tool's own documentation. If something doesn't work, contact support. > Autocomplete is not available with eWest yet. It needs a fill-in-the-middle model, and none of eWest's models supports `suffix` on `/v1/completions` (the request returns a 400). Keep the `autocomplete` role on another model. ## Setup Open Continue's config: click the configs dropdown at the top right of the chat input and the cog next to **Local Config**. That opens `~/.continue/config.yaml` (`%USERPROFILE%\.continue\config.yaml` on Windows). Add eWest models like this, then save; Continue reloads the file. [Create an API key](https://ewest.ai/keys) and keep it in the `EWEST_KEY` environment variable (`export EWEST_KEY=sk-…`). Never commit it to a repository. ~/.continue/config.yaml: ```yaml name: eWest version: 1.0.0 schema: v1 models: - name: Claude Sonnet (eWest) provider: openai model: ewest/claude-sonnet apiBase: https://api.ewest.ai/v1 apiKey: ${{ secrets.EWEST_KEY }} roles: - chat - edit - apply capabilities: - tool_use - image_input defaultCompletionOptions: maxTokens: 4096 - name: Claude Haiku (eWest) provider: openai model: ewest/claude-haiku apiBase: https://api.ewest.ai/v1 apiKey: ${{ secrets.EWEST_KEY }} roles: - chat - edit - apply capabilities: - tool_use - image_input defaultCompletionOptions: maxTokens: 4096 ``` `provider: openai` with `apiBase: https://api.ewest.ai/v1` sends chat completions to eWest. `tool_use` in `capabilities` turns on Agent mode for the model, and `roles` lists what it is used for. The key is written as `${{ secrets.EWEST_KEY }}`, which Continue resolves from its secrets; the pages we checked don't say where a local config reads them from, so look that up in Continue's docs. If you would rather not, paste the key into `apiKey` instead, and keep `config.yaml` out of any repository. For search over your codebase, add an embeddings model with the `embed` role: Embeddings: ```yaml models: - name: Embeddings (eWest) provider: openai model: ewest/gemini-embedding apiBase: https://api.ewest.ai/v1 apiKey: ${{ secrets.EWEST_KEY }} roles: - embed ``` ## Choose a model Use the full model ID, including the `ewest/` prefix: `ewest/claude-sonnet` for everyday coding, `ewest/claude-haiku` for fast and cheap work, `ewest/gemini-flash` when you need a very long context. [Models](https://ewest.ai/docs/models) lists every model with its context window and limits; `GET /v1/models` returns the models your key may use. `model` is the eWest id, `name` is what Continue shows in its picker. Add one entry per model. Embedding ids (`ewest/gemini-embedding`) belong only in `embed` entries, and chat ids only in chat roles. ## Verify it works Open the Continue chat, pick the eWest model and send a short message. To rule out the key and model, send the same request without Continue: cURL: ```bash # The request Continue sends for a chat message, without Continue: curl https://api.ewest.ai/v1/chat/completions \ -H "Authorization: Bearer $EWEST_KEY" \ -H "content-type: application/json" \ -d '{"model": "ewest/claude-haiku", "stream": true, "messages": [{"role": "user", "content": "Reply with the single word OK"}]}' ``` The request shows up in the console under **Requests** within a few seconds, with its tokens and cost. Every response carries an `x-request-id` header, its [trace ID](https://ewest.ai/docs/traces). ## Streaming and tools Chat streams by default. Agent mode needs a model with tool calling: keep `tool_use` in its `capabilities` (all current `ewest/*` chat models support tools). Without it Continue treats the model as chat-only. ## Troubleshooting - **404 `model_not_found`:** the model name needs the `ewest/` prefix (`ewest/claude-sonnet`, not `claude-sonnet`). Check the spelling against [Models](https://ewest.ai/docs/models). - **401, 402 or 403:** the key is missing or wrong, out of budget, or not allowed to use this model. [Errors](https://ewest.ai/docs/errors) explains each code; a [trace ID](https://ewest.ai/docs/traces) finds the request in the console. - **Empty answer from `ewest/gemini-flash`:** `ewest/gemini-flash` does not think unless reasoning is on (low, medium or high); then thinking uses output tokens and a small output limit can be used up. Allow at least 256 output tokens in the editor's model settings, or turn reasoning off. - **Autocomplete returns a 400 or nothing:** eWest has no fill-in-the-middle model, so `/v1/completions` with `suffix` is rejected. Use another model for the `autocomplete` role. - **The key isn't picked up:** if `${{ secrets.EWEST_KEY }}` doesn't resolve on your setup, put the key directly in `apiKey` (and keep the file private). List the models your key may use and copy the ids exactly: cURL: ```bash # The models your key may call (use these ids exactly, with the ewest/ prefix): curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models # One model, with its context window and whether it supports tools and images: curl -H "Authorization: Bearer $EWEST_KEY" https://api.ewest.ai/v1/models/ewest/claude-haiku ``` Still stuck? Follow [Troubleshoot a request](https://ewest.ai/docs/troubleshooting). Source: https://ewest.ai/docs/guides/continue