LLM gateway: token and spend management¶
A ready-to-run LiteLLM Proxy set-up that puts one endpoint in front of Anthropic, OpenAI, Gemini and local Ollama models. It records tokens and cost for every call, enforces budgets per key, user and team, and produces spend reports. It is optional: the app and agents run without it. Background, and the comparison with other tools, is in background.md.
Tested on 11 November 2026 with LiteLLM v1.109.0, Postgres 16, Prometheus 3.5 and Grafana 12.1 (see What was tested). The image is now pinned to v1.110.2, and CI runs the smoke test against that image.
deploy/llm-gateway/
├── compose.yaml gateway + Postgres (+ Prometheus/Alertmanager/Grafana with --profile monitoring)
├── compose.test.yaml test overlay: fake provider, no real keys needed
├── config.yaml models (Claude, OpenAI, Gemini, Ollama) and the limits on spend
├── dd_token_guard.py limits on one request's output and prompt size, loaded by the config
├── background.md why LiteLLM, and how it compares with other tools
├── config.test.yaml fake models and small limits used by the smoke test
├── .env.example copy to .env and fill in
├── monitoring/
│ ├── prometheus.yml
│ ├── alerts.yml spend alerts: budgets nearly used or out, spend spikes
│ └── alertmanager.yml where the alerts go (nowhere until you add a receiver)
└── scripts/
├── admin.py teams, users, keys, spend reports, CSV export (stdlib only)
├── smoke_test.sh end-to-end test of tracking, tags, budgets and metrics
├── systemd.sh starts and stops it on a VM (data-director-llm-gateway.service)
└── testing/
├── fake_upstream.py the fake provider the test stack uses
├── ci_env.sh a throwaway .env for the test stack
└── broker_e2e.sh the model broker's calls through the test stack
Quick start¶
Requirements: Docker with Compose v2+, and Python 3.9+ for admin.py.
-
Create
.envwith fresh secrets:Then editcp .env.example .env.env. Generate eachsk-secret withecho "sk-$(openssl rand -hex 32)"and add the provider keys you have. -
Look at
config.yaml, and delete any providers you don't use. It serves Claude models by name and OpenAI and Gemini models by pattern (gpt-*,gemini-*); see Model names. -
Start the gateway:
docker compose up -d -
Check it's running:
curl http://localhost:4000/health/liveliness -
Open the admin UI at http://localhost:4000/ui. Log in as
admin, with yourLITELLM_MASTER_KEYas the password.
Point code at the gateway with a virtual key, never a provider key. Using the OpenAI SDK (works for every model in config.yaml):
from openai import OpenAI
client = OpenAI(base_url="http://localhost:4000", api_key="sk-<virtual key>")
client.chat.completions.create(
model="claude-sonnet-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
extra_body={"metadata": {"tags": ["experiment:ablation-2"]}}, # optional per-request tags
)
Using the Anthropic SDK (/v1/messages):
import anthropic
client = anthropic.Anthropic(base_url="http://localhost:4000", api_key="sk-<virtual key>")
client.messages.create(
model="claude-sonnet-5-5", max_tokens=1024, messages=[{"role": "user", "content": "Hello"}]
)
For existing code, setting OPENAI_BASE_URL / ANTHROPIC_BASE_URL and the API key environment variables is often enough.
On a Data Director VM¶
On a VM set up with deploy/install.sh, run it again with --gateway. It installs Docker, runs this
gateway under systemd with its secrets in /etc/data-director/credentials/llm-gateway/, and gives
the model broker a key for it (deploy/README.md). The steps
below are for running it by hand, or for pointing agents at it.
The gateway's Docker network has a fixed subnet, 10.201.0.0/24 unless DD_GATEWAY_SUBNET says
otherwise (in /etc/data-director/llm-gateway.env on a VM, or .env by hand). Docker's own
default would be 172.18.0.0/16 on a host that already has docker0, which is a University's
Wi-Fi range: the host would route replies for those clients to the Docker bridge and they could
not connect. Choose a block that no campus network uses. install.sh also sets Docker's default
address pools in /etc/docker/daemon.json, if that file does not exist. A changed subnet takes
effect when the gateway is started again, which recreates the network and keeps the database's
volume.
Model names¶
A client's model must match a model_name in config.yaml, or the gateway refuses the call. The
entries use the providers' own model IDs, so an agent keeps its DD_MODEL_ID when its calls go
through the gateway, whether directly or through the model broker:
- Claude:
claude-sonnet-5-5andclaude-haiku-5-5, by name. - OpenAI: any model whose ID starts
gpt-, through the patterngpt-*. A model outside that family needs an entry of its own. - Gemini: any model whose ID starts
gemini-, through the patterngemini-*.
A pattern is not listed by /v1/models, but serves and costs each model it matches. A key's
--models may name a pattern too: --models 'gemini-*' allows every Gemini model and nothing
else.
Using it with Data Director agents¶
The agents create their Anthropic client with only an API key (dd_sdk.credentials), so the
Anthropic SDK takes its base URL from ANTHROPIC_BASE_URL. An agent moves to the gateway with no
code change:
- Create a gateway key for the agent, so its spend is reported and limited on its own:
scripts/admin.py key create advisor-standards --team <team_id> --budget 20 --period 30d \ --models claude-sonnet-5-5 --tags agent:advisor-standards - On the VM, give the agent that key in place of the provider key (it arrives as
ANTHROPIC_API_KEY_FILE, as before; deploy/README.md, "Secrets"):sudo data-director secret set advisor-standards anthropic-api-key # paste the gateway key - Point the agent at the gateway in its local environment file, then restart it:
echo 'ANTHROPIC_BASE_URL=http://127.0.0.1:4000' | sudo tee -a /etc/data-director/agents/advisor-standards.env
The provider key then lives only in the gateway's .env. This gives each agent a spending limit
of its own; without the gateway, limits are set per provider workspace
(Policy and identity, "Key hygiene"). The gateway listens
on 127.0.0.1:4000, which is clear of the app (7860), the workbench (8000) and the agents
(8101–8117).
With the model broker¶
When a profile lets people use their own AI accounts, agents call the
model broker and no longer hold a provider key or a
gateway key. The broker then pays for the deployment's calls as well. Give the gateway
key to the broker instead of to each agent, and point it at the gateway with
DD_BROKER_DEPLOYMENT_BASE_URL=http://127.0.0.1:4000. Make that one key with a tag such as
--tags service:model-broker. The gateway's budgets and spend reports keep covering the
deployment's calls. Every call arrives on that one key, so the broker tags each with the agent
that made it (agent:<name>, in the x-litellm-tags header), and scripts/admin.py spend --by
tag shows the deployment's spend by agent. A tag names the agent, never the person: who made a
call is in the broker's own usage store, by pseudonym.
A call paid for by a person's own account goes from the broker straight to their provider. It never passes through the gateway, which would otherwise see their key. The gateway's spend reports therefore show only what the deployment pays for.
The admin service's Spend page¶
The deployment's admin service (docs/guide/operations/admin.md)
shows this gateway's spend for the month and the last 30 days, by day, model and key, beside the
tokens each run recorded, priced at the gateway's prices, by agent, person and project. Its LLM
gateway page shows, with the same key, whether the gateway is ready, its models and their prices,
and each key, team and user with its spend against its budget (/health/readiness,
/model/info, /key/list, /team/list, /user/list). It needs a read-only key: the proxy_admin_viewer role, with a budget of 0, so it can make no model call.
- Create the key (this writes it to
monitoring/litellm_key):scripts/admin.py metrics-key --user-id dd-admin - On the VM, install it where only root can read it, then remove the copy:
sudo install -d -m 0700 /etc/data-director/credentials/adminsudo install -m 0600 monitoring/litellm_key /etc/data-director/credentials/admin/litellm-keyrm monitoring/litellm_key - Have systemd pass it to the admin service, which reads it from its credentials directory:
and add
sudo systemctl edit data-director-admin[Service] LoadCredential=litellm-key:/etc/data-director/credentials/admin/litellm-key - Name the gateway, and a monthly budget to show spend against if you want one, in
/etc/data-director/admin.env, then restart the service:printf 'DD_ADMIN_LITELLM_URL=http://127.0.0.1:4000\nDD_ADMIN_MONTHLY_BUDGET=200\n' | sudo tee -a /etc/data-director/admin.envsudo systemctl restart data-director-admin
The page's budget is shown, not enforced; the budgets that stop calls are the gateway's own.
Day-to-day admin¶
scripts/admin.py reads LITELLM_MASTER_KEY from .env, and LITELLM_URL (default http://localhost:4000) from the environment.
Create a team for a group or grant, with a monthly budget:
scripts/admin.py team create nlp-lab --budget 200 --period 30d
Create a user in that team (prints a user_id):
scripts/admin.py user create someone@example.ac.uk --team <team_id> --budget 50 --period 30d
Create a key for one project; the tags are added to every request made with it:
scripts/admin.py key create thesis-ch3 --team <team_id> --user <user_id> \
--budget 25 --period 30d --models 'claude-sonnet-5-5,gemini-*' --tags project:thesis,grant:EP-X-1
Check spend against budget for a key, a team, or all teams:
scripts/admin.py key info sk-...
scripts/admin.py team info <team_id>
scripts/admin.py team list
See this month's spend grouped by team, or by tag, user, key, model or day:
scripts/admin.py spend --by team
See spend by tag for a date range:
scripts/admin.py spend --by tag --start 2026-10-01 --end 2026-10-31
Export the request logs to CSV:
scripts/admin.py export --start 2026-10-01 --end 2026-10-31 --out oct.csv
Attribution tips
- One key per project or grant, inside a team per group, gives clean attribution and enforceable budgets on the free tier.
- Tags give finer slicing (experiments, tasks) for reporting. admin.py spend --by tag aggregates them from the request logs, so you don't need the Enterprise-only /global/spend/report. A request with several tags counts towards each one.
- Don't rely on the OpenAI user field for accountability, because callers can set it to anything. Attach --user to the key instead.
How budgets behave (tested)¶
- Before each request, the gateway checks the spend already recorded against every budget that applies (key, user, team). If any is used up, the request gets an error with
"type": "budget_exceeded"(HTTP 422 in this version), naming the key or team. - The request that crosses a limit is still allowed. Budgets can therefore be exceeded by about one request's cost, or by more if several requests are in flight at once. Leave some headroom, and set
max_tokenson requests to bound the cost of each one. - Budgets with
--periodreset automatically (e.g.30d). - Spend reaches the database in batches, so
key infoandteam infocan lag by up to about a minute. Enforcement uses the live in-memory figure.
Protections against runaway usage¶
A budget stops spending after the fact, so the gateway has several layers, each bounding a different way a call or a loop can run away. The figures are in config.yaml, and are placeholders to change to suit the deployment.
| Layer | What it bounds | Where | Limit shipped |
|---|---|---|---|
| Output size of one call | A caller that sets no max_tokens can no longer ask for a model's whole output window; one that asks for too much is refused (HTTP 400). |
dd_token_guard.py, general_settings.dd_token_guard |
Default 4096, ceiling 32000 |
| Prompt size of one call | A prompt over the limit is refused (HTTP 413). Characters stand in for tokens, at about four to one. | The same | 1,000,000 characters |
| Key defaults | A key created without a limit gets these, so no key is unlimited by accident. | default_key_generate_params |
$25 per 30 days, 200,000 tokens and 60 requests a minute, 5 calls at once |
| Key ceilings | The most any key may be given, by admin.py, the admin UI or the API. |
upperbound_key_generate_params |
$100 per 30 days, 1,000,000 tokens and 300 requests a minute, 20 calls at once |
Creation by admin.py |
A team, user or key needs --budget and --period (a key needs --models too), or a deliberate --unlimited. |
scripts/admin.py |
|
| Calls in flight | A backstop on every key together, because budgets are checked before a call and can be overshot by those in flight. | global_max_parallel_requests |
50 |
| Whole-gateway budget | Every call is refused once the gateway as a whole has spent this much in the period. | max_budget, budget_duration |
$400 per 30 days |
| Timeouts and retries | A call is dropped after two minutes, and a failed call is retried once, because a retry is billed like the call it repeats. | request_timeout, num_retries |
120 s, 1 retry |
| Alerts | A key or team with under 20% of its budget left, a key out of budget, and spend over $20 an hour, or $10 an hour for one key. | monitoring/alerts.yml |
|
| Provider limits | The last backstop, outside the gateway: a spend limit on the provider's workspace or project, for the gateway's own provider keys. | The provider's console | Set it by hand |
The agents also set max_tokens on every call (dd_sdk.model defaults to 4096, and the orchestrator asks for at most 16000), so the guard is a floor under callers that do not.
What this does not cover:
- Keys that already exist. The defaults and ceilings apply when a key is created. Look through the admin UI's Virtual Keys page for keys with no budget, and give each one.
- Teams and users made outside
admin.py. The ceilings are for keys only; the admin UI and API can still make a team without a budget. The whole-gateway budget bounds them. - The whole-gateway budget refuses everyone at once, the model broker's calls included, until the period resets. Set it above what the deployment spends in a period, not at it. Raise it in
config.yamland restart. - Prompt size is approximate. It is counted in characters, so a prompt of unusually short words, or one that carries images, can pass or fail by a wide margin. A model's own context window is the hard bound.
- LiteLLM's
max_request_size_mbandmax_response_size_mbare not used. The proxy ignores them without an Enterprise licence. - Per-model rate limits (
rpmandtpmunderlitellm_params) are not set: LiteLLM uses them to choose between deployments of a model, and they have not been tested as a hard stop. The limits on the key are. - The model broker's key (
deploy/install.sh --gateway) is made at the ceiling for rates and with $100 per 30 days, because it pays for the whole deployment's calls. If the deployment spends more than that, raiseupperbound_key_generate_params.max_budgetand the key's own budget.
A deployment that runs its own gateway configuration (DD_GATEWAY_CONFIG) needs the same settings and the dd_token_guard.proxy_handler_instance callback in it: the guard loads only if the configuration names it.
Monitoring (optional)¶
Create a read-only key for Prometheus. This writes monitoring/litellm_key, which is git-ignored and world-readable so the Prometheus container can read it:
scripts/admin.py metrics-key
Then start the monitoring stack:
docker compose --profile monitoring up -d
- Prometheus is at http://localhost:9090. Useful queries:
sum by (team_alias) (litellm_spend_metric_total),litellm_remaining_team_budget_metricandlitellm_remaining_api_key_budget_metric. - Grafana is at http://localhost:3000 (first login
admin/admin). Add Prometheus as a data source with URLhttp://prometheus:9090. - Budget gauges for every team and key are refreshed every 5 minutes (
prometheus_initialize_budget_metricsinconfig.yaml). - The spend alerts in
monitoring/alerts.ymlload into Prometheus (http://localhost:9090/alerts) and go to Alertmanager (http://localhost:9093). Alertmanager sends them nowhere until you add a receiver tomonitoring/alertmanager.yml, which has an email example. The two dollar thresholds for spend per hour are placeholders: set them to suit. - LiteLLM's own email alerts are an Enterprise feature.
- The admin service's Monitoring page links to all three and lists the alerts Prometheus and Alertmanager hold, once
DD_ADMIN_PROMETHEUS_URLandDD_ADMIN_ALERTMANAGER_URLname them (the admin guide).
Optional: Langfuse tracing¶
Run Langfuse yourself using its Docker Compose guide, or use Langfuse Cloud. Set LANGFUSE_* in .env, uncomment success_callback: ["langfuse"] in config.yaml, then:
docker compose up -d
Testing without provider keys¶
CI runs these steps on every change to the gateway, the model broker or the workflows (the
"LiteLLM gateway and model broker" job in .github/workflows/ci.yml), so a gateway or broker that
no longer works together never reaches a deployment.
Without a .env, write one with throwaway secrets and no provider keys:
scripts/testing/ci_env.sh
Start the test stack. It uses config.test.yaml and a fake provider, so nothing is billed:
docker compose -f compose.yaml -f compose.test.yaml up -d
Run the test:
scripts/smoke_test.sh
Send the model broker's deployment-paid calls, in the Anthropic and OpenAI formats, through the
gateway, and check that the gateway costs them to the broker's key. This needs uv and a clone of
the whole repository:
scripts/testing/broker_e2e.sh
Tear it down; -v deletes the test database:
docker compose -f compose.yaml -f compose.test.yaml down -v
What was tested¶
smoke_test.sh passed 19/19 checks (on a fresh database and on a repeat run):
- the gateway, admin UI, team, user and key creation;
- calls through both the OpenAI (/v1/chat/completions) and Anthropic (/v1/messages) routes, costed correctly;
- the key budget and the team budget, both blocking further calls (spend stopped within one request of each limit);
- spend persisted per key and per team;
- tag totals for key-level and per-request tags;
- CSV export;
- Prometheus spend metrics.
Separately confirmed:
- an Anthropic SDK client built the way the agents build it (anthropic.Anthropic(api_key=...)),
with only ANTHROPIC_BASE_URL set, reaches claude-sonnet-5-5 through the gateway. Its spend is
attributed to the key's tag, and a model outside the key's allow-list is refused (HTTP 403);
- the real config.yaml loads all five models;
- Prometheus scrapes the gateway with the read-only key;
- Grafana starts.
The checks of the limits on one request and one key (section 8 of smoke_test.sh), and the alert rules and Alertmanager, were added after that run. scripts/tests/test_llm_gateway_config.py tests the guard and the shipped settings without Docker.
Not tested here: real provider calls (no API keys were available), Ollama, Langfuse, and running behind a reverse proxy.
LiteLLM's built-in mock_response option records $0 cost on the Anthropic route, which is why the test uses a fake provider instead.
Production notes¶
- Exposure: ports are bound to
127.0.0.1. To share the gateway with colleagues, put it behind an HTTPS reverse proxy (e.g. Caddy or nginx) on a campus network or VPN. Don't expose port 4000 directly. - Secrets: keep
LITELLM_SALT_KEYstable and backed up. Changing it makes the provider keys stored in the database unreadable. - Back-ups: on a Data Director VM, the nightly backup dumps the gateway's database and
restoreputs it back (deploy/README.md). Run by hand, back up thepgdatavolume, which holds keys, budgets and spend history. For example:docker compose exec db pg_dump -U litellm litellm > backup.sql - Privacy:
turn_off_message_logging: truekeeps prompt and response text out of the spend logs. Decide on log retention in line with GDPR and any ethics approvals. - Prices: LiteLLM costs requests using its built-in price list. At start-up it also tries to download the latest list from GitHub, and falls back to the built-in copy if that fails. Set
LITELLM_LOCAL_MODEL_COST_MAP=Truein.envto always use the version shipped with the image. For new or negotiated prices, setinput_cost_per_token/output_cost_per_tokenundermodel_infoinconfig.yaml. - Reconciliation: the gateway's figures are estimates. Check them monthly against each provider's own usage and cost reports (see the guide). Giving the gateway its own provider keys or workspace makes this one-to-one.
- Large exports:
/spend/logs/v2returns at most 10,000 rows per query, so use shorter date ranges, or query Postgres directly (table"LiteLLM_SpendLogs"). - Upgrades: the image is pinned to
v1.110.2. Read the release notes before bumping it, then re-run the smoke test. The limits above use LiteLLM settings that change between releases (upperbound_key_generate_params,default_key_generate_params,global_max_parallel_requests, and the hook thatdd_token_guard.pyimplements), so check each of them in the notes.