# Calling the Gateway

URL: https://www.elchi.io/docs/ai-gateway/calling-the-gateway

> How applications and agents call an AI gateway — base URL, endpoints, keys, streaming, OpenAI and Anthropic SDKs, curl, LangChain, Claude Code — and every error a client can get.

Applications call an AI gateway the way they call OpenAI or Anthropic: same paths, same request bodies, same SDKs. Only three things change: the **base URL**, the **key** (an elchi consumer key when the gateway requires one), and the **model names** (the ones the gateway serves).

## The base URL

A request reaches a gateway when

1. it arrives on an **AI listener** that serves the gateway (its address on a client it is deployed on, and the listener's HTTPS or HTTP port), and
2. its `Host` is one of the gateway's hosts, or the gateway is that listener's default.

So the base URL is `https://<gateway host>[:<HTTPS port>]`, with the gateway host resolving to the edge's address. The listener's page shows where it runs (**Where it runs**, for example `https://10.0.0.5:443`).

| Client family | Base URL to configure | Requests go to |
|---|---|---|
| OpenAI SDKs and OpenAI-compatible tools | `https://llm.example.com/v1` | `/v1/chat/completions`, `/v1/embeddings`, … |
| Anthropic SDKs, Claude Code | `https://llm.example.com/anthropic` | `/anthropic/v1/messages` |
| Cohere rerank | `https://llm.example.com/cohere` | `/cohere/v2/rerank` |

Without DNS for the gateway host, send the `Host` header yourself (or `curl --resolve`). A request whose `Host` no gateway of the listener claims goes to the listener's default gateway, or gets 404 `gateway_not_found` when it has none. The port in `Host` is ignored.

Use the HTTPS port. A plain-HTTP port in redirect mode answers **308**, which most LLM SDKs do not follow, and a key sent there has crossed the network in clear.

## Endpoints

Paths with the default prefixes. Which provider types each one reaches is in the [endpoint × provider matrix](https://www.elchi.io/docs/ai-gateway/providers#endpoint--provider-matrix); a provider type an endpoint cannot reach answers **422**.

| Path | API |
|---|---|
| `/v1/chat/completions` | OpenAI Chat Completions (streaming with `"stream": true`) |
| `/v1/completions` | OpenAI legacy completions |
| `/v1/embeddings` | OpenAI embeddings |
| `/v1/responses`, `/v1/responses/input_tokens` | OpenAI Responses API |
| `/v1/images/generations` | OpenAI images |
| `/v1/audio/speech`, `/v1/audio/transcriptions`, `/v1/audio/translations` | OpenAI audio |
| `/v1/models` | the gateway's model list (OpenAI shape), answered by Envoy |
| `/anthropic/v1/messages` | Anthropic Messages (streaming with `"stream": true`) |
| `/anthropic/v1/messages/count_tokens` | Anthropic token counting |
| `/anthropic/v1/models` | the gateway's model list (Anthropic shape), answered by Envoy |
| `/cohere/v2/rerank` | Cohere rerank |
| `/typesafe/v1/systemone` | TypeSafe SystemOne (no streaming) |
| `/v1/files…` | OpenAI Files API — refused on gateways that require a key (**403** `files_not_allowed`) |
| `/mcp` | MCP, on gateways that serve MCP servers: [Connecting agents](https://www.elchi.io/docs/ai-gateway/mcp/connecting-agents) |

The `model` in the request body selects the model route; it must be one of the gateway's models (`GET /v1/models`). A client's own `x-ai-eg-model` header is ignored: the gateway removes it, and the engine sets it from the body.

## Keys and headers

| Header | When |
|---|---|
| `Authorization: Bearer sk-elchi-…` (or `x-api-key`, or `api-key`) | The gateway **requires a key**: one of the consumer's keys. See [Consumers and keys](https://www.elchi.io/docs/ai-gateway/consumers-and-keys#sending-the-key). |
| none | The gateway requires no key. The provider's credential is the gateway's in both cases. |
| `x-elchi-provider-key: <provider key>` | Optional, only for providers with **Client's own key** on: your own key for that provider instead of the configured one ([Providers](https://www.elchi.io/docs/ai-gateway/providers#a-clients-own-provider-key)). |

The gateway removes the consumer key headers and `x-elchi-provider-key` before anything reaches the provider. Headers such as `x-elchi-consumer` and `x-elchi-ai-gateway` are set by the gateway; values a client sends are removed or overwritten.

## Streaming and long answers

- Streaming answers (`"stream": true`) are passed through as server-sent events.
- A model route has no overall timeout. It has an **idle** timeout of 15 minutes: an answer that sends nothing for 15 minutes is cut. A multi-provider gateway may set a shorter per-attempt idle timeout ([Failover settings](https://www.elchi.io/docs/ai-gateway/gateways-and-models#failover-settings)).
- On a model served by several providers, a failed attempt is retried on another provider **only before the answer starts**; a stream that has begun is never moved.
- A request body may be up to 50 MiB.

## Examples

All examples use the gateway host `llm.example.com` and a consumer key. Leave the key out (or pass any placeholder the SDK insists on) when the gateway requires none.

### curl

```bash
curl https://llm.example.com/v1/chat/completions \
  -H "Authorization: Bearer sk-elchi-..." \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"Say hello"}]}'

# streaming
curl -N https://llm.example.com/v1/chat/completions \
  -H "Authorization: Bearer sk-elchi-..." -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o-mini","stream":true,"messages":[{"role":"user","content":"Count to five"}]}'

# Anthropic Messages
curl https://llm.example.com/anthropic/v1/messages \
  -H "x-api-key: sk-elchi-..." -H "anthropic-version: 2023-06-01" -H "Content-Type: application/json" \
  -d '{"model":"claude-sonnet","max_tokens":256,"messages":[{"role":"user","content":"Say hello"}]}'

# calling the edge by address
curl --resolve llm.example.com:443:10.0.0.5 https://llm.example.com/v1/models -H "Authorization: Bearer sk-elchi-..."
```

### OpenAI Python SDK

```python
from openai import OpenAI

client = OpenAI(base_url="https://llm.example.com/v1", api_key="sk-elchi-...")

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Say hello"}],
)
print(resp.choices[0].message.content)

stream = client.chat.completions.create(
    model="gpt-4o-mini", stream=True,
    messages=[{"role": "user", "content": "Count to five"}],
)
for chunk in stream:
    if chunk.choices:
        print(chunk.choices[0].delta.content or "", end="")
```

The SDK sends the key as `Authorization: Bearer`. It also reads `OPENAI_BASE_URL` and `OPENAI_API_KEY` from the environment, so many tools built on it need only:

```bash
export OPENAI_BASE_URL=https://llm.example.com/v1
export OPENAI_API_KEY=sk-elchi-...
```

### OpenAI Node SDK

```js
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://llm.example.com/v1", apiKey: "sk-elchi-..." });

const resp = await client.chat.completions.create({
  model: "gpt-4o-mini",
  messages: [{ role: "user", content: "Say hello" }],
});
console.log(resp.choices[0].message.content);
```

### Anthropic Python SDK

```python
import anthropic

client = anthropic.Anthropic(base_url="https://llm.example.com/anthropic", api_key="sk-elchi-...")

msg = client.messages.create(
    model="claude-sonnet",
    max_tokens=256,
    messages=[{"role": "user", "content": "Say hello"}],
)
print(msg.content[0].text)
```

The SDK sends the key as `x-api-key`. The model name is the one the gateway serves: the gateway maps it to a provider that speaks the Messages API (`anthropic`, `aws-anthropic`, `gcp-anthropic`, `openai` or `aws-bedrock`).

### LangChain

```python
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(base_url="https://llm.example.com/v1", api_key="sk-elchi-...", model="gpt-4o-mini")
print(llm.invoke("Say hello").content)
```

### Claude Code

Claude Code takes an Anthropic base URL from the environment:

```bash
export ANTHROPIC_BASE_URL=https://llm.example.com/anthropic
export ANTHROPIC_AUTH_TOKEN=sk-elchi-...   # sent as Authorization: Bearer
# or: export ANTHROPIC_API_KEY=sk-elchi-...  (sent as x-api-key)
claude
```

The gateway must serve the model names Claude Code asks for, on providers that speak the Messages API. For its MCP use, see [Connecting agents](https://www.elchi.io/docs/ai-gateway/mcp/connecting-agents).

## Errors a client can get

Errors from the gateway itself use OpenAI's error shape, which the SDKs read:

```json
{"error":{"message":"…","type":"…","code":"…"}}
```

| Status | `code` | Cause | What to do |
|---|---|---|---|
| 308 | — | Plain-HTTP port in redirect mode | Use the HTTPS URL. |
| 400 | — | The body is not valid JSON (answered by the engine) | Fix the request. |
| 401 | `invalid_api_key` | Keyed gateway: no key, an unknown or revoked key, a disabled consumer | Send a valid consumer key. |
| 403 | `gateway_not_allowed` | The consumer may not use this gateway | Change the consumer's **Gateways**. |
| 403 | `model_not_allowed` | The consumer may not use this model, or one provider of it | Change the consumer's **Models** / **Providers**. |
| 403 | `model_not_priced` | The consumer has a cost quota and the model has no price | Add the price. |
| 403 | `files_not_allowed` | The Files API on a keyed gateway | Not available on keyed gateways. |
| 403 | `sensitive_data` | The request carries sensitive data the gateway blocks | Remove it; the message names the types, never the value. |
| 403 | `sensitive_scan_overflow` | Too many values that look sensitive to check, where the policy blocks | Send less. |
| 404 | `gateway_not_found` | No gateway of this listener claims the `Host`, and the listener has no default | Use a gateway host. |
| 404 | `model_not_found` | The gateway does not serve this model | Use a model from `/v1/models`. |
| 404 | `not_found` | A route that belongs to no AI gateway (an HTTP connection manager of your own with the AI gateway on) | Call a gateway route. |
| 404 | — | A path the engine does not serve | Check the path. |
| 413 | — | The body is larger than 50 MiB | Send less. |
| 413 | `sensitive_scan_too_large` | The body is larger than the sensitive-data scan reads, where the policy blocks | Send less, or raise the policy's scan size. |
| 422 | — | The endpoint cannot reach the model's provider type (for example `/v1/chat/completions` to a native `anthropic` provider) | Use the matching endpoint, or another provider type. |
| 429 | `quota_exceeded` | The consumer used up a quota; `retry-after` says when it resets | Wait, or raise the quota. |
| 503 | `gateway_not_ready` | This edge has not applied the configuration Envoy already routes; `retry-after: 5` | Retry; persistent means an edge did not apply a push. |
| 503 | `sensitive_scan_busy`, `sensitive_scan_incomplete` | The sensitive-data scan could not start or finish in time; `retry-after: 1` | Retry. |
| 503 | `service_unavailable` | The edge's gateway has no configuration yet | Wait for the first push. |

The `type` is `authentication_error` for 401, `invalid_request_error` for 404, `rate_limit_error` for 429, `server_error` for 503, and `permission_error` for the 403 and 413 answers above.

Errors from the **provider itself** (its own 401 for a bad provider key, its 429, a 5xx) reach the client with the provider's status code; the engine may rewrite the error body into the client API's error shape. On a model served by several providers they reach the client only after the failover's retries.

MCP calls on `/mcp` answer JSON-RPC errors instead: [MCP overview](https://www.elchi.io/docs/ai-gateway/mcp/overview). The full catalogue with every message: [Error codes](https://www.elchi.io/docs/ai-gateway/reference/error-codes).
