---
title: "LLM gateway tutorial: run Bifrost, add a fallback, cap spend"
type: "guide"
url: "https://aifordevs.org/articles/llm-gateway-tutorial"
markdown: "https://aifordevs.org/articles/llm-gateway-tutorial.md"
publisher: "AI for Devs"
license: "https://aifordevs.org/reuse"
attribution: "Credit AI for Devs and link to https://aifordevs.org/articles/llm-gateway-tutorial"
description: "An LLM gateway tutorial: run Bifrost locally, add OpenAI and Anthropic, send OpenAI-format requests, force a fallback, and cap spend with a virtual-key budget."
author: "AI for Devs"
published: "2026-11-24"
level: "Intro"
topics: ["apis", "models"]
---

# LLM gateway tutorial: run Bifrost, add a fallback, cap spend

An LLM gateway tutorial: run Bifrost locally, add OpenAI and Anthropic, send OpenAI-format requests, force a fallback, and cap spend with a virtual-key budget.

> **TL;DR**
>
> - This LLM gateway tutorial runs Bifrost on `localhost:8080`, adds OpenAI and Anthropic, sends OpenAI-format requests, adds a fallback, and caps spend with a virtual-key budget.
> - Every command, port, config key, and endpoint comes from the Bifrost docs as read on November 23, 2026. None of the commands were run for this article, and the sample outputs are the docs' own.
> - A fallback is a `fallbacks` array in the request body. When the primary fails after its retries, Bifrost tries each entry in order and marks the answer with `is_fallback: true`.
> - A virtual-key budget is checked before each call and charged after it, so the request that crosses the limit completes and the next one gets a `402 budget_exceeded`.
> - The docs' fallback example names `claude-3-5-sonnet-20241022`, which Anthropic retired on October 28, 2025. This guide uses `claude-haiku-5-5` instead.

An LLM gateway gives your code one endpoint for every model provider and moves keys, failover, and spend limits out of application code. This LLM gateway tutorial builds one in five steps with [Bifrost](https://www.getmaxim.ai), an [open-source AI gateway](https://github.com/maximhq/bifrost) written in Go. The steps run the gateway, add two providers, send requests, force a fallback, and stop a key at its budget.

Read this before you copy anything: no command here was run for this article. Each one is taken from, or assembled out of, the Bifrost quickstart and feature pages as they read on November 23, 2026, and the JSON outputs are the samples printed in those pages. Where the docs disagree with each other, or with a provider's current model list, the text says so.

## What you build in this LLM gateway tutorial

You end up with one Bifrost process on `localhost:8080` that accepts requests in the OpenAI format and routes them to OpenAI or Anthropic. Your code talks to one URL. The gateway holds the provider keys, fails over when the primary provider errors, and refuses a key's requests once its budget is spent.

**Figure 1.** Inference calls use two routes on one port. Provider keys never leave the gateway's environment, and the dashed admin calls are what each step uses to change stored config.

| Step | Endpoint or setting | What it proves |
| --- | --- | --- |
| 1. Run the gateway | `npx -y @maximhq/bifrost` or `maximhq/bifrost` on Docker | The gateway starts with no config file |
| 2. Add providers | `POST /api/providers` | Keys are stored as `env.` references, not raw values |
| 3. Send requests | `POST /v1/chat/completions` | One request format reaches both providers |
| 4. Add a fallback | `fallbacks` in the request body | A failed primary is replaced without a client retry |
| 5. Cap spend | `POST /api/governance/virtual-keys` | A spent key gets a `402` before any provider is called |

The concept behind this is the [AI gateway](https://aifordevs.org/glossary#ai-gateway). For the case for routing everything through one interface, see [what a unified AI API buys you](https://aifordevs.org/articles/unified-ai-api). For how Bifrost compares with other gateways, see the [LLM gateway ranking](https://aifordevs.org/articles/best-llm-gateways).

## Before you start

You need three things: a way to run the gateway, two provider keys, and a client. Check the model IDs first, because the ones in the docs examples are not all current.

1. Node.js for `npx`, or Docker.
2. An OpenAI API key and an Anthropic API key.
3. `curl`, plus Python with the `openai` package for the SDK example.

The Bifrost docs examples use `openai/gpt-4o-mini` and, for fallbacks, `anthropic/claude-3-5-sonnet-20241022`. Anthropic's [deprecations page](https://platform.claude.com/docs/en/about-claude/model-deprecations) lists that Claude model as retired on October 28, 2025, and requests to retired models fail. This guide uses `anthropic/claude-haiku-5-5`, the cheapest current Claude model on Anthropic's [models overview](https://platform.claude.com/docs/en/about-claude/models/overview) as of November 23, 2026.

`gpt-4o-mini` still works, but OpenAI's [deprecations page](https://developers.openai.com/api/docs/deprecations) lists it as deprecated, with shutdown on January 14, 2027. Swap in any model your keys can reach. The [API pricing guides](https://aifordevs.org/articles/openai-api-pricing) on this site list current model IDs and prices.

## Step 1: run Bifrost locally

Start Bifrost with one command, after exporting your provider keys. The provider config in Step 2 reads the keys from the gateway's environment, so they must be set in the shell or container that runs Bifrost, not only in your client's shell.

```bash
export OPENAI_API_KEY="your-openai-api-key"
export ANTHROPIC_API_KEY="your-anthropic-api-key"

# Option A: npx
npx -y @maximhq/bifrost

# Option B: Docker, with a volume so config survives restarts
docker run -p 8080:8080 -v $(pwd)/data:/app/data \
  -e OPENAI_API_KEY -e ANTHROPIC_API_KEY maximhq/bifrost
```

The [setup quickstart](https://docs.getbifrost.ai/quickstart/gateway/setting-up) gives port 8080 as the default, changed with `-port` on npx or `-e APP_PORT=8080 -p 8080:8080` on Docker. The bind host defaults to `localhost`. The `-e OPENAI_API_KEY` form is plain Docker: it copies the variable from your shell into the container.

With npx, Bifrost keeps its data in `~/.config/bifrost` on Linux and macOS unless you pass `-app-dir`. That directory holds `config.db`, the SQLite database behind the UI and the admin API, and `logs.db`, the request log. With Docker, the mounted volume becomes the app directory.

Open `http://localhost:8080` to see the web UI. No config file is needed, and every step below can be done in the UI or over HTTP. The docs state that a fresh instance has no password, so anyone who can reach the port can open the dashboard and the admin API. That is acceptable on your laptop, and the last section covers what to change before anyone else can reach it.

## Step 2: add OpenAI and Anthropic as providers

Add each provider with one `POST` to `/api/providers`. The `env.` prefix on `value` tells Bifrost to read the key from an environment variable instead of storing the secret itself.

```bash
curl --location 'http://localhost:8080/api/providers' \
--header 'Content-Type: application/json' \
--data '{
    "provider": "openai",
    "keys": [
        {
            "name": "openai-key-1",
            "value": "env.OPENAI_API_KEY",
            "models": ["*"],
            "weight": 1.0
        }
    ]
}'

curl --location 'http://localhost:8080/api/providers' \
--header 'Content-Type: application/json' \
--data '{
    "provider": "anthropic",
    "keys": [
        {
            "name": "anthropic-key-1",
            "value": "env.ANTHROPIC_API_KEY",
            "models": ["*"],
            "weight": 1.0
        }
    ]
}'
```

`"models": ["*"]` lets the key serve any model from that provider. `weight` matters once a provider has two or more keys: Bifrost splits traffic between them in proportion to the weights, and the [provider configuration page](https://docs.getbifrost.ai/quickstart/gateway/provider-configuration) shows a 0.7 and 0.3 split. Each key in a provider needs a unique `name`, and Bifrost redacts key values in GET responses and in the UI.

In the UI, the same step is **Model Providers** in the sidebar, then the provider, then its keys. The same provider page has a `config.json` form of these calls if you want the setup in version control.

## Step 3: send OpenAI-compatible requests

Send requests to `/v1/chat/completions` with the model written as `provider/model`. The request and the response use the OpenAI format whichever provider serves the call, so switching providers means changing one string.

```bash
curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [{"role": "user", "content": "Hello, Bifrost!"}]
  }'
```

To reach Anthropic, change only the model: `"model": "anthropic/claude-haiku-5-5"`. A bare name such as `gpt-4o-mini` also works, because Bifrost resolves the provider from its model catalog.

If this first call comes back as `401` with type `virtual_key_required`, your build already requires virtual keys on inference. The docs disagree on the default. The [client config reference](https://docs.getbifrost.ai/deployment-guides/config-json/client) lists `enforce_auth_on_inference` as `false`, and the virtual keys page says governance is optional by default. A note on the same virtual keys page says new deployments have it on by default. Check **Settings**, then **Security**, in the UI, or create the virtual key in Step 5 first and send it with this request.

## Step 4: add a fallback and force it to fire

Add a `fallbacks` array to the request body, and Bifrost tries each entry in order when the primary fails. Each entry is a `provider/model` string, and the first provider that succeeds returns the response.

```bash
curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [{"role": "user", "content": "Explain DNS in two sentences"}],
    "fallbacks": ["anthropic/claude-haiku-5-5"]
  }'
```

The response body carries `extra_fields.routing_info`. When the fallback served the call, the [retries and fallbacks page](https://docs.getbifrost.ai/features/retries-and-fallbacks) shows it like this, from the docs' own sample with a different model:

```json
"routing_info": {
  "provider": "anthropic",
  "model": "claude-3-5-sonnet-20241022",
  "is_fallback": true,
  "primary_provider": "openai",
  "primary_model": "gpt-4o-mini"
}
```

The drop-in SDK routes return the provider's own response shape with no `extra_fields`, so read the same facts from the [response headers](https://docs.getbifrost.ai/providers/response-headers) there: `x-bifrost-routing-info-is-fallback`, `x-bifrost-routing-info-primary-provider`, and `x-bifrost-fallback-index`, which counts from 1.

To see the fallback fire, make the primary fail on purpose with a model name OpenAI does not have:

```bash
curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/not-a-real-model",
    "messages": [{"role": "user", "content": "Explain DNS in two sentences"}],
    "fallbacks": ["anthropic/claude-haiku-5-5"]
  }'
```

This was not run, so here is what the docs predict. OpenAI answers `model_not_found`, which Bifrost classes as `model_access`, a key-bound failure. With one OpenAI key there is no other key to rotate to, so the primary attempt ends with that error. Bifrost then moves to the fallback because you named it in the request. A fallback is skipped only when the caller cancelled, a plugin blocked fallbacks, or the error was the request's own fault on a fallback the model catalog added. If every provider fails, you get the primary's original error back.

**Figure 2.** Governance refuses a request before any provider is called. Only a provider failure, after its retries, takes the fallback branch, and a chain that runs out returns the primary's error, not the last one.

### Retries are a separate setting

Retries repeat the request against the same provider, and they are off by default with `max_retries: 0`. Turn them on per provider in `network_config`, then send the provider's `POST /api/providers` body again with this block added:

```json
"network_config": {
  "max_retries": 3,
  "retry_backoff_initial": 500,
  "retry_backoff_max": 5000
}
```

With retries on, a `5xx` or network error is retried on the same key with exponential backoff and jitter. A `429` rotates to another key in the pool, with backoff, because account-level quotas can be shared across keys. A rejected credential, an empty quota, or a model the key cannot reach rotates at once with no backoff, and that rotation happens even at `max_retries: 0`.

Each fallback provider gets its own full retry budget. The docs' example is a primary and two fallbacks, each at `max_retries: 3`, which allows up to 12 attempts before the caller sees an error. Set retry counts with that product in mind. To test the chain under real faults rather than a typo, see [failover testing](https://aifordevs.org/articles/failover-testing).

## Step 5: cap spend with a virtual-key budget

Create a virtual key with a budget, and Bifrost refuses that key's requests once its recorded spend reaches the limit. Your apps send the virtual key instead of a provider key, and each virtual key carries its own allowed providers, models, budgets, and rate limits.

```bash
curl -X POST http://localhost:8080/api/governance/virtual-keys \
  -H "Content-Type: application/json" \
  -d '{
    "name": "tutorial-app",
    "provider_configs": [
      {"provider": "openai", "allowed_models": ["*"], "key_ids": ["*"]},
      {"provider": "anthropic", "allowed_models": ["*"], "key_ids": ["*"]}
    ],
    "budgets": [
      {"max_limit": 5.00, "reset_duration": "1d"}
    ],
    "is_active": true
  }'
```

The response returns the key under `virtual_key`, and its `value` field holds the secret, which starts with `sk-bf-`. The [virtual keys page](https://docs.getbifrost.ai/features/governance/virtual-keys) has three details that decide whether this body works:

1. `key_ids` goes inside each `provider_configs` entry. `["*"]` allows every key for that provider. An empty or missing `key_ids` denies all keys, so the virtual key reaches nothing.
2. `budgets` is always an array. The older singular `budget` field is ignored.
3. List every provider the key should reach. Provider access is deny-by-default unless **Allow all providers** is on, and governance runs again for each fallback. Leave Anthropic out here and the fallback from Step 4 is refused for this key.

`max_limit` is in dollars, and Bifrost prices each request from its model catalog using token usage and request type. `reset_duration` takes `1m`, `1h`, `1d`, `1w`, `1M`, `1Q`, or `1Y`, and the [budget and limits page](https://docs.getbifrost.ai/features/governance/budget-and-limits) describes calendar-aligned resets in UTC as an option.

Send the key in the `x-bf-vk` header, or as `Authorization: Bearer sk-bf-...`:

```bash
curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "x-bf-vk: sk-bf-your-key" \
  -d '{"model": "openai/gpt-4o-mini", "messages": [{"role": "user", "content": "Hi"}]}'
```

### Make the key mandatory

A request with no virtual key skips governance when enforcement is off, which would let any caller bypass the budget. Turn enforcement on:

```bash
curl -X PUT http://localhost:8080/api/config \
  -H "Content-Type: application/json" \
  -d '{"client_config": {"enforce_auth_on_inference": true}}'
```

In the open-source UI this is the **Enforce Virtual Keys on Inference** toggle under **Settings**, then **Security**. A request with no key now gets a `401` with type `virtual_key_required`.

### Watch the budget stop a request

Create a second key with `"max_limit": 0.01` and send a few calls with it. The budget is checked before each call and charged after it, so the call that crosses the limit still completes and the next one is refused. The docs' own example, drawn in Figure 3, has $9 of a $10 budget used, a $2 request allowed, usage at $11, and the following request blocked.

**Figure 3.** The check happens before the call and the charge after it, so a budget can end above its limit by the cost of one request. Size limits with your largest expected request in mind.

The refusal is a `402`. This sample is the docs' message for a $100 limit:

```json
{
  "type": "budget_exceeded",
  "status_code": 402,
  "error": {
    "message": "Budget exceeded: vk_model_config * budget exceeded: 105.5000 >= 100.0000 dollars"
  }
}
```

Branch on the top-level `type` field in your client, not on `error.type`, which this shape does not carry.

### Use the virtual key from the OpenAI SDK

Existing OpenAI SDK code needs a new base URL and the virtual key in place of the provider key. The [OpenAI SDK integration](https://docs.getbifrost.ai/integrations/openai-sdk) serves the drop-in route at `/openai`, and the SDK's `api_key` travels as the `Authorization: Bearer` header that Bifrost reads as a virtual key.

```python
import openai

client = openai.OpenAI(
    base_url="http://localhost:8080/openai",
    api_key="sk-bf-your-key",
)

response = client.chat.completions.create(
    model="anthropic/claude-haiku-5-5",
    messages=[{"role": "user", "content": "Hello from Claude"}],
)
print(response.choices[0].message.content)
```

The same page has the JavaScript client, and Bifrost serves an `/anthropic` route for the Anthropic SDK.

## What each refusal returns

Once Steps 4 and 5 are in place, a request can fail at the gateway or at a provider, and the response says which. These are the shapes the docs list, which makes them the cases to handle in client code.

| Status | Top-level `type` | When it happens | Provider called? |
| --- | --- | --- | --- |
| `401` | `virtual_key_required` | No key sent while enforcement is on | No |
| `403` | `access_blocked` | Key inactive or expired | No |
| `403` | `model_blocked` | Model not in the key's `allowed_models` | No |
| `429` | `token_limited` or `request_limited` | The key's rate limit ran out | No |
| `402` | `budget_exceeded` | A budget that applies is spent | No |
| `502` | `upstream_credentials_exhausted` | Every provider key was rejected for credentials or quota within the retry budget | Yes |
| Primary's status | Primary's error | Primary and every fallback failed | Yes |

The first five come from governance and cost nothing at the provider. The last two mean provider keys or providers failed, which points at your provider accounts rather than the caller. Bifrost returns `502` instead of the raw provider `401` so a caller does not mistake a revoked provider key for a problem with its own virtual key.

## Before you expose it beyond localhost

The quickstart labels the unversioned commands above as for local evaluation. Before anyone else can reach the gateway, the docs ask for four changes:

1. **Pin a version.** Use `npx -y @maximhq/bifrost --transport-version v2.4.0` or the `maximhq/bifrost:v2.4.0` image instead of the latest tag.
2. **Password-protect the dashboard.** Set `BIFROST_SETUP_TOKEN` before start, for example `export BIFROST_SETUP_TOKEN=$(openssl rand -hex 32)`. Then turn on **Password protect the dashboard** under **Workspace**, **Config**, **Security**, and paste the token when creating the first admin. The [auth setup page](https://docs.getbifrost.ai/quickstart/gateway/setting-up-auth) covers inference auth once dashboard auth is on.
3. **Put TLS in front of it.**
4. **Choose durable storage.** Config and logs can move from SQLite to PostgreSQL 16 or later, and the database must use `UTF8` encoding.

The same governance that capped this key also covers security at scale: virtual keys, budgets, guardrails, and audit logs are applied centrally at the gateway. For AI tools that never call a gateway URL, such as coding agents and desktop chat apps on employee laptops, [Bifrost Edge](https://www.getmaxim.ai/edge) extends those same controls to each machine, with [guardrails and policy enforced on the device](https://docs.getbifrost.ai/edge/security). The [shadow AI guide](https://aifordevs.org/articles/shadow-ai) covers that side.

On cost, the gateway overhead is small next to model time. The Bifrost team's [benchmarks](https://docs.getbifrost.ai/benchmarking/getting-started) report about 11 microseconds per request at 5,000 requests per second on a t3.xlarge. The larger cost lever is what traffic reaches a provider at all, which is where [semantic caching](https://aifordevs.org/articles/semantic-caching) comes in.

## Where to take the gateway next

The five steps leave you with a gateway that has the parts most teams add first: one API, two providers, a fallback, and a budget. Before you route real traffic, do these in order:

1. Move the provider and virtual-key setup into `config.json` so it lives in version control, and keep `env.` references for every secret.
2. Give each app or team its own virtual key with its own budget, so one runaway loop cannot spend another team's money.
3. Add a second key per provider and set `max_retries`, so a `429` rotates keys before it reaches a fallback.
4. Replace the typo test in Step 4 with real fault injection, as in [failover testing](https://aifordevs.org/articles/failover-testing), and confirm `is_fallback` in your logs.
5. Handle every `type` in the refusal table in client code, and alert on `502 upstream_credentials_exhausted`, which means a provider account needs attention.

If you are still choosing a gateway rather than configuring one, the [ranked comparison of LLM gateways](https://aifordevs.org/articles/best-llm-gateways) covers how Bifrost and the alternatives differ on failover, budgets, and licensing.

## Questions

### What is an LLM gateway?

An LLM gateway is a service that sits between your application and model providers. Your code sends every request to one endpoint, and the gateway holds the provider keys, picks the provider, retries or fails over on errors, and applies budgets and rate limits. Bifrost, the gateway in this tutorial, accepts requests in the OpenAI format and routes them to OpenAI, Anthropic, and other providers.

### Does an LLM gateway add latency?

Yes, but for a compiled gateway the overhead is small next to model response time. The Bifrost team's published benchmark reports about 11 microseconds of added latency per request at 5,000 requests per second on a t3.xlarge instance. Retries and fallbacks add time only when a provider fails, because each extra attempt is another upstream call.

### Is an LLM gateway the same as an LLM proxy?

A proxy forwards requests to a provider. A gateway forwards them and also applies policy: fallbacks across providers, key rotation, budgets, rate limits, and request logging. Steps 4 and 5 of this tutorial are the parts a plain proxy does not do. Most gateways also translate between API formats, so one client can reach providers with different native APIs.

### Can I self-host an LLM gateway?

Yes. Bifrost runs from npx, Docker, Kubernetes, or the Go SDK inside your own network, so prompts and provider keys pass only through infrastructure you control. The open-source core is Apache 2.0. A local instance like the one in this tutorial has no password by default, so add dashboard authentication, a pinned version, and TLS before other people can reach it.

### Do you need an LLM gateway?

A gateway pays off once you call more than one provider, share provider keys across apps or people, or need a hard spend cap per team or project. A single script calling one model gains little from it. The deciding question is usually whether you want failover and budgets written once in shared infrastructure or rewritten in every service.

### What happens when an LLM gateway budget runs out?

In Bifrost, a request whose virtual key has no remaining budget is refused with HTTP 402 and a top-level type of budget_exceeded, before any provider is called. The check runs before the call and the cost is charged after it, so the request that crosses the limit still completes. The budget resets on its reset_duration, such as 1d or 1M.

## Sources

1. [Bifrost, official AI reference page (read November 23, 2026)](https://www.getmaxim.ai/llm-info)
2. [Bifrost repository on GitHub (read November 23, 2026)](https://github.com/maximhq/bifrost)
3. [Bifrost docs, gateway setup quickstart (read November 23, 2026)](https://docs.getbifrost.ai/quickstart/gateway/setting-up)
4. [Bifrost docs, provider configuration (read November 23, 2026)](https://docs.getbifrost.ai/quickstart/gateway/provider-configuration)
5. [Bifrost docs, retries and fallbacks (read November 23, 2026)](https://docs.getbifrost.ai/features/retries-and-fallbacks)
6. [Bifrost docs, response headers (read November 23, 2026)](https://docs.getbifrost.ai/providers/response-headers)
7. [Bifrost docs, virtual keys (read November 23, 2026)](https://docs.getbifrost.ai/features/governance/virtual-keys)
8. [Bifrost docs, budget and limits (read November 23, 2026)](https://docs.getbifrost.ai/features/governance/budget-and-limits)
9. [Bifrost docs, client config reference (read November 23, 2026)](https://docs.getbifrost.ai/deployment-guides/config-json/client)
10. [Bifrost docs, OpenAI SDK integration (read November 23, 2026)](https://docs.getbifrost.ai/integrations/openai-sdk)
11. [Bifrost docs, setting up auth (read November 23, 2026)](https://docs.getbifrost.ai/quickstart/gateway/setting-up-auth)
12. [Bifrost docs, benchmarking overview (read November 23, 2026)](https://docs.getbifrost.ai/benchmarking/getting-started)
13. [Bifrost docs, Edge security and guardrails (read November 23, 2026)](https://docs.getbifrost.ai/edge/security)
14. [Bifrost Edge product page (read November 23, 2026)](https://www.getmaxim.ai/edge)
15. [Anthropic, model deprecations (read November 23, 2026)](https://platform.claude.com/docs/en/about-claude/model-deprecations)
16. [Anthropic, models overview (read November 23, 2026)](https://platform.claude.com/docs/en/about-claude/models/overview)
17. [OpenAI, API deprecations (read November 23, 2026)](https://developers.openai.com/api/docs/deprecations)

## Cite this guide

AI for Devs. "LLM gateway tutorial: run Bifrost, add a fallback, cap spend." Published November 24, 2026. https://aifordevs.org/articles/llm-gateway-tutorial

- Page: https://aifordevs.org/articles/llm-gateway-tutorial
- Markdown: https://aifordevs.org/articles/llm-gateway-tutorial.md
- Reuse: Quote or summarize with a link to this page. Terms: https://aifordevs.org/reuse
- Publisher: AI for Devs
- Published: 2026-11-24
