# Get Started with the AI Gateway

URL: https://www.elchi.io/docs/ai-gateway/getting-started

> The shortest complete path to a first LLM request through Elchi AI Gateway: a provider, a gateway, a consumer key and an AI listener, in the UI or through the REST API.

This walkthrough takes a project with no AI gateway to a first successful request. You create a provider, a gateway that serves one model with it, a consumer with a key, and an AI listener, deploy the listener, call it with `curl` and the OpenAI SDK, and find the request in **Usage** and **Request log**.

Every step is shown in the UI first and then as the equivalent REST call.

## Before you start

You need:

- **An edge registered to the project** with the AI gateway installed next to the agent. On Elchi OS 0.8.0+ it is in the image; on a plain Linux edge the `elchi-client` installer installs it unless you pass `--no-ai-gateway`. See [Installation](https://www.elchi.io/docs/ai-gateway/installation).
  - Check: **Administration → Clients**, open the client, tab **AI Gateway**. The **AI gateway service** panel shows the service state. "The client returned no AI gateway status (is elchi-ai-gateway installed on this edge?)" means it is not installed.
- **The Envoy version you will use installed on that edge** (the deploy drawer warns about clients without it).
- **ClickHouse configured on the edge** if you want to see the request in Usage and Request log (`usage.clickhouse_dsn` in the gateway's `config.yaml`, or `set ai-gateway usage clickhouse …` on Elchi OS). Without it the request still works.
- **The Owner or Admin role** in the project.
- **A provider API key.** The examples use OpenAI and `sk-...` as a placeholder.

Open **Infrastructure → AI Gateway**. A project without a configuration shows "This project has no AI gateway yet".

### REST setup

Every REST call below needs a bearer token and the project id. Log in once:

```bash
ELCHI=https://elchi.example.com
TOKEN=$(curl -s -X POST "$ELCHI/auth/login" \
  -H 'Content-Type: application/json' -H 'from-elchi: yes' \
  -d '{"username":"admin","password":"..."}' | jq -r .token)
PROJECT=<your project id>   # the login answer's base_project is your default project
H=(-H "Authorization: Bearer $TOKEN" -H 'from-elchi: yes' -H 'Content-Type: application/json')
```

Each write answers with the configuration it saved and a `deploy` object: `{"enqueued": true, "deploy_job": "<job id>"}`, or `{"enqueued": true, "deduped": true, "message": "..."}` when a deploy of the project is already queued (that one carries your change too).

## Step 1 — Add a provider

**UI:** tab **Providers** → **New provider**.

| Field | Value |
|---|---|
| **Name** | `openai` (lower-case letters, digits and hyphens, at most 63; `new` is reserved) |
| **Type** | `openai` |
| **API key** | your key, `sk-...` |
| **Endpoint** | leave as filled in: Host `api.openai.com`, Port 443, TLS on, Path prefix `v1` |

Click **Create and deploy**.

**REST:**

```bash
curl -s -X PUT "$ELCHI/api/v3/ai-gateway/providers" "${H[@]}" -d '{
  "project": "'"$PROJECT"'",
  "providers": [
    {"name": "openai", "type": "openai", "pathPrefix": "v1",
     "credentials": {"apiKey": "sk-..."}}
  ],
  "expected_version": 0
}'
```

`PUT /providers` replaces the whole provider list, limits and prices of the project. To add a provider later, `GET /providers?project=…`, add to the list, and send it back with the `version` you read as `expected_version` (a stale version gets `409`). Masked credentials sent back unchanged keep their stored value.

**Success looks like:** a notification "AI gateway configuration saved and applied" with "applied on N/N edge(s), version …". On the provider's page, **Check now** in the **Status** card asks the provider for its model list with the stored key (no tokens spent).

## Step 2 — Add a gateway

**UI:** tab **Gateways** → **New gateway** (disabled until a provider exists).

| Field | Value |
|---|---|
| **Name** | `team-a` |
| **Hosts** | `llm.example.com` — the `Host` your clients will send |
| **Require a key** | on |
| **Models** → **Add model** | model `gpt-4o-mini`, provider `openai` |

Leave **Request log** → **Level** at its default, metadata (one row per request, no content). Click **Create and deploy**. **Try** next to a model name asks the provider for one short answer with its stored key (a few tokens).

**REST:**

```bash
curl -s -X PUT "$ELCHI/api/v3/ai-gateway/gateways/team-a" "${H[@]}" -d '{
  "project": "'"$PROJECT"'",
  "create": true,
  "gateway": {
    "name": "team-a",
    "hosts": ["llm.example.com"],
    "requireKey": true,
    "models": [{"model": "gpt-4o-mini", "provider": "openai"}]
  }
}'
```

`create: true` refuses (`409`) a name that is already used; without it the call creates or updates. With **Require a key** on, a request without a valid key gets `401`, a consumer not allowed this gateway or model gets `403`, a consumer over its quota gets `429`. Off, anyone who reaches the listener may use the gateway.

## Step 3 — Add a consumer and a key

**UI:** tab **Consumers** → **New consumer**.

| Field | Value |
|---|---|
| **Name** | `app-1` |
| **Access** → Gateways, Providers, Models | leave empty: empty allows all |

Click **Create and deploy**. The consumer's page opens. Under **Keys** click **New key**. The dialog "New key for app-1" shows the key once ("Copy it now: it is shown only this once."). Copy it, then click **I have copied it**. Keys start with `sk-elchi-`; the control plane and the edges keep only its hash.

**REST:**

```bash
curl -s -X PUT "$ELCHI/api/v3/ai-gateway/consumers/app-1" "${H[@]}" -d '{
  "project": "'"$PROJECT"'", "create": true,
  "consumer": {"name": "app-1"}
}'

curl -s -X POST "$ELCHI/api/v3/ai-gateway/consumers/app-1/keys" "${H[@]}" \
  -d '{"project": "'"$PROJECT"'"}' | jq -r .data.key
# sk-elchi-...   (the only time it is returned)
```

## Step 4 — Create an AI listener

**UI:** tab **Listeners** → **New listener**.

| Field | Value |
|---|---|
| **Name** | `ai-edge` (also names its service; lowercase letters, digits and `-`, at most 48; may not end in `-mcp` or `-redirect`) |
| **Envoy version** | the version installed on your edge |
| **HTTPS** | off for this test |
| **Plain HTTP** | on, **Port** `8080`, **Requests**: Serve the gateways |
| **Gateways** | tick **Serve** on `team-a`; optionally pick it as **Default** |

The form warns that `team-a` requires a key and would be served over plain HTTP: keys cross the network in clear. That is acceptable for a test; in production use HTTPS with a Downstream TLS context, or redirect plain HTTP to HTTPS (see [Listeners](https://www.elchi.io/docs/ai-gateway/listeners)). Port 10088 is reserved (the AI listeners' own MCP egress) and refused.

Click **Create**. The listener, its service and bootstrap, its HTTP connection manager with the AI filters and its route are created, not deployed. The notification says "Listener ai-edge created — Choose the clients to deploy it on." and the **Manage service** drawer opens.

**REST:**

```bash
curl -s -X POST "$ELCHI/api/v3/ai-gateway/listeners" "${H[@]}" -d '{
  "project": "'"$PROJECT"'",
  "name": "ai-edge",
  "version": "<envoy version, e.g. 1.40.2>",
  "http": {"port": 8080, "mode": "serve"},
  "gateways": ["team-a"]
}'
```

For HTTPS add `"https": {"port": 8443, "tls_context": "<your Downstream TLS context>"}`; for a default gateway add `"default": "team-a"`.

## Step 5 — Deploy the listener

**UI:** in the **Manage service** drawer (Mode **Deploy**), select the edge client and click **Deploy service**. Later, the listener's page has a **Deploy** button while it runs on no client.

**REST:**

```bash
curl -s -X POST "$ELCHI/api/op/clients?project=$PROJECT&version=<envoy version>" "${H[@]}" -d '{
  "type": "DEPLOY",
  "command": {"name": "ai-edge", "project": "'"$PROJECT"'"},
  "clients": [{"client_id": "<client id>", "downstream_address": "<edge address>", "ip_mode": "fixed"}]
}'
```

**Success looks like:** the **Listeners** tab shows `ai-edge` with `:8080` under **HTTP**, the edge's address under **Served on** and `team-a` under **Gateways**; the listener's page says "Deployed on 1 client: a change reaches them live, without a restart."

## Step 6 — Send a request

The gateway is selected by the `Host` header. Either make `llm.example.com` resolve to the edge, or send the header yourself. A port in `Host` is fine (`llm.example.com:8080` matches `llm.example.com`).

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

Or with `curl --resolve llm.example.com:8080:<edge-address> http://llm.example.com:8080/v1/chat/completions …`.

With the OpenAI Python SDK (the host must resolve to the edge):

```python
from openai import OpenAI

client = OpenAI(base_url="http://llm.example.com:8080/v1", api_key="sk-elchi-...")
r = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Say hello"}],
)
print(r.choices[0].message.content)
```

The key may also be sent as `x-api-key` (Anthropic SDKs) or `api-key` (Azure OpenAI SDKs). On a gateway that requires a key, the edge removes every key header (`authorization`, `x-api-key`, `api-key`, `x-goog-api-key`) from an admitted request; the provider gets the provider's own credential.

List what the gateway serves:

```bash
curl -s http://<edge-address>:8080/v1/models -H 'Host: llm.example.com' -H 'Authorization: Bearer sk-elchi-...'
```

**Success looks like:** an OpenAI-format chat completion. More endpoints and SDKs: [Calling the gateway](https://www.elchi.io/docs/ai-gateway/calling-the-gateway).

## Step 7 — See it in Usage and Request log

- **Usage** tab: tokens per model, provider, consumer and gateway for **Today**, **This week** or **This month** (UTC). The edge reads the engine's token counters every 30 seconds and writes them to ClickHouse a few seconds later, so the request shows up within about half a minute.
- **Request log** tab (Owners and Admins): one row per request with **Time**, **Gateway**, **Consumer**, **Model**, **Provider**, **Status**, **Tokens**, **Duration** and **Content**. Rows are written within seconds. Open a row for its detail.

![The Usage tab of the AI Gateway](https://www.elchi.io/docs/img/docs/aigw-usage-light.webp)

Both read the ClickHouse the controller uses; the edge must write to the same one. See [Usage and costs](https://www.elchi.io/docs/ai-gateway/usage-and-costs) and [Request log](https://www.elchi.io/docs/ai-gateway/request-log).

## When it does not work

| What you see | Cause | Fix |
|---|---|---|
| `404` `{"error":{… "code":"gateway_not_found"}}` "no AI gateway serves this host on listener ai-edge" | The `Host` matches no gateway the listener serves, and the listener has no default gateway. | Send `Host: llm.example.com` (or make the name resolve to the edge), add the host to the gateway, or make `team-a` the listener's **Default**. |
| `404` `… "code":"model_not_found"` "the model is not served by gateway team-a" | The `model` in the body is not in the gateway's **Models**. | Use a listed model (`GET /v1/models`) or add it to the gateway. |
| `401` `… "type":"authentication_error","code":"invalid_api_key"` | The gateway requires a key and none or an unknown one was sent, or the consumer is disabled or deleted. | Send `Authorization: Bearer sk-elchi-…` with a current key. A key revoked or created a moment ago takes effect when the edge applies the deploy. |
| `422 unsupported API schema` | The client API cannot reach that provider type, e.g. `/v1/chat/completions` to a native `anthropic` provider. | Use the provider's API (`/anthropic/v1/messages`) or a provider type that endpoint reaches. See [Providers](https://www.elchi.io/docs/ai-gateway/providers). |
| Connection refused on `:8080` | The listener is not deployed on that edge, or the edge lacks the Envoy version. | Deploy it (Step 5) and check the drawer's warnings. |
| The save notification says the edges did NOT apply it, or "no connected client of the project runs the AI gateway" | The edge refused the set, is offline, or has no AI gateway installed. | Open the client's **AI Gateway** tab: service state, the applied version (`cfg …`, `behind: …`), recent logs. See [Operations](https://www.elchi.io/docs/ai-gateway/operations) and [Troubleshooting](https://www.elchi.io/docs/ai-gateway/troubleshooting). |
| Request works, but Usage and Request log stay empty | The edge has no ClickHouse DSN, or a different ClickHouse than the controller. | Set the edge's ClickHouse ([Installation](https://www.elchi.io/docs/ai-gateway/installation)) and restart the gateway. |

## Where to go next

- [Listeners](https://www.elchi.io/docs/ai-gateway/listeners): HTTPS, the redirect, several gateways on one listener.
- [Consumers and keys](https://www.elchi.io/docs/ai-gateway/consumers-and-keys) and [Quotas, limits and costs](https://www.elchi.io/docs/ai-gateway/quotas-limits-and-costs).
- [Gateways and models](https://www.elchi.io/docs/ai-gateway/gateways-and-models): one model served by several providers, with failover.
