Free lesson · Course 1

A key and a budget per agent.

Lesson 3.2 of AI Engineering Foundations, exactly as students get it: the screencast, the written lesson and the full code. No sign-up.

7 min 41 s · captions in the video, transcript below the lesson · narrated by an AI version of Charafeddine's voice, from his script.

Course 1 of 6 in the Engineering Series, which builds one AI platform in Python for Larkfield Supply, a fictional company. In the lesson, E1 to E6 are the six courses; you can skip mentions of other lessons on a first read. Reading needs no setup. To run the code, you need the course repository (tag e1-m3-l2) and lessons 2.2 to 2.4.

You'll leave with a pinned LiteLLM gateway with two aliases and a fallback, every agent declared in one reviewed file with its models, budget and rate limits, a script that issues (and rotates) each agent's key, and tests that prove the gateway enforces both.

In one screen

  • Use it on Monday: Give every agent its own gateway key with a model list and a budget, and set fallback_on_unsupported_params: false so a bad request is never answered by a cheaper model.
  • The picture: Application code names only aliases, and each agent gets a virtual key from a reviewed agents.yaml carrying its aliases, budget and rate limits, which the gateway checks on every call.
  • The decision: One key per agent, declared in a reviewed file and issued by a script, never by hand in the admin screen, with fallback_on_unsupported_params: false; when many teams run agents, add team budgets on top (E6 lesson 2.3).
  • You'll run: The step 5 call, Client().complete('smart', ...), on the support answerer's key: AuthFailed 403 with key_model_access_denied, and no retry.

Why this matters

On 12 November 2026, when I first ran the course platform on real models, it sent smart a parameter it doesn't support. The answer came back as a 200, from a cheaper model, and nothing in the code raised. By the end of this lesson the gateway refuses that, and it refuses any agent an alias or a budget it wasn't given.

Until this lesson, our one key could call any alias, with no budget and no rate limit. That's most teams' first month: one provider key, shared by every feature. The day one agent loops at 2 a.m., the whole company's quota goes with it, and the bill can't tell you which agent did it.

A gateway is the one proxy every model call goes through, and lesson 3.1 chose LiteLLM for it. This lesson makes it do the two things that justify it: application code that never names a vendor model, and a key per agent that the gateway enforces on every call.

The idea

Aliases (model_name in LiteLLM) are the names application code uses, fast and smart, each mapped to a pinned model in the gateway's config. Three config files map the same aliases (the stand-in, Claude, OpenAI), and application code can't tell which one is loaded. The same file holds the router (smart falls back to fast; the gateway doesn't retry, because the client does, lesson 2.4) and what the gateway logs.

Agents are declared in infra/gateway/agents.yaml, reviewed like code. A script turns each declaration into a virtual key: a gateway-issued key that carries its own limits. The file is the source of truth for what each agent may do; the gateway's Postgres is where it's enforced.

infra/gateway/agents.yaml  --(scripts/agent_key.py, master key, once)-->  /key/generate
                                                                            |
                                                          virtual key for "support-answerer"
                                                          models [fast], USD 5 per 30d, 60 rpm
                                                                            |
app (.env: AIP_GATEWAY_KEY) --> gateway checks key: alias allowed? under budget? under rpm/tpm?
                                --> alias "fast" --> pinned model --> spend row tagged with the key
infra/gateway/agents.yaml
   |  scripts/agent_key.py, master key, once
   v
/key/generate
   |
   v
virtual key for "support-answerer"
models [fast], USD 5 per 30d, 60 rpm

app (.env: AIP_GATEWAY_KEY)
   |
   v
gateway checks key:
  alias allowed? under budget?
  under rpm/tpm?
   |
   v
alias "fast" --> pinned model
   |
   v
spend row tagged with the key

Build it

We'll read the config that makes the aliases and the fallback, declare two agents, issue their keys, and then ask the gateway for something a key wasn't given. It says no, and nothing in the application had to check.

git checkout e1-m3-l2 && uv sync
cd infra/compose && docker compose up -d --wait --force-recreate sim gateway && cd ../..

Your .env still holds lesson 2.2's key, with no budget and both aliases. Step 4 replaces it.

Step 1: the gateway config

What to notice. The aliases (fast, smart) sit in model_list at the top of this file, each pointing at the stand-in; the excerpt below is the part that carries decisions. Read fallbacks and the line under it together: a failed smart call moves to fast, except when the request itself was wrong. num_retries: 0 is the one-retry-layer rule from lesson 2.4.

From infra/gateway/config.offline.yaml (whole file in Full code):

router_settings:
  fallbacks: [{"smart": ["fast"]}]   # a failed `smart` call is retried once on `fast`; always a list (1.108.1+)
  fallback_on_unsupported_params: false   # a 400 goes back to the caller, never to the fallback alias
  num_retries: 0                    # the client owns retries (aip.llm); stacking two retry layers multiplies load
  allowed_fails: 3
  cooldown_time: 30

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  proxy_batch_write_at: 10          # spend is written in batches every 10 s: budgets lag (lesson 3.3)
  allow_requests_on_db_unavailable: false

The litellm_settings block between the two, what the gateway logs, is in Going deeper. Secrets are os.environ/... references to infra/compose/.env. Two settings carry decisions (the spend write interval is lesson 3.3's subject):

  • fallback_on_unsupported_params: false: a 400 goes back to the caller instead of being answered by fast. Step 6 shows why.
  • allow_requests_on_db_unavailable: false, the default, written out so nobody flips it unseen. Without its database the gateway can't check budgets, so it refuses requests instead of serving them unmetered.

Two more files map the same two names to real models: config.yaml to Claude, config.openai.yaml to OpenAI. Same aliases, a different provider, no line of application code changed. Both live mappings, the cache breakpoint the aliases carry and the placeholder aliases are in Going deeper.

Step 2: the gateway service

The gateway service of infra/compose/compose.yml locks down how the gateway runs. Lesson 3.4 explains why, from the 2026 LiteLLM supply-chain compromises. The excerpt with its comments is in Going deeper, the whole service in Full code:

  • The image is pinned by version and digest, so a moved tag can't change what runs.
  • The port binds 127.0.0.1 only.
  • Provider keys never come from a file in the repository. Anthropic's comes from the shell that runs docker compose up. OpenAI's comes from a mode-600 file outside it, named by AIP_PROVIDER_ENV (the env_file entry), handed to this container only. Unset, it reads /dev/null: offline.
  • STORE_MODEL_IN_DB: "False" keeps models out of the gateway's database, so the reviewed config file is the only place an alias is defined. AIP_GATEWAY_CONFIG picks offline or live.

Step 3: declare each agent

What to notice. Each agent is a small block of limits plus an owner. Read support-answerer and ask what it may call, how much it may spend, how fast, and who answers for it.

The whole of infra/gateway/agents.yaml:

# One virtual key per agent: which aliases it may call, how much it may spend, how fast.
# Keys are created from this file by scripts/agent_key.py; changing a budget is a reviewed change here.
# Budgets are in USD and checked by the gateway with a lag (lesson 3.3): treat them as a control, not a hard cap.
agents:
  support-answerer:
    models: [fast]
    max_budget: 5.00
    budget_duration: 30d
    rpm_limit: 60
    tpm_limit: 200000
    metadata: {team: support, cost_center: CC-410, owner: support-leads}
  eval-runner:
    models: [fast, smart]
    max_budget: 2.00
    budget_duration: 1d
    rpm_limit: 120
    tpm_limit: 400000
    metadata: {team: platform, cost_center: CC-200, owner: platform-team}

Each line answers a question someone will ask you. Which models? The support answerer gets fast only: smart would be a reviewed change with a cost estimate. How much? Five dollars per 30 days, small enough that a loop hits it before anyone's budget meeting. How fast? 60 requests and 200,000 tokens per minute. Whose? team, cost_center and owner, so the spend report in lesson 3.3 maps to a person. The eval runner gets both aliases and a daily budget, because evals compare models and run in bursts.

For real models, infra/gateway/agents.live.yaml declares the same agents with smaller budgets (Going deeper has the numbers).

Step 4: issue the keys

What to notice. The order inside create_key: delete the agent's old key first, check the answer, and only then generate a new one. That order is what makes a rerun a rotation and not a second key.

From scripts/agent_key.py:

def create_key(agent: str, gateway: str, master: str, decl: dict) -> dict:
    """The key carries the agent's limits: the gateway enforces them on every call made with it."""
    body = {"key_alias": agent, "models": decl["models"],
            "max_budget": decl.get("max_budget"), "budget_duration": decl.get("budget_duration"),
            "rpm_limit": decl.get("rpm_limit"), "tpm_limit": decl.get("tpm_limit"),
            "metadata": {"agent": agent, **decl.get("metadata", {})}}
    headers = {"Authorization": f"Bearer {master}"}
    # One live key per agent: creating a new one revokes the old one (rotation in one step). Safe to re-run:
    # 404 means there was no key yet. Any other failure stops here, before a second key can exist.
    d = httpx.post(f"{gateway}/key/delete", json={"key_aliases": [agent]}, headers=headers)
    if d.status_code not in (200, 404):
        sys.exit(f"could not revoke the old key for {agent}: {d.status_code} {d.text[:200]}")
    r = httpx.post(f"{gateway}/key/generate", json=body, headers=headers)
    if r.status_code >= 400:
        sys.exit(f"gateway refused: {r.status_code} {r.text[:300]}")
    return r.json()

The master key is used for this one admin call. No application ever holds it.

The delete is checked. A 200 means the old key is revoked, a 404 means there was none. Anything else stops the script before it creates a second key, because two live keys for one agent means two budgets and a key nobody knows to revoke.

This open-source way has no grace period: anything still using the old key fails at once (Going deeper).

Run it for both agents (it never prints the key: Going deeper); the first call replaces lesson 2.2's key in .env:

$ uv run python scripts/agent_key.py support-answerer
created key for support-answerer: {'key_alias': 'support-answerer', 'models': ['fast'], 'max_budget': 5.0, 'budget_duration': '30d', 'rpm_limit': 60, 'tpm_limit': 200000} -> AIP_GATEWAY_KEY in /…/ai-platform/.env
$ uv run python scripts/agent_key.py eval-runner --env-file .env.eval
created key for eval-runner: {'key_alias': 'eval-runner', 'models': ['fast', 'smart'], 'max_budget': 2.0, 'budget_duration': '1d', 'rpm_limit': 120, 'tpm_limit': 400000} -> AIP_GATEWAY_KEY in .env.eval

Try it (5 min). Predict first: you run the script a second time for the support answerer. What happens to a client still holding the first key? Copy the old one aside with cp .env /tmp/old.env, rerun uv run python scripts/agent_key.py support-answerer, then call fast with the old file:

uv run python -c "from aip.config import Settings; from aip.llm import Client, GatewayError
try: Client(settings=Settings(_env_file='/tmp/old.env')).complete('fast', [{'role': 'user', 'content': 'hi'}])
except GatewayError as e: print(type(e).__name__, e.status)"

Then rm /tmp/old.env, because it holds a key. (Answer in Check yourself, item 5.)

Step 5: the gateway says no

The support answerer asks for smart:

$ uv run python -c "from aip.llm import Client, GatewayError
try: Client().complete('smart', [{'role': 'user', 'content': 'hi'}])
except GatewayError as e: print(type(e).__name__, e.status, str(e)[:120])"
AuthFailed 403 403 key_model_access_denied: The requested model 'smart' is not available for this API key, or the model name is invalid

A 403, classified as AuthFailed by lesson 2.4's code, and not retried. The application checked nothing; the key carries the rule. (Lesson 2.4's demo now runs on the eval runner's key: Going deeper.)

What to notice. Each test makes its own throwaway key, tries one rule, and deletes the key. The alias test is in Going deeper; here is the budget one.

From tests/integration/test_gateway_keys.py:

def test_an_exhausted_budget_is_refused_and_not_retried(admin):
    key = make_key(admin, models=["smart"], max_budget=0.0005)
    client = Client(settings=Settings(_env_file=None, gateway_key=key))
    first = client.complete("smart", [{"role": "user", "content": "x " * 400}])
    assert first.cost_usd > 0.0005          # one call can overshoot: the check runs before the cost is known
    with pytest.raises(BudgetExceeded) as e:
        client.complete("smart", [{"role": "user", "content": "x"}])
    assert e.value.status == 422
    admin.post("/key/delete", json={"keys": [key]})

The budget test pins two facts about LiteLLM 1.108.5: one call can overshoot the whole budget, and the next is refused with 422 and budget_exceeded. If an upgrade changes either, this test fails before your agents notice. The first test in the file, test_declared_agents_have_budgets_and_limits, needs no stack: every declared agent must have a budget, a window, rate limits, a team and a cost center, or continuous integration (CI) fails. The run of all seven tests, and the four that test the key script, are in Going deeper.

Step 6: a 400 is not a failure to fall back from

This step is a bug the first live run found, and the one setting that closes it. On LiteLLM 1.108.5 the fallback also fired on a 400. I sent smart (GPT-6.1 Sol) a reasoning_effort it doesn't support:

reasoning_effort=none on smart         -> 200, response "model": "gpt-6-luna"   (Sol has no `none`: smart failed, the gateway fell back to fast)

A request smart rejected came back as a 200 from another model; an invalid schema did the same. The client records fell_back on every Completion (lesson 2.2), but a 200 raises nothing, so nobody looks. A 400 means the request is wrong, and serving it from another model hides the bug behind a cheaper answer.

The fix is one router setting, fallback_on_unsupported_params: false, in all three configs. To prove it, I wrote a small script, bad400.py (mine, not in the repository; it's in Going deeper), that turns on one 400 at the stand-in, then calls smart with the eval runner's key.

With the setting, then with the line deleted from config.offline.yaml and the gateway recreated (in a scratch clone):

$ uv run python bad400.py
BadRequest 400: 400 sim_chaos: litellm.BadRequestError: OpenAIException - sim chaos 400
$ uv run python bad400.py          # fallback_on_unsupported_params removed
200 served by 'fast', fell_back=True

A test pins it: test_a_bad_request_is_never_served_by_the_fallback turns on one 400 at the stand-in and expects a BadRequest back, never a 200 from fast (the test, and its runs with and without the setting, are in Going deeper).

429s, 5xx and timeouts still fall back, which is the job. One gap stays: a provider's 401 or 422 still falls back on 1.108.5, with no setting for it (checked with the stand-in's chaos modes).

Your turn (10 min)

Lesson 2.2's ticket triage example still runs on whatever key sits in .env. If it became a real agent, it would get its own declaration first. Write it: add ticket-triage to infra/gateway/agents.yaml with fast only, a budget of USD 1 per day, 30 requests and 100,000 tokens per minute, a team and an owner. Leave out cost_center on purpose, then run the one test in the file that needs no stack:

uv run pytest tests/integration/test_gateway_keys.py -q -k declared

It fails and names your agent. Add the cost center and run it again until it reads 1 passed, 2 deselected. That's the review rule doing its job: an agent nobody can bill doesn't get declared. (The YAML is under Check yourself.)

What breaks

  • Fail open on the database. /health/readiness returns 200 with the database down. Control: allow_requests_on_db_unavailable: false (step 1), and monitor the database itself.
  • Counters per instance. A second instance without Redis doubles every limit. Control: Redis 7.0+ (Going deeper, step 2).
  • The master key in an application. It can create keys with any limits. Control: the master key lives in infra/compose/.env, is read by admin scripts only, and is never in an agent's environment.
  • A bad request answered by the fallback. On 1.108.5 a 400 from smart comes back as a 200 from fast unless you say otherwise. Control: fallback_on_unsupported_params: false in every config (step 6); a provider 401 or 422 still falls back, so alert on fell_back.

Decide

Default: aliases in a reviewed config file, STORE_MODEL_IN_DB off; one virtual key per agent, declared in a reviewed file with models, budget, window, rate limits and an owner; keys issued and rotated by a script, never by hand in the admin UI; fallback_on_unsupported_params: false.

When to pick otherwise: many teams with their own agents → LiteLLM teams with team budgets on top of per-agent keys (E6 lesson 2.3). Per-end-user budgets → pass user on each call and set user budgets. If you need organizations or team-admin roles, those are enterprise features in LiteLLM as of November 2026; look at the alternatives in lesson 3.1 before you buy.

Check yourself

  1. Your support agent needs smart for one feature. What changes? One line in agents.yaml, reviewed with a cost estimate, then the script rotates the key. No application code changes.
  2. A teammate wants smart on the support answerer's key, just to run lesson 2.4's fallback demo. What do you say? No. The demo runs on the eval runner's key. A production key widened for a demo stays widened for the loop at 2 a.m.
  3. The gateway's database restarts for two minutes. What happens to requests? With allow_requests_on_db_unavailable: false, they're refused. Flip it and they're served without budget checks.
  4. Why does the budget test assert that the first call costs more than the budget? It pins the real behavior of the pinned version: the check runs before the cost is known. If an upgrade changes that, you want to know.
  5. Try it (step 4): what happens to a client still holding the first key? You should see AuthFailed 401: the old key is gone from the gateway's database (token_not_found_in_db), and the new one in .env works.
  6. Your turn: one declaration that passes. Without cost_center, the test stops on AssertionError: ticket-triage (assert {'cost_center', 'team'} <= {'owner', 'team'}). With it, 1 passed, 2 deselected. I ran both at e1-m3-l2 on 16 November 2026, with no stack running. Your turn solution (not in the repository), appended under agents::
  ticket-triage:
    models: [fast]
    max_budget: 1.00
    budget_duration: 1d
    rpm_limit: 30
    tpm_limit: 100000
    metadata: {team: support, cost_center: CC-410, owner: support-leads}
Transcript

Hey friends. In this video, I'd like to show you how to set up LiteLLM so every agent gets its own key, with its own limits, enforced by the gateway. So you'll learn aliases, a key and a budget per agent, and fallbacks that don't hide bugs. All right, so far our one key can call any alias, with no budget and no rate limit.

That's most teams' first month, you know. Then one agent loops at two in the morning, the whole quota goes with it, and the bill can't tell you which agent did it. So, the gateway config. Application code says fast or smart. Here, fast means the stand-in, priced like Haiku, with the cache breakpoint from lesson two point three. The embedding and rerank names are placeholders: we pin the name now and choose the model in E5.

Name first, model later. Then the router. Smart falls back to fast, and the gateway's own retries are zero, because the client owns retries. The line under the fallback came from the first live run, and I'll come back to it. Below it, prompts and answers never reach the trace callbacks, and spend is written every ten seconds. That's why budgets lag, by the way, and lesson three point three measures it.

And this one I write out even though it's the default: no database, no requests. Why? Because serving unmetered is worse than refusing. Now, the live config maps the same two aliases to Claude Haiku five point five and Sonnet five point five. Same router, same settings. Application code can't tell which file is loaded, and that's the whole point. The fallback stays inside one provider family.

The first live runs were on OpenAI, because that was the key I had in November 2026, so there's a third file: fast is GPT-6 Luna, smart is GPT-6.1 Sol. No line of application code changed. And there's no price override either. The gateway's own price map has both models, so its cost header checks OpenAI's price page instead of echoing numbers we typed.

The decision record says why these two. All right, the gateway service. Everything lesson three point four argues for fits in this block. The image is pinned by version and digest, so a moved tag can't change what runs. The port binds to localhost only. And provider keys never live in the repo. The Anthropic key comes from the shell. The OpenAI key comes from a file outside the repo, named by one variable, and compose hands it to this container and no other.

Unset, it reads nothing, and you're offline. Now, read the warning in the comment: two common debugging commands print a container's environment, key included. So don't run them with the key set. The salt key encrypts stored credentials, and it can't change after first start. Models aren't stored in the database, so the reviewed file is the only place an alias is defined.

And there's no Redis here, so this is one instance. Run two without Redis, and every limit doubles. Now, the file that matters. Every agent the platform runs is declared here, and it's reviewed like code. The support answerer may call fast only. Five dollars per thirty days, small enough that a loop hits it before anyone's budget meeting. Sixty requests a minute.

And a team, a cost center and an owner, so the spend report maps to a person instead of a key name. The eval runner gets both models and a daily budget, because evals compare models and run in bursts. For live runs there's a second file, same agents, with budgets of one and two dollars. And honestly, the whole first live run of this course cost under eight cents.

So a script turns each declaration into a virtual key. It replaces the key we've used since lesson two point two, the one with no budget. The master key is used for this one admin call and nowhere else, and no application ever holds it. It deletes the agent's old key before it creates the new one, so running it again is a rotation: the old key stops working before the new one exists.

And it reads the answer to the delete. Revoked, or nothing to revoke, it goes on. Anything else, it stops, before a second live key can exist. Oh, and the env file is created with owner-only permissions before a byte is written. The script prints the limits the gateway accepted, and it never prints the key. Okay, let's see the gateway say no.

The support answerer asks for smart. Forbidden: a 403, typed as an auth failure by the client from lesson two point four, and not retried. Now notice where the rule lives, right? The application checked nothing. The key carries the rule, and the gateway enforces it on every call. Seven tests. This one pins two facts about this LiteLLM version. The first call on a tiny budget is allowed and costs more than the whole budget, because the check runs before the cost is known.

The second is refused with a 422. If an upgrade changes either one, this test fails before your agents notice. And the key script: run it twice, and there's one live key, so a rerun is a rotation. All right, back to that line under the fallback. On the first live run I sent smart a reasoning setting it doesn't support.

It came back as a 200. From fast. So the gateway fell back on a 400, and a request smart rejected was quietly answered by a cheaper model. The client records the fallback, but a 200 raises nothing, so nobody looks. A 400 means the request is wrong, and serving it from another model hides the bug. One router setting sends the 400 back to the caller.

The stand-in can fake a 400, so here it is: smart, the eval runner's key, a 400, and it comes back as a 400. When I deleted that one line and restarted the gateway, the same call came back as a 200 from fast, and this test failed. Rate limits, outages and timeouts still fall back. That's the job. But a provider's 401 or 422 still falls back on this version, and there's no setting for it, so alert on the fallback flag.

Last, the decision records. The first lists what we measured on this version that the docs didn't lead us to expect: budgets answer 422, the wait header is renamed, a forbidden alias is a 403, and a stream has no cost header. The second does the same for the first live provider: the fallback on a 400, a refusal written inside the schema, and a cache that charges more on the first call.

So write these down when you find them, because they're what your next upgrade has to re-check. And the tree matches the tag. Every agent now has a key, a budget and an owner. Next up: what a call actually cost, and how late the budget finds out. See you there.

Going deeper

Build it: what's pinned, and what changed

Pinned for this lesson: LiteLLM proxy ghcr.io/berriai/litellm:v1.108.5 by digest, Postgres 17 (pgvector/pgvector:0.8.7-pg17), Python 3.12, httpx 0.28.1, pyyaml 6.0.3. Aliases point at the stand-in model (decision record 0001 in docs/decisions/), so no provider key is needed. The gateway config and the sim are mounted from your clone: without the recreate, the stack keeps serving lesson 2.4's files.

This tag adds the agents, the key script, the tests, and three fixes from the first live runs:

git diff --stat=72 e1-m2-l4..e1-m3-l2 -- src examples scripts infra
 examples/bad_day.py               |  9 +++++--
 infra/compose/compose.yml         |  9 ++++++-
 infra/gateway/agents.live.yaml    | 25 +++++++++++++++++++
 infra/gateway/agents.yaml         | 18 ++++++++++++++
 infra/gateway/config.offline.yaml |  1 +
 infra/gateway/config.openai.yaml  | 40 +++++++++++++++++++++++++++++++
 infra/gateway/config.yaml         |  1 +
 infra/sim/simllm.py               |  4 ++--
 scripts/agent_key.py              | 17 +++++++++----
 9 files changed, 114 insertions(+), 10 deletions(-)

Step 1: what the gateway logs

Between router_settings and general_settings sits the logging block:

litellm_settings:
  callbacks: ["otel"]               # gateway spans -> OTel Collector -> Langfuse, joined to the caller's traceparent
  turn_off_message_logging: true    # prompts and completions never reach callbacks; spend and metadata still do
  redact_user_api_key_info: true    # strip key, user and team identifiers from logged spans
  request_timeout: 60

Prompts and answers never reach the trace callbacks. Content in traces is a decision you make later, with redaction in front of it (lesson 5.1).

Don't take the redact_user_api_key_info comment at its word, though: the flag doesn't reach the otel callback, and lesson 5.1, part 2 shows key identifiers arriving anyway.

Step 1: the cache breakpoint

The aliases carry the cache breakpoint from lesson 2.3 (cache_control_injection_points in the whole file, in Full code).

Step 1: placeholders and cooldown

The embedding and rerank aliases are placeholders for E5 (an embedding is a list of numbers that stands for a text's meaning, so similar texts get similar lists; a reranker reorders search results). The name is pinned now, the model is chosen in E5. Once a deployment fails more than three calls (allowed_fails), LiteLLM takes it out of rotation for 30 seconds.

Step 1: the spend write interval

proxy_batch_write_at: 10: spend reaches Postgres in batches every 10 seconds (the default; the LiteLLM production guide's example uses 60). That's why budgets lag, and lesson 3.3 measures it.

Step 1: the two live mappings

What to notice. Same two alias names, now pointing at real Claude models. The comment says why the gateway, not your code, adds the cache marker.

From infra/gateway/config.yaml, the live mapping:

# Anthropic caches only up to an explicit cache_control breakpoint. The gateway adds one on the system prompt
# (the stable prefix: instructions, policies), so application code never carries provider-specific markers.
# On an automatically caching provider (OpenAI before GPT-5.6) LiteLLM adds nothing. Docs read 12 Nov 2026.
model_list:
  - model_name: fast
    litellm_params: {model: anthropic/claude-haiku-5-5, api_key: os.environ/ANTHROPIC_API_KEY,
                     cache_control_injection_points: [{location: message, role: system}]}
  - model_name: smart
    litellm_params: {model: anthropic/claude-sonnet-5-5, api_key: os.environ/ANTHROPIC_API_KEY,
                     cache_control_injection_points: [{location: message, role: system}]}

config.openai.yaml ran the first live runs (decision record 0006 in docs/decisions/). Model ids from Anthropic's models page, read 12 November 2026. The rest of the file matches the offline one, and the fallback stays inside one provider family. Remapping an alias is a reviewed change, gated by the evals of module 5 and E2.

config.yaml points fast and smart at Claude Haiku 5.5 and Sonnet 5.5; config.openai.yaml points them at GPT-6 Luna and GPT-6.1 Sol. The first live runs of this platform were on OpenAI, because that was the key I had on 12 November 2026. Decision record 0006 in docs/decisions/ says so, and why these two models. This is the live configuration the rest of the series refers to.

What to notice. The same fast and smart names again, a third provider behind them. There's no model_info price override and no cache marker; the header comments of the file (in Full code) say why.

From infra/gateway/config.openai.yaml (whole file in Full code):

model_list:
  - model_name: fast
    litellm_params: {model: openai/gpt-6-luna, api_key: os.environ/OPENAI_API_KEY}
  - model_name: smart
    litellm_params: {model: openai/gpt-6.1-sol, api_key: os.environ/OPENAI_API_KEY}
  - model_name: embed-default
    litellm_params: {model: openai/text-embedding-3-small, api_key: os.environ/OPENAI_API_KEY}
    model_info: {mode: embedding}
  # OpenAI has no rerank endpoint: rerank-default stays on the sim until E5 chooses a reranker.
  - model_name: rerank-default
    litellm_params: {model: openai/sim-rerank, api_base: http://sim:9100/v1, api_key: sim-needs-no-key}
    model_info: {mode: rerank}

Same aliases, a different provider, no line of application code changed. No price override: LiteLLM's bundled price map holds both ids, so the cost header becomes an independent check of OpenAI's price page (lesson 3.3 compares them). No cache breakpoint: OpenAI caches long prefixes on its own. The rest of the file repeats the offline file's settings.

Step 2: the gateway service, excerpt

Two debugging commands print the key. docker compose config and docker inspect print a container's resolved environment, key included (a comment in the service warns about it). To check the key arrived without seeing it: docker compose exec gateway sh -c '[ -n "$OPENAI_API_KEY" ] && echo present'.

What to notice. Two ways a provider key reaches this container: ANTHROPIC_API_KEY from your shell, and the OpenAI key through env_file, from a file outside the repo. Then the last line: the port binds to 127.0.0.1 only. The image line above this excerpt pins ghcr.io/berriai/litellm:v1.108.5 by digest.

From the gateway service in infra/compose/compose.yml (the whole service is in Full code at the end):

    environment:
      DATABASE_URL: postgresql://litellm:${LITELLM_DB_PASSWORD}@postgres:5432/litellm
      LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
      LITELLM_SALT_KEY: ${LITELLM_SALT_KEY}
      STORE_MODEL_IN_DB: "False"
      # Provider keys are read from the shell that runs `docker compose up`, never from a file in the repo.
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
      # Gateway spans go to the collector (obs profile). If it is not running, export fails quietly.
      OTEL_EXPORTER: otlp_http
      OTEL_ENDPOINT: http://otel-collector:4318/v1/traces
      OTEL_SERVICE_NAME: litellm-gateway
    # OpenAI key: from a file OUTSIDE the repo (mode 600), named by AIP_PROVIDER_ENV. Compose reads the file and
    # hands the variable to this container only: the value never appears on a command line or in this repo.
    # Careful: `docker compose config` and `docker inspect` print resolved environments; do not run them with it set.
    # Unset = /dev/null = no key (offline). Not under `environment:` on purpose: an `environment:` entry, even
    # an empty one, overrides the same name from env_file.
    env_file:
      - path: ${AIP_PROVIDER_ENV:-/dev/null}
        required: false
    volumes:
      - ../gateway/${AIP_GATEWAY_CONFIG:-config.offline.yaml}:/etc/litellm/config.yaml:ro
    ports: ["127.0.0.1:${AIP_GATEWAY_PORT:-4000}:4000"]

Step 2: no Redis, one instance

There is no Redis for the gateway: this is one instance. From the second instance on, LiteLLM needs Redis 7.0 or later, or each instance keeps its own counters and every limit multiplies by the number of instances.

Step 2: two more details of the gateway service

  • An environment: entry for the same name, even an empty one, would override env_file (the comment just above it says so).
  • LITELLM_SALT_KEY encrypts stored credentials and can't change after first start, which is why init-secrets.sh won't overwrite it without --force.

Step 3: the live budgets

For real models a second file, infra/gateway/agents.live.yaml, declares the same agents with smaller budgets (USD 1 for the support answerer, 2 for the eval runner, and a live-probe key at USD 1 for measurements by hand), passed to the script with --agents-file. The whole first live run of E1, 495 calls, cost USD 0.0777 against a ceiling of USD 4.

Step 4: how the script writes the key

write_dotenv creates the file with mode 600 before writing a byte. The script prints the limits it got back and where it wrote the key, never the key (see main in Full code).

Step 4: the grace period

LiteLLM's regeneration with a grace period is an enterprise feature. This open-source way has no grace period: anything still using the old key fails at once.

Step 5: lesson 2.4's demo on two keys

Lesson 2.4's 503 demo calls smart, so on the support answerer's key it now fails the same way. It runs on the eval runner's key instead. The production agent's key never gets widened for a demo.

$ uv run python examples/bad_day.py 503
AuthFailed (retryable=False): 403 key_model_access_denied: The requested model 'smart' is not available for this API key, or the model name is invalid. Check the models available to you and try again.
$ AIP_ENV_FILE=.env.eval uv run python examples/bad_day.py 503
ok after 1 attempt(s), served by 'fast', fallbacks=1: How long does ground shipping take?

bad_day.py reads AIP_ENV_FILE, so the fallback demo runs on the eval runner's key.

Step 5: the alias test, and the run

From tests/integration/test_gateway_keys.py:

def test_a_key_only_reaches_its_aliases(admin):
    key = make_key(admin, models=["fast"])
    client = Client(settings=Settings(_env_file=None, gateway_key=key))
    assert client.complete("fast", [{"role": "user", "content": "hi"}]).text
    with pytest.raises(AuthFailed):
        client.complete("smart", [{"role": "user", "content": "hi"}])
    admin.post("/key/delete", json={"keys": [key]})
$ uv run pytest tests/integration/test_gateway_keys.py tests/integration/test_agent_key.py tests/unit/test_agent_key_script.py -q
.......                                                                  [100%]
7 passed

Step 5: the fixture and the other four tests

Each test makes a throwaway key through the admin fixture (tests/conftest.py reads the master key from infra/compose/.env, and skips with the reason when the stack isn't up), tests one rule, and deletes the key.

The other four test the key script: run twice, one live key, one line in the env file, no key in the output; and a 500 on the delete stops it with nothing created (test_a_failed_delete_stops_before_a_second_key_exists).

Step 6: the script that proves it

The fix is one router setting, fallback_on_unsupported_params: false, in all three configs. To prove it, this script (mine, not in the repository) turns on one 400 at the stand-in, then calls smart with the eval runner's key:

cat > bad400.py <<'EOF'
import httpx
from aip.config import Settings, local
from aip.llm import Client, GatewayError

httpx.post(local("AIP_SIM_PORT", 9100, "/admin/chaos"), json={"mode": "400", "count": 1})
try:
    c = Client(settings=Settings(_env_file=".env.eval")).complete("smart", [{"role": "user", "content": "hi"}])
    print(f"200 served by '{c.served_alias}', fell_back={c.fell_back}")
except GatewayError as e:
    print(f"{type(e).__name__} {e.status}: {str(e)[:90]}")
EOF

Step 6: the test

What to notice. The test turns on one 400 at the stand-in and expects a BadRequest back, never a 200 from fast. The finally turns the chaos off, whatever happens.

From tests/integration/test_gateway_failures.py:

def test_a_bad_request_is_never_served_by_the_fallback(gateway):
    """A request `smart` rejects (400) must come back as a 400, not as a 200 from `fast` (decision 0006)."""
    chaos("400", count=1)
    try:
        with pytest.raises(BadRequest) as e:
            Client(settings=gateway).complete("smart", [{"role": "user", "content": "shipping?"}])
        assert e.value.status == 400
    finally:
        chaos(None, count=0)

Step 6: the failure tests, with the setting

Without the setting this test fails (1 failed, 5 passed when I deleted the line); with it, the file gives 6 passed:

$ uv run pytest tests/integration/test_gateway_failures.py -q
......                                                                   [100%]
6 passed

Step 6: what we wrote down

My default, after this run: whenever the pinned version surprises you, write it down in a decision record. Those notes are what your next upgrade has to re-check.

Decision record 0006 also notes the gap that stays: a provider's 401 or 422 still falls back on 1.108.5.

Last, decision record 0003 in docs/decisions/ lists what we observed on 1.108.5 that the docs didn't lead us to expect: budgets answer 422, Retry-After arrives as llm_provider-retry-after, a forbidden alias answers 403, and a stream carries no cost header. Decision record 0006 does the same for the first live provider. Write these down when you find them: they're what your next upgrade has to re-check.

What breaks: four more

  • A key that outlives its agent. Keys don't expire unless you say so. Control: agents.yaml is the list; an agent removed from it gets its key deleted in the same change.
  • A rotation that leaves two keys. A delete that fails unread leaves the old key spending against its own budget. Control: the script goes on only after a 200 or a 404 (step 4).
  • A provider key printed by a debugging command. env_file keeps the key out of the repository, not out of docker inspect. Never run those two commands on a stack with a live key; check presence with the present one-liner.
  • A rename that stops the proxy. In 1.108.1, a fallback target written as a plain string stops the proxy at startup. Control: the list form, and a staging start on every upgrade.
Full code

From infra/gateway/config.offline.yaml:

# LiteLLM proxy config, OFFLINE: every alias points at the sim stand-in model (infra/sim/simllm.py).
# Same aliases, same settings as config.yaml (live), so application code never changes between the two.
# Prices below are ILLUSTRATIVE: copied from the provider price pages on 11 Nov 2026 (fast = Claude Haiku 5.5,
# smart = Claude Sonnet 5.5, USD per token) so cost numbers look like real ones. The sim is free.
# Cache breakpoints: the gateway marks the system prompt (cache_control_injection_points), as in config.yaml.
model_list:
  - model_name: fast
    litellm_params: {model: openai/sim-small, api_base: http://sim:9100/v1, api_key: sim-needs-no-key,
                     cache_control_injection_points: [{location: message, role: system}]}
    model_info: {input_cost_per_token: 0.0000001, cache_read_input_token_cost: 0.00000001, output_cost_per_token: 0.0000005}
  - model_name: smart
    litellm_params: {model: openai/sim-large, api_base: http://sim:9100/v1, api_key: sim-needs-no-key,
                     cache_control_injection_points: [{location: message, role: system}]}
    model_info: {input_cost_per_token: 0.000002, cache_read_input_token_cost: 0.0000001, output_cost_per_token: 0.00001}
  # Placeholders for E5 (knowledge): pinned names now, real models later.
  - model_name: embed-default
    litellm_params: {model: openai/sim-embed, api_base: http://sim:9100/v1, api_key: sim-needs-no-key}
    model_info: {mode: embedding, input_cost_per_token: 0.00000002, output_cost_per_token: 0}
  - model_name: rerank-default
    litellm_params: {model: openai/sim-rerank, api_base: http://sim:9100/v1, api_key: sim-needs-no-key}
    model_info: {mode: rerank}

router_settings:
  fallbacks: [{"smart": ["fast"]}]   # a failed `smart` call is retried once on `fast`; always a list (1.108.1+)
  fallback_on_unsupported_params: false   # a 400 goes back to the caller, never to the fallback alias
  num_retries: 0                    # the client owns retries (aip.llm); stacking two retry layers multiplies load
  allowed_fails: 3
  cooldown_time: 30

litellm_settings:
  callbacks: ["otel"]               # gateway spans -> OTel Collector -> Langfuse, joined to the caller's traceparent
  turn_off_message_logging: true    # prompts and completions never reach callbacks; spend and metadata still do
  redact_user_api_key_info: true    # strip key, user and team identifiers from logged spans
  request_timeout: 60

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  proxy_batch_write_at: 10          # spend is written in batches every 10 s: budgets lag (lesson 3.3)
  allow_requests_on_db_unavailable: false

From infra/gateway/config.openai.yaml:

# LiteLLM proxy config, LIVE on OpenAI: same aliases as config.yaml and config.offline.yaml, so application code
# never changes. Decision record: docs/decisions/0006-live-provider-openai.md.
# Model ids and prices from https://developers.openai.com/api/docs/pricing and /api/docs/models, read 12 Nov 2026.
# None of them is on the deprecations page (gpt-5, gpt-5-mini/nano, o3, o3-pro: shutdown date 11 Dec 2026).
# Prices: no model_info override. LiteLLM 1.108.5's bundled price map already holds these ids at the price-page
# values, so the x-litellm-response-cost header can be checked against the provider's price, not against itself.
# The key: OPENAI_API_KEY, handed to the gateway container by compose from the file named in AIP_PROVIDER_ENV.
# Caching: OpenAI caches prefixes of 1,024+ tokens automatically (no cache_control_injection_points here).
# Sampling parameters stay opt-in in the client (AIP_SAMPLING), as in E1: nothing is set here.
model_list:
  - model_name: fast
    litellm_params: {model: openai/gpt-6-luna, api_key: os.environ/OPENAI_API_KEY}
  - model_name: smart
    litellm_params: {model: openai/gpt-6.1-sol, api_key: os.environ/OPENAI_API_KEY}
  - model_name: embed-default
    litellm_params: {model: openai/text-embedding-3-small, api_key: os.environ/OPENAI_API_KEY}
    model_info: {mode: embedding}
  # OpenAI has no rerank endpoint: rerank-default stays on the sim until E5 chooses a reranker.
  - model_name: rerank-default
    litellm_params: {model: openai/sim-rerank, api_base: http://sim:9100/v1, api_key: sim-needs-no-key}
    model_info: {mode: rerank}

router_settings:
  fallbacks: [{"smart": ["fast"]}]
  fallback_on_unsupported_params: false   # a 400 goes back to the caller, never to the fallback alias
  num_retries: 0
  allowed_fails: 3
  cooldown_time: 30

litellm_settings:
  callbacks: ["otel"]
  turn_off_message_logging: true
  redact_user_api_key_info: true
  request_timeout: 60

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  proxy_batch_write_at: 10
  allow_requests_on_db_unavailable: false

The gateway service in infra/compose/compose.yml:

  gateway:
    profiles: [core]
    image: ghcr.io/berriai/litellm:v1.108.5@sha256:008a5916c0a0ca6f4f6ad64969f6a4ef6f03ce885a639f3d97fd53665754ce48
    command: ["--config", "/etc/litellm/config.yaml", "--port", "4000"]
    depends_on:
      postgres: {condition: service_healthy}
      sim: {condition: service_healthy}
    environment:
      DATABASE_URL: postgresql://litellm:${LITELLM_DB_PASSWORD}@postgres:5432/litellm
      LITELLM_MASTER_KEY: ${LITELLM_MASTER_KEY}
      LITELLM_SALT_KEY: ${LITELLM_SALT_KEY}
      STORE_MODEL_IN_DB: "False"
      # Provider keys are read from the shell that runs `docker compose up`, never from a file in the repo.
      ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}
      # Gateway spans go to the collector (obs profile). If it is not running, export fails quietly.
      OTEL_EXPORTER: otlp_http
      OTEL_ENDPOINT: http://otel-collector:4318/v1/traces
      OTEL_SERVICE_NAME: litellm-gateway
    # OpenAI key: from a file OUTSIDE the repo (mode 600), named by AIP_PROVIDER_ENV. Compose reads the file and
    # hands the variable to this container only: the value never appears on a command line or in this repo.
    # Careful: `docker compose config` and `docker inspect` print resolved environments; do not run them with it set.
    # Unset = /dev/null = no key (offline). Not under `environment:` on purpose: an `environment:` entry, even
    # an empty one, overrides the same name from env_file.
    env_file:
      - path: ${AIP_PROVIDER_ENV:-/dev/null}
        required: false
    volumes:
      - ../gateway/${AIP_GATEWAY_CONFIG:-config.offline.yaml}:/etc/litellm/config.yaml:ro
    ports: ["127.0.0.1:${AIP_GATEWAY_PORT:-4000}:4000"]
    healthcheck:
      test: ["CMD-SHELL", "python3 -c \"import urllib.request;urllib.request.urlopen('http://127.0.0.1:4000/health/liveliness')\""]
      interval: 5s
      timeout: 5s
      retries: 40

From scripts/agent_key.py, create_key and write_dotenv:

def create_key(agent: str, gateway: str, master: str, decl: dict) -> dict:
    """The key carries the agent's limits: the gateway enforces them on every call made with it."""
    body = {"key_alias": agent, "models": decl["models"],
            "max_budget": decl.get("max_budget"), "budget_duration": decl.get("budget_duration"),
            "rpm_limit": decl.get("rpm_limit"), "tpm_limit": decl.get("tpm_limit"),
            "metadata": {"agent": agent, **decl.get("metadata", {})}}
    headers = {"Authorization": f"Bearer {master}"}
    # One live key per agent: creating a new one revokes the old one (rotation in one step). Safe to re-run:
    # 404 means there was no key yet. Any other failure stops here, before a second key can exist.
    d = httpx.post(f"{gateway}/key/delete", json={"key_aliases": [agent]}, headers=headers)
    if d.status_code not in (200, 404):
        sys.exit(f"could not revoke the old key for {agent}: {d.status_code} {d.text[:200]}")
    r = httpx.post(f"{gateway}/key/generate", json=body, headers=headers)
    if r.status_code >= 400:
        sys.exit(f"gateway refused: {r.status_code} {r.text[:300]}")
    return r.json()


def write_dotenv(path: Path, updates: dict[str, str]) -> None:
    env = read_env(path) if path.exists() else {}
    env.update(updates)
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        f.writelines(f"{k}={v}\n" for k, v in env.items())
    os.chmod(path, 0o600)

main in scripts/agent_key.py:

def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("agent")
    ap.add_argument("--agents-file", default=str(ROOT / "infra" / "gateway" / "agents.yaml"))
    ap.add_argument("--gateway", default=Settings(_env_file=None).gateway_url)
    ap.add_argument("--env-file", default=str(ROOT / ".env"))
    ap.add_argument("--var", default="AIP_GATEWAY_KEY")
    a = ap.parse_args()
    master = read_env(ROOT / "infra" / "compose" / ".env")["LITELLM_MASTER_KEY"]
    decl = yaml.safe_load(Path(a.agents_file).read_text())["agents"][a.agent]
    info = create_key(a.agent, a.gateway, master, decl)
    write_dotenv(Path(a.env_file), {a.var: info["key"]})
    shown = {k: info.get(k) for k in ("key_alias", "models", "max_budget", "budget_duration", "rpm_limit", "tpm_limit")}
    print(f"created key for {a.agent}: {shown} -> {a.var} in {a.env_file}", file=sys.stderr)
Sources
  • LiteLLM virtual keys (/key/generate fields; regeneration with grace period is enterprise): https://docs.litellm.ai/docs/proxy/virtual_keys (checked 12 Nov 2026)
  • LiteLLM budgets (levels; counters per instance without Redis; fail open without a database): https://docs.litellm.ai/docs/proxy/users (checked 12 Nov 2026)
  • LiteLLM production guide (Postgres required, Redis 7.0+, LITELLM_SALT_KEY, proxy_batch_write_at example of 60, /health/readiness): https://docs.litellm.ai/docs/proxy/prod (checked 12 Nov 2026)
  • LiteLLM config settings (proxy_batch_write_at default 10 s, allow_requests_on_db_unavailable), logging (turn_off_message_logging, redact_user_api_key_info), access control (open-source and enterprise roles), fallbacks: https://docs.litellm.ai/docs/proxy/config_settings, https://docs.litellm.ai/docs/proxy/logging, https://docs.litellm.ai/docs/proxy/access_control, https://docs.litellm.ai/docs/proxy/reliability (checked 12 Nov 2026)
  • LiteLLM release notes (1.108.1 string fallback stops the proxy): https://docs.litellm.ai/release_notes/ (checked 12 Nov 2026)
  • Anthropic models overview (claude-haiku-5-5, claude-sonnet-5-5): https://platform.claude.com/docs/en/about-claude/models/overview (read 12 Nov 2026, per docs/VERSIONS.md)
  • Reference repository ai-platform, tag e1-m3-l2: infra/gateway/{config.offline,config,agents}.yaml, infra/compose/compose.yml, scripts/agent_key.py, examples/bad_day.py, tests/integration/test_gateway_keys.py, tests/integration/test_agent_key.py, tests/unit/test_agent_key_script.py, tests/conftest.py, docs/decisions/0003; runs and a key-rotation check on 12 Nov 2026, rerun from lesson 2.4's tag on 13 Nov 2026 (offline config)
  • Reference repository ai-platform, tag e1-m3-l2: infra/gateway/config.openai.yaml, infra/gateway/agents.live.yaml, tests/integration/test_gateway_failures.py (test_a_bad_request_is_never_served_by_the_fallback), decision record 0006 (docs/decisions/0006-live-provider-openai.md); the 400 run with and without fallback_on_unsupported_params, 13 Nov 2026 (offline config, scratch clone)
  • Live runs on OpenAI, 12 Nov 2026 (the 400 served by the fallback, total spend): reference repository, branch live, docs/LIVE_RUNS_E1.md, sections "2.4" and "Spend"
  • OpenAI models and pricing (gpt-6-luna, gpt-6.1-sol): https://developers.openai.com/api/docs/models, https://developers.openai.com/api/docs/pricing (read 12 Nov 2026, per decision record 0006)

That was one lesson of 27. The rest builds on it.

The other 26 build the platform around it: one client for every model call, the cost and trace of every call, and a first eval gate in CI.

AI Engineering Foundations
€197
One-time · lifetime access · all future updates included.
  • 27 lessons, 8 films and 13 step-by-step screencasts
  • The course code as git bundles, labs with tests and a capstone
3 months in the Engine Room, Cohorte's community of people who put AI to work. What's inside the Engine Room
Enroll · €197
Refunds, company invoices and client use of the code: see the FAQ.

A free lesson from each courseCourse 1 · A key and a budget per agent (this page)
Course 2 · An LLM judge, checked against human labels
Course 3 · A tamper-evident audit trail for agents
Course 4 · An agent that asks when it could leak
Course 5 · Retrieval that knows who is asking
Course 6 · A model outage you've already rehearsed