# Gateways and Models

URL: https://www.elchi.io/docs/ai-gateway/gateways-and-models

> How a gateway is selected by host, which models it serves on which providers, models served by several providers with weights and fallbacks, the model lists, and what clients get for an unknown model.

A **gateway** is one logical LLM endpoint of the project: a set of **hosts** that select it, the **models** it serves (each on one or more [providers](https://www.elchi.io/docs/ai-gateway/providers)), whether it **requires a consumer key**, and its own limits, request log and sensitive-data settings. One project can have any number of gateways; every edge of the project receives all of them, and each [AI listener](https://www.elchi.io/docs/ai-gateway/listeners) serves the gateways bound to it.

How a request finds its way:

```mermaid
flowchart LR
  C[Client] -->|Host: llm.example.com| L[AI listener]
  L -->|Host selects| G[Gateway team-a]
  G -->|body model: gpt-4o-mini| M{Model route}
  M --> P1[provider openai]
  M -->|model 'chat'| P2[pool: openai 75% / azure 25% → bedrock]
  G -->|model not served| E[404 model_not_found]
```

1. The request's `Host` selects a gateway **among the gateways of the listener it arrived on**.
2. The engine reads the `model` from the request body and sets it as the `x-ai-eg-model` header.
3. Envoy routes on that header to the route of that model inside the gateway, which sends it to the model's provider (or provider pool).

![The gateway form: selection, MCP, models, failover](https://www.elchi.io/docs/img/docs/aigw-gateway-form-light.webp)

## Create a gateway in the UI

A gateway needs at least one provider first (**New gateway** is disabled until one exists). Only Owners and Admins change gateways.

1. Open **Infrastructure → AI Gateway** (the **Gateways** tab is the default) and click **New gateway**.
2. **Selection** section:
   - **Name** — lower-case letters, digits and hyphens, at most 63 characters, unique in the project. It cannot be changed later (create another and delete this one). `new` is reserved, and names starting with `elchi-aigw-` are refused.
   - **Hosts** — the host names that select this gateway (type a name and press Enter, space or comma). See [Hosts](#hosts).
   - **Require a key** — see [Require a key](#require-a-key).
3. **MCP** section — the MCP servers whose tools this gateway serves at `/mcp`. Choosing one turns **Require a key** on and locks it. See [MCP overview](https://www.elchi.io/docs/ai-gateway/mcp/overview).
4. **Models** section — one row per model: the model name clients send and its **Provider**. **Add model** adds a row; **Add provider** under a row turns it into a model served by several providers (see [Models served by several providers](#models-served-by-several-providers)).
5. **Failover** section — appears once a model has several providers.
6. **Token limits**, **Request log**, **Sensitive data** sections — see [Quotas, limits and costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs), [Request log](https://www.elchi.io/docs/ai-gateway/request-log) and [Sensitive data](https://www.elchi.io/docs/ai-gateway/sensitive-data).
7. Click **Save**.

When you turn **Require a key** on and no enabled consumer with a key may use the gateway, the UI asks first: `No consumer can use <name> yet — Every request to it gets 401 from this deploy until a consumer with a key is allowed on it (Consumers tab). Save anyway?`

A saved gateway is not reachable until a listener serves it. The gateways list shows a **not served** tag for such a gateway, and the gateway's page lists the listeners that serve it under **Served on**. Bind it on a listener's page: [AI listeners](https://www.elchi.io/docs/ai-gateway/listeners).

Every save validates the whole project configuration with the change, then queues a deploy to every connected edge.

## Hosts

| Rule | Detail |
|---|---|
| Form | An exact host name (`llm.example.com`) or one leading wildcard (`*.example.com`). |
| Normalised | Lower-cased. |
| Refused | A port, user info, a path, whitespace, a trailing dot, an empty entry, a host listed twice, and `"*"` (`"*" is not a host: a listener's default gateway serves the hosts its gateways do not claim`). |
| Unique | A host can be claimed by **one gateway of the project** only: `host "x" is claimed by both gateway "a" and gateway "b"`. |
| Wildcard | On Envoy, `*.example.com` matches any depth (`a.example.com`, `a.b.example.com`) but not `example.com` itself. |
| No hosts | A gateway with no hosts is reachable only as a listener's **default gateway**. A listener that serves it any other way is refused: `gateway "x" has no hosts, so it is reachable there only as the listener's default gateway`. |

On the wire:

- Envoy ignores the port in `Host` (`llm.example.com:8443` selects `llm.example.com`), strips a trailing dot, and matches case-insensitively.
- A `Host` no gateway of the listener claims goes to the listener's default gateway, or gets **404** `gateway_not_found` when the listener has none (see [AI listeners](https://www.elchi.io/docs/ai-gateway/listeners#default-gateway-and-unclaimed-hosts)).
- A host only selects a gateway **on the listeners bound to it**: sending another gateway's host to a listener that does not serve that gateway does not reach it.
- A client cannot pick a gateway with a header: the gateway sets `x-elchi-ai-gateway` itself, overwriting any value the client sent.

## Models

Each model row says which name clients send and who serves it.

| Field | Meaning |
|---|---|
| Model name | The `model` value clients send. Unique within the gateway. The same name may appear in several gateways, even on different providers. Focus the field to see the provider's own model list (OpenAI-compatible and Anthropic providers; see [Providers](https://www.elchi.io/docs/ai-gateway/providers#model-lists-check-now-and-try)). |
| **Provider** | The provider that serves it. |
| **Try** | Next to the name for `openai` and `anthropic` providers: asks the provider for one short answer with the stored key (a few tokens). |
| `ownedBy` (API only) | What `/v1/models` reports as `owned_by`. Default: the type of the provider that answers first. |

The name is sent upstream as the client sent it, unless the provider has a **Model override**, or the model's provider entry names a model of its own (below).

A request for a model the gateway does not list never reaches a provider: Envoy answers **404**:

```json
{"error":{"message":"the model is not served by gateway team-a; GET /v1/models lists the ones it serves","type":"invalid_request_error","code":"model_not_found"}}
```

The form needs at least one model, unless the gateway serves MCP. Removing a model from a gateway takes effect with the next deploy; clients asking for it then get the 404 above.

## Models served by several providers

A model can be served by up to **8** provider entries. Clients still send one model name; Envoy picks the provider.

In the UI, click **Add provider** under a model row. The row then shows a table:

| Column | Meaning |
|---|---|
| **Provider** | A provider of the project. |
| **Model at the provider** | The model's name at this provider. Empty (**Same name**): the client's name. Each entry with a name of its own is a separate backend (`<provider>~<model>`) whose usage is still billed to the provider. |
| **Role** | **Primary** (priority 0) or **Fallback 1** … **Fallback 4**. At least one entry must be Primary. |
| **Weight** | 1–100 (default 1): the entry's share of the requests **within its level**. |

The row shows the routing in one line, for example `openai 75% · azure 25% → bedrock (anthropic.claude-3-5-sonnet-20240620-v1:0)`. Removing entries until one is left with no model name of its own makes it a plain one-provider model again.

How Envoy uses the entries (proven against a real Envoy in the sidecar's end-to-end tests and the elchi e2e suite):

- **Within a level**, requests are split by weight.
- **A fallback level takes requests only while the level above has no healthy provider**, or on a retry. One healthy provider left in the primary level keeps the whole primary share.
- **A retry goes to another provider of the same level first**, then to the next level. Envoy picks a provider other than the one that failed even with uneven weights (it retries the pick enough times for a 99.9% chance).
- **A retry happens only before the answer starts.** A streamed answer that already began is never moved to another provider.
- The engine translates and signs each attempt for the provider it reaches, also across APIs: an OpenAI-format primary can fall back to a Bedrock or Vertex provider.
- Envoy's default limit of 3 concurrent retries per cluster is lifted, so retries are not dropped under load.

### Failover settings

The **Failover** section applies to every multi-provider model of the gateway.

| Setting (UI) | API field | Default | Meaning |
|---|---|---|---|
| **Move a request on after** | `retryOn` | all three | **Connection failures and resets** (`connect-failure`: connect failure, refused stream, reset), **Server errors (500, 502, 503, 504)** (`5xx`), **Rate limited (429)** (`429`). At least one. |
| **Retries** | `numRetries` | `0` | `0` = one retry per other provider of the model, at most 5. 1–5 sets the number. A model whose single entry only renames the model retries only when you set a number. |
| **Give up on a silent attempt after** | `perTryIdleTimeout` | empty | A duration from 1s to 10m (`30s`, `2m`, `1m30s`). An attempt silent that long ends: before the answer, the next provider is tried; **mid-answer, a stream pausing that long is cut**. Set it above a model's longest pause. Empty: the route's idle timeout (15 minutes). |
| **Leave out a provider failing in a row** | `outlier` | on, 3 errors, 30s | After **After errors in a row** (1–100) server errors or failed connections in a row, requests skip the provider for **Leave it out for** (1s–1h), then try it again. 429 does not count: a provider that keeps rate-limiting stays in the rotation (its retries go to the others). Off in the API: `"outlier": {}`. |

Retries wait 0.1 s, growing to at most 1 s, between attempts.

### Rules that follow from several providers

- **Prices**: usage is billed to the provider that served, under the name it was asked for. Price each entry as `{provider, model: <its model at the provider>}`. See [Quotas, limits and costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs).
- **Consumers with a provider list**: a consumer may use the model only if it may use **every** provider of it (Envoy picks after the check); otherwise **403** `model_not_allowed`. The page shows a note for such a consumer.
- **Consumers with a cost quota**: every provider of the model must have a price, or the model is refused with **403** `model_not_priced`.
- **A client's own provider key** is refused on any provider of a multi-provider model.
- **Mixing a native `anthropic` provider with OpenAI-format providers** in one model fails half of the requests (a retry cannot translate between them). The page shows a note; use `aws-anthropic` or `gcp-anthropic` for Claude there.
- The [request log](https://www.elchi.io/docs/ai-gateway/request-log) names the provider that served each request; when Envoy's access log for it did not arrive within 2 seconds, it names the candidates as `openai|azure`.
- The provider's page shows, per edge, whether a pool member is currently ejected (**Ask the edges**, see [Provider status](https://www.elchi.io/docs/ai-gateway/providers#provider-status)).

## Model lists: /v1/models

Envoy answers each gateway's model list itself; no provider is called:

- `GET /v1/models` (OpenAI shape):

  ```json
  {"data":[{"id":"gpt-4o-mini","created":1735689600,"object":"model","owned_by":"openai"}],"object":"list"}
  ```

- `GET /anthropic/v1/models` (Anthropic shape):

  ```json
  {"data":[{"id":"gpt-4o-mini","type":"model","display_name":"gpt-4o-mini","created_at":"2025-01-01T00:00:00Z"}],"first_id":"gpt-4o-mini","has_more":false,"last_id":"gpt-4o-mini"}
  ```

Details:

- The list is the gateway selected by `Host` on that listener (the default gateway for unclaimed hosts). Any method and any query string get the same answer.
- `created` is a fixed date (2025-01-01) for every model.
- On a gateway that requires a key, the list needs a valid key too (**401** without one).
- The list is the gateway's, not the consumer's: a consumer limited to some models still sees all of them, and gets **403** `model_not_allowed` for the others.
- A gateway's list must stay under 1 MiB; a save that makes it larger is refused.

## Require a key

With **Require a key** off, anyone who can reach the listener can use the gateway; requests are not tied to a consumer.

With it on, only requests carrying an enabled consumer's elchi virtual key are let through, and the consumer's allow lists and quotas apply:

| Request | Answer |
|---|---|
| No key, an unknown key, a revoked key, a disabled consumer | **401** `invalid_api_key` |
| A consumer limited to other gateways | **403** `gateway_not_allowed` |
| A model, or a provider of it, outside the consumer's lists | **403** `model_not_allowed` |
| A consumer over a quota | **429** `quota_exceeded`, with `retry-after` |
| The Files API (`/v1/files…`) | **403** `files_not_allowed` (files belong to the provider's account and would be shared by every consumer) |

The client's key is removed before the provider is called; the provider always gets the provider's own credential. Keys, headers and quotas: [Consumers and keys](https://www.elchi.io/docs/ai-gateway/consumers-and-keys), [Quotas, limits and costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs).

A gateway that serves MCP always requires a key.

## gateway_not_ready (503)

On a gateway that requires a key, or whose sensitive-data policy reads requests, each edge's `elchi-ai-gateway` checks the request against **its own applied configuration**. When Envoy already routes a gateway or model that this edge's configuration does not have yet (a push not applied yet, or rejected by that edge), the request is refused rather than let through unchecked:

```
HTTP/1.1 503
retry-after: 5
{"error":{"message":"this edge's AI gateway configuration does not serve model \"gpt-4o\" on gateway team-a yet; retry shortly","type":"server_error","code":"gateway_not_ready"}}
```

It clears once the edge applies the configuration. When it persists, check the edge's applied version and reload failures: [Operations](https://www.elchi.io/docs/ai-gateway/operations).

## Per-gateway limits, request log, sensitive data

- **Token limits** — counters the engine computes for this gateway's requests: [Quotas, limits and costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs#token-limits-cel).
- **Request log** — `Off`, `Metadata` (default) or `Full`: [Request log](https://www.elchi.io/docs/ai-gateway/request-log).
- **Sensitive data** — overrides of the project's policy for this gateway: [Sensitive data](https://www.elchi.io/docs/ai-gateway/sensitive-data).

## Delete a gateway

A gateway a listener serves cannot be deleted: the API answers **409** `gateway "x" is served by listener y: take it off first`. A gateway that a consumer's gateway list names cannot be deleted either (the UI says `… use it; change them first`). Remove it from the listeners and consumers first. A deleted gateway's file leaves every edge with the next deploy.

## REST API

| Method and path | Body / query |
|---|---|
| `GET /api/v3/ai-gateway/gateways?project=` | All gateways (each with `version`, `updated_at`, `updated_by`). |
| `GET /api/v3/ai-gateway/gateways/:name?project=` | One gateway. |
| `PUT /api/v3/ai-gateway/gateways/:name` | `{project, gateway, expected_version, create}` |
| `DELETE /api/v3/ai-gateway/gateways/:name?project=` | |

`PUT` creates or updates. `create: true` refuses a name already used (**409**); `expected_version: 0` creates or updates whatever is stored; a version other than the stored one is **409**. The name in the body must match the path.

```bash
curl -s -X PUT "$ELCHI/api/v3/ai-gateway/gateways/team-a" \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "project": "'"$PROJECT"'",
    "create": true,
    "gateway": {
      "name": "team-a",
      "hosts": ["llm.example.com"],
      "requireKey": true,
      "models": [
        {"model": "gpt-4o-mini", "provider": "openai"},
        {"model": "chat", "providers": [
          {"provider": "openai", "model": "gpt-4o", "weight": 3},
          {"provider": "azure", "model": "gpt-4o", "weight": 1},
          {"provider": "bedrock", "model": "anthropic.claude-3-5-sonnet-20240620-v1:0", "priority": 1}
        ]}
      ],
      "failover": {"perTryIdleTimeout": "60s"},
      "capture": {"level": "metadata"}
    }
  }'
```

The answer carries the stored gateway, the queued deploy and the configuration's notes (`warnings`).

## Verify

```bash
# the gateway's model list (add -H "Authorization: Bearer sk-elchi-..." when it requires a key)
curl -s https://llm.example.com/v1/models

# a request for a listed model
curl -s https://llm.example.com/v1/chat/completions -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o-mini","messages":[{"role":"user","content":"ping"}]}'
```

- `gateway_not_found` (404): no gateway of this listener claims the host, and the listener has no default.
- `model_not_found` (404): the model is not in the gateway's list; compare with `/v1/models`.
- `gateway_not_ready` (503) that does not clear: an edge did not apply the configuration.
- More: [Calling the gateway](https://www.elchi.io/docs/ai-gateway/calling-the-gateway), [Troubleshooting](https://www.elchi.io/docs/ai-gateway/troubleshooting).
