One key, many models, and a budget that actually holds
7 lessons2026-08-13AI-generated
1Overview
A proxy that speaks one API to your applications and many APIs to providers, adding auth, budgets, routing, failover and logging in between.
The EU-sovereign inference chapter answers whose GPUs run your tokens. This one answers what happens to a request on the way there: which model it lands on, whose budget it spends, what happens when that provider is down, and whether anyone can reconstruct it afterwards. → A gateway is the single most useful piece of infrastructure for an organisation with more than one AI project, and it is one container. → It is also where the governance policy you wrote in an earlier chapter stops being a document and becomes a rule that returns HTTP 429.
One endpoint in front of every model you use — local, EU-hosted, frontier — with per-key budgets, provider failover and a log of every token. It is the layer where "we have a policy about AI spending" becomes a 429 instead of a memo.
→Put one OpenAI-compatible endpoint in front of several model providers
→Enforce a per-team or per-key budget that fails the request instead of the invoice
→Fail over between providers without changing application code
→Log every request so a cost spike can be traced to a caller
→Route by task: cheap model for bulk, expensive model for judgment
→Decide when a gateway is worth its operational weight and when it is not
1.3When to reach for it
Two or more projects, or two or more providers. One app talking to one provider does not need this.
1.4Key parts
Virtual keys per team, a spend ceiling per key, a routing policy, a fallback chain, and a request log with token counts.
1.5Free vs paid
Both anchors are open source and self-hostable; both also sell a managed tier. Self-hosted costs one small container and a database.
1.6Watch out
A gateway is on the critical path of every AI call you make. Budget for its failure modes before you route production through it.
2Lessons 7
2.1Route all LLM calls through a single OpenAI‑compatible endpoint
The LiteLLM proxy (or openziti llm‑gateway) provides an OpenAI‑compatible /v1/chat/completionsendpoint that forwards requests to configured providers.
Run a gateway exposing one /v1/chat/completionsURL and forward calls to multiple model backends
Create a config.yaml file listing each provider’s API key and base_url
Start the gateway with llm-gateway run config.yaml (or litellm --config config.yaml)
Send a request to http://localhost:8080/v1/chat/completions using any OpenAI‑compatible client
You'll see The client receives a normal response even though the request was routed through the local gateway to different providers
Takeaway A single endpoint lets every application talk to many models without changing code
Check How does routing all LLM calls through one OpenAI‑compatible /v1/chat/completionsendpoint simplify integration with multiple model providers?
Cost Free and open source to self-host; both projects also sell a managed tier. Self-hosting costs one small container and, for LiteLLM, a database for key and spend state.
2.2Create a virtual key with a hard spend limit
A virtual key is an APItoken generated for a team that includes a max_budget enforcing a hard spending ceiling.
Generate a virtual key for a team and set a maximum budget that returns an error once the limit is reached
Open Terminal and run a curl command to POST to /key/generate on the LiteLLM admin endpoint, including your master‑key in the Authorization: Bearer header and a JSON body with {"models": ["gpt-4"], "max_budget": 50}
Verify that the response contains a new virtual key identifier and that it is stored in the proxy’s LiteLLM_VerificationTokenTable backed by Postgres
Make an API call using the newly created virtual key; when the cumulative spend exceeds the max_budget, observe an HTTP 400 error with the message Authentication Error, ExceededTokenBudget…
If using Bifrost, open the Web UI, navigate to Virtual Keys → Add Virtual Key, set the budget amount and reset period, assign the key to a team, and save
You'll see The application receives a normal response on the first request and an HTTP 400 ExceededTokenBudget error on the request that exceeds the key’s budget
Takeaway A virtual key separates caller identity from the provider key and enforces spend limits instantly via error responses
Check What response does the gateway return when the cumulative spend of a virtual key exceeds its defined max_budget?
Cost Free — budgeting is a core feature of both open-source proxies, not a paid add-on. The cost is operational: someone has to decide the ceilings and update them as teams grow.
2.3Switch to another LLM provider automatically
The fallback chain maps a primary model to an ordered list of alternate models used when the primary fails.
Declare a fallback chain so a provider outage or rate‑limit becomes a slower response instead of a failed one, with zero changes on the calling side.
Open config.yaml in your favourite editor.
Add a fallbacks entry under litellm_settings, mapping the primary model to an ordered list of alternates, e.g. fallbacks: [{"gpt-4": ["claude-opus", "local-llama"]}].
Optionally configure content_policy_fallbacks, context_window_fallbacks and default_fallbacks for specific failure types.
Set num_retries and cooldown_time in the same file to control how many attempts are made before moving on and how long a failing model is skipped.
You'll see A request against a deliberately down provider still returns a normal 200 response with an answer because the gateway used the next entry in the fallback chain.
Takeaway A fallback chain in LiteLLM’s config or Bifrost’s weighted pool turns a provider outage into a slower answer without changing application code, provided the alternate models are acceptable substitutes
Check How does configuring a fallback chain in LiteLLM’s config change the behaviour of requests when the primary model is unavailable?
Cost Free — fallback routing is core proxy behavior in both projects. The real cost is a slower response on the failover path (extra retry + a second provider round-trip) and, if the fallback model is weaker, a quality gap nobody flagged.
2.4Find the exact caller behind a cost spike
The Logs UI provides controls such as Date filter, Key column with Group by key, and Model column with Group by model to trace spend.
Pinpoint which API key, team and model caused an unexpected increase in spend using the gateway’s request log
Open the LogsUI from the gateway dashboard
Set the date range to cover the period of the spike using the Date filter control
Add a Key column and select Group by key to see spend per API key
Add a Model column and enable Group by model to break down cost by model
If needed, toggle Store Prompts in Spend Logs under Settings to include prompt content for deeper analysis
You'll see A spend chart showing a sudden rise and a filtered request list that isolates the responsible key and model within a few clicks
Takeaway The gateway logs attach caller identity to every request, turning anonymous provider totals into traceable spend data
Check Which controls in the Logs UI let you isolate the specific API key and model responsible for a sudden cost spike?
Cost Free — logging spend metadata is core to both proxies. Storing full prompt/response content is a real storage cost and a privacy decision, which is exactly why LiteLLM makes it an explicit opt-in rather than the default.
2.5Send bulk calls to a cheap model and judgment calls to an expensive model
Model groups like bulk-classify and judgment-review are named mappings that the gateway resolves to specific underlying models.
Route high‑volume tasks to a low‑cost model while reserving the frontier model for judgement‑heavy requests without changing application code
Open config.yaml in the LiteLLM gateway directory
Add a group named bulk-classify that maps to a cheap, high‑throughput model (or local open‑weight model)
Add a group named judgment-review that maps to the frontier model you want for judgement tasks
Save config.yaml and restart the LiteLLM gateway service
You'll see Two identical request blocks – one with model: "bulk-classify" and one with model: "judgment-review" – are resolved by the gateway to different real models and show different per‑call costs
Takeaway Name model groups by task so the gateway can swap underlying models without touching call sites
Check How do the named model groups bulk-classify and judgment-review determine which underlying model processes each request?
Cost No direct cost — this is a config decision on top of infrastructure you already stood up in the first lesson. The savings come from routing volume away from the model that was never needed for it.
2.6Plan for gateway failures
Deploying multiple gateway instances behind a load balancer with datastore backups ensures high availability.
Define an availability strategy for the AI gateway before routing production traffic through it
Identify the failure scenarios that could affect the gateway process and its database
Deploy multiple gateway instances behind a load balancer to eliminate a single‑container SPOF
Configure backups and automated restart for the gateway’s datastore (Postgres, SQLite or ClickHouse)
Document an on‑call rotation specifically for gateway incidents, separate from provider account owners
You'll see All applications report AI call errors simultaneously, indicating a gateway outage rather than a single‑provider failure
Takeaway A central gateway is a single point of failure, so its redundancy, backup and ownership must be treated with the same rigour as any downstream provider
Check What architectural measure prevents a single gateway instance from becoming a point of failure for production traffic?
Cost No new tool — this is an operational commitment (a second instance, a monitored database, an on-call owner) layered on infrastructure you already run. Skipping it costs nothing until the day it costs everything downstream of the gateway at once.
2.7Decide if your organisation needs an LLM gateway
The decision framework evaluates whether you have two or more projects or providers before justifying a gateway.
Make a concrete decision about deploying a gateway using the two‑or‑more projects or providers threshold
Review the list of problems a gateway solves – single endpoint, spend ceiling, fallback chain, traceable logs and routing rules – and note which of these currently exist in your stack.
Compare the number of projects and providers you are using against the threshold of two or more for each; if either count is below two, the gateway adds extra service overhead.
Identify any real‑world symptoms such as unallocated spend, rate‑limiting collisions, or unenforceable governance policies that indicate you have crossed the threshold.
Choose to stand up a self‑hosted gateway only if those symptoms are present, otherwise keep the infrastructure at zero.
You'll see A single application talking to a single provider with no virtual keys, fallback chain or gateway in front of it
Takeaway A gateway is justified only when you have two or more projects or two or more providers, otherwise it adds unnecessary complexity and a new point of failure
Check According to the decision framework, what threshold must be met before it is justified to stand up an LLM gateway?
Cost Choosing not to deploy a gateway costs nothing today. The cost of deploying one too early is the same operational weight named in the previous lesson, carried for governance nobody is exercising yet.
3You’ll know it worked 30 checkable outcomes in this chapter
✓Send a finance‑related query and see it hit OpenAI GPT‑4; send a coding query and see it go to Gemini
✓Disable the primary provider (e.g., block OpenAI endpoint) and observe that requests are fulfilled by the fallback model (e.g., Gemini)
✓curl http://localhost:8080 returns a 200 response (or model output) instead of connection refused
✓When the primary API key is invalid, the response comes from a fallback model
✓Log shows alternating `deployment_id`s or key identifiers across consecutive calls
✓Dashboard displays non‑zero usage numbers that match known test calls from each team
✓Visiting the instance URL shows the LiteLLM dashboard login page
✓The Usage page lists requests, models used, tokens consumed, and dollar cost; totals match the provider billing statements
30 outcomes in all — one per recipe below.
4FAQ, Tips & How-to 30
one problem, one solution, one action
▸How-toEveryone
Finance or coding queries go to the right AI model
Semantic routing lets you define topics with example utterances and map each topic to a specific LLM model. When a request arrives, the gateway matches the prompt against the topics and forwards it to the mapped provider, ensuring cost‑effective and accurate responses.
The gateway exposes a single HTTPendpoint that abstracts away individual API keys and URLs for each LLM provider. Developers authenticate once, and the gateway handles authentication to the underlying models, providing high availability via automatic fallback.
A token‑rate‑limit policy lets you set maximum tokens per time window for each client or business group. The gateway tracks usage and rejects requests that would exceed the limit, turning budget overruns into HTTP 429 errors.
If the primary model for a topic cannot be reached, the gateway can automatically route the request to a secondary model defined in the fallback configuration, ensuring uninterrupted service.
Want to use different AI models for each client region
Header‑based routing lets you route requests based on custom HTTP headers such as region or client ID. This enables scenarios like EU‑specific models for compliance or per‑customer model selection.
Want to connect a new language model to your gateway
An Agent Gateway backend is a custom Kubernetes resource that represents an LLM provider (e.g., Gemini, Anthropic). By creating a secret with the API key and applying a Backend CRD, the gateway can route requests to that model without changing application code.
Agent Gateway’s HTTPRoute can contain multiple rules, each matching a URL prefix and rewriting it before forwarding to a chosen backend. This lets one endpoint serve many models (e.g., /ai/gemini → Gemini, /ai/claude → Anthropic).
When using a local Kind cluster without an external load balancer, `kubectl port-forward` can forward the gateway service’s port to localhost, allowing curl or client apps to reach the gateway as if it were a public endpoint.
Need an API gateway running in my Kubernetes cluster
Agent Gateway provides two Helm charts: one for its custom resource definitions (CRDs) and another for the control‑plane deployment. Installing both sets up the gateway API objects and the data‑plane proxy in a Kubernetes cluster.
A GatewayClass resource defines the type of gateway (e.g., Agent Gateway) that can be instantiated in the cluster. By creating a specific class, you enforce policy such as replica count or load‑balancer type for all Agent Gateways.
The `completion` function from LiteLLM abstracts away provider-specific SDKs. By passing the model name and a standard message payload, you can call OpenAI, Anthropic, Google Gemini, Grok, etc., with identical code.
LiteLLM’s `fallbacks` parameter lets you list secondary models. If the primary model raises an error (e.g., 403 or timeout), LiteLLM automatically retries with the next model, ensuring uninterrupted service.
LiteLLM maintains a pricing database and provides `completion_cost` which returns input tokens, output tokens, and monetary cost for the request, enabling per‑team budgeting.
Enabling `cache=True` with `cache_type="local"` stores request/response pairs in RAM. Subsequent identical prompts hit the cache instantly, saving latency and token cost.
Using LiteLLM’s `router` you map abstract task names (e.g., "fast", "code") to concrete provider configurations. The router selects the appropriate model at runtime based on the task label.
Define several entries for the same provider with different API keys; LiteLLM’s `simple_shuffle` strategy rotates requests, automatically avoiding rate‑limit errors and balancing load.
Want one simple spot for all LLM calls in your chain
LangChain provides `ChatLiteLLM` wrapper that accepts the same config as LiteLLM. You can build a prompt template, chain it with other components, and still benefit from routing, fallbacks, cost tracking, etc.
The AI Gateway acts as a reverse proxy that presents one APIendpoint to all applications, handling request transformation and routing to any configured LLM provider. This removes hard‑coded model URLs and SDK differences, simplifying integration.
The gateway records token counts for every request, tagging them with the originating application or team. This visibility lets finance and engineering pinpoint budget hotspots and enforce spend limits.
By inspecting request payloads (e.g., length, complexity) the gateway can route cheap queries to a low‑cost LLM and send demanding ones to an expensive, high‑performance model, reducing overall spend while preserving quality where needed.
The gateway can enforce API‑key validation, PII masking, and access control before any request reaches an LLM, turning governance documents into enforced runtime rules that return HTTP 429 when limits are exceeded.
Because applications talk only to the gateway, changing the underlying LLM provider is a configuration update in the gateway rather than a code rewrite across multiple services.
LiteLLM acts as a single proxy that normalizes API calls across providers, letting you route requests through one endpoint. Installing it (self‑hosted or via Elestio) gives you immediate control over all your keys and models.
Within LiteLLM you register each provider as a “model” with its own credentials. The gateway then forwards calls to the correct upstream API based on the model selected in the request.
Need to cap a dev team’s monthly budget and request speed
Teams group users and can be assigned spending caps (daily/weekly/monthly) and token‑rate limits. This enforces governance policies automatically, returning HTTP 429 when a limit is exceeded.
Virtual keys are scoped to a team and optionally to specific models, letting you hand out credentials without exposing real provider keys. They inherit the team’s budget and rate limits.
The built‑in analytics tab logs every request with model, token count, and cost. By filtering per team or key you can see which provider is cheaper for your workload and adjust routing accordingly.
A gateway sits between your app and external LLMAPIs, letting you decide per request which model to use based on task type or cost constraints. By configuring routing rules in the gateway, you can automatically send translation jobs to a specialized model and cheap chat to a smaller one.
The gateway can inspect each outgoing request, look up the cost of the target model, and reject or downgrade requests when a predefined budget is exceeded. This turns your governance policy into an enforceable rule that returns HTTP 429 when spending caps are hit.
By configuring secondary endpoints, the gateway can detect failed calls (timeouts, 5xx) and transparently retry the request against an alternative vendor or region, preserving uptime without code changes in the application.