- 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
fallbacksarray in the request body. When the primary fails after its retries, Bifrost tries each entry in order and marks the answer withis_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 usesclaude-haiku-5-5instead.
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, an open-source AI gateway 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.
| 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. For the case for routing everything through one interface, see what a unified AI API buys you. For how Bifrost compares with other gateways, see the LLM gateway ranking.
#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.
- Node.js for
npx, or Docker. - An OpenAI API key and an Anthropic API key.
curl, plus Python with theopenaipackage 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 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 as of November 23, 2026.
gpt-4o-mini still works, but OpenAI's deprecations page lists it as deprecated, with shutdown on January 14, 2027. Swap in any model your keys can reach. The API pricing guides 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.
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/bifrostThe setup quickstart 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.
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 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.
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 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.
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 shows it like this, from the docs' own sample with a different model:
"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 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:
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.
#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:
"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.
#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.
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 has three details that decide whether this body works:
key_idsgoes inside eachprovider_configsentry.["*"]allows every key for that provider. An empty or missingkey_idsdenies all keys, so the virtual key reaches nothing.budgetsis always an array. The older singularbudgetfield is ignored.- 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 describes calendar-aligned resets in UTC as an option.
Send the key in the x-bf-vk header, or as Authorization: Bearer sk-bf-...:
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:
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.
The refusal is a 402. This sample is the docs' message for a $100 limit:
{
"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 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.
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:
- Pin a version. Use
npx -y @maximhq/bifrost --transport-version v2.4.0or themaximhq/bifrost:v2.4.0image instead of the latest tag. - Password-protect the dashboard. Set
BIFROST_SETUP_TOKENbefore start, for exampleexport 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 covers inference auth once dashboard auth is on. - Put TLS in front of it.
- Choose durable storage. Config and logs can move from SQLite to PostgreSQL 16 or later, and the database must use
UTF8encoding.
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 extends those same controls to each machine, with guardrails and policy enforced on the device. The shadow AI guide covers that side.
On cost, the gateway overhead is small next to model time. The Bifrost team's benchmarks 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 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:
- Move the provider and virtual-key setup into
config.jsonso it lives in version control, and keepenv.references for every secret. - Give each app or team its own virtual key with its own budget, so one runaway loop cannot spend another team's money.
- Add a second key per provider and set
max_retries, so a429rotates keys before it reaches a fallback. - Replace the typo test in Step 4 with real fault injection, as in failover testing, and confirm
is_fallbackin your logs. - Handle every
typein the refusal table in client code, and alert on502 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 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.