AI Engineering · Capstone 4 of 4
Build an LLM gateway in Python: an OpenAI-compatible proxy with API keys, rate limits, token budgets, fallback, caching and cost per team
Build the one service every app calls instead of a model provider: an OpenAI-compatible FastAPI proxy with streaming, team API keys, token-bucket rate limits, daily token budgets, model aliases with fallback and circuit breakers, an exact-match cache, cost per team in SQLite, redacted logs, traces and a load test.
⏱ 480 minAdvanced💸 Free (local model)8 milestones
Python 3.12uvOllamallama3.2:3bFastAPIhttpx2SQLiteOpenTelemetrypytestDocker
Overview video
What you will build
An LLM gateway: a small web service that sits between your company's apps and the model servers. An app keeps using the normal OpenAI SDK; it only changes two settings, the base URL (now the gateway) and the key (now a gateway key for its team). It asks for model="fast" or model="smart", and the gateway decides which real model answers: fast is llama3.2:3b on your Ollama, smart is a "hosted" model on a fake paid API that you run locally. When the first choice fails, the gateway quietly uses the next one.
On the way through, the gateway does the jobs no single app should do on its own: it checks the API key and the team's allowed models, applies a rate limit per key (a token bucket) and a daily token budget per team, streams answers through as they are generated, falls back to a second upstream on errors and timeouts and stops calling a broken one (a circuit breaker), answers repeated deterministic questions from an exact-match cache, records tokens and cost per team in SQLite with an /admin/usage report, writes one JSON log line per request with personal data masked, and traces every request and every upstream try with OpenTelemetry. You finish with a load test (p50, p95, cache hit rate) and a Docker image.
It is the hands-on version of the system design problem Design an LLM gateway: one process and SQLite instead of a fleet and Redis, but the same ideas, and the same trade-offs to talk about in an interview.
How a capstone works. Each milestone gives you the requirements, the exact names and shapes the tests rely on, Done when checks and hints. The reference solution is folded away under each milestone: try it yourself first. Every milestone has a test file, tests/test_m<n>.py. Before you start a milestone, copy that one file from the solution (or from the project download at the bottom of the page) into your tests/ folder, then write code until it passes. Milestone 1 also gives you tests/conftest.py and tests/fakes.py, the shared test helpers: two fake upstreams behind one httpx2.MockTransport, so the tests need no model and run in a few seconds.
Before you start
- This capstone combines four labs. You can build it without them, but each explains one part in depth: Your first LLM call (the request and the errors), Streaming chat (Server-Sent Events through FastAPI), Tracing and cost (spans, GenAI attributes, prices, p95) and Ship it, and serve a model (the Dockerfile).
- Python you will see: FastAPI (endpoints, dependencies,
TestClient), HTTP clients with httpx (async clients, streaming,MockTransport), async and await and Testing with pytest. New to Python? Start with Set up Python the modern way. - The design behind it (15 minutes): Design an LLM gateway.
- About 3 GB of free disk for the model. Docker for milestone 8 (optional).
Setup
S1Install uv (skip if you did lab 1)
uv installs Python for you, creates the virtual environment and manages packages: one tool instead of pyenv + venv + pip.
curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"curl -LsSf https://astral.sh/uv/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" everything's installed!
S2Check uv works
The export PATH=... line makes uv work in this terminal right away. New terminal windows find it on their own (the installer added it to your shell settings). On Windows, open a new terminal after installing.
uv --version uv 0.x.y
S3Install Ollama (skip if you did lab 1)
Download it from ollama.com/download and open it once. It runs a server on port 11434 that speaks the OpenAI-compatible API under /v1. That is the gateway's first upstream.
ollama --version ollama version is 0.x.y
S4Pull the model (llama3.2:3b, about 2 GB)
The gateway does not care which model answers, so a small one is fine. The second upstream, a fake "hosted" API, is a Python file you write in milestone 5: no account and no cost.
ollama pull llama3.2:3b pulling manifest ... success
S5Check Ollama answers on its OpenAI-compatible API
This is the endpoint the gateway calls. If you see a JSON list with llama3.2:3b in it, the upstream is ready.
curl -s localhost:11434/v1/modelscurl -s localhost:11434/v1/modelscurl.exe -s localhost:11434/v1/models {"object":"list","data":[{"id":"llama3.2:3b","object":"model","created":1764000000,"owned_by":"library"}]} A pass-through proxy with model aliases
An OpenAI-compatible FastAPI app that resolves `fast` and `smart` to a real upstream model, forwards the request, and answers errors in the OpenAI error shape.
Create the project. uv init --python 3.12 llm-gateway (the --python 3.12 matters: uv may otherwise pick a newer Python, like 3.15, and the outputs on this page are from 3.12). Delete the main.py uv writes, then add every package this capstone uses:
uv add fastapi uvicorn httpx2 python-dotenv opentelemetry-api==1.45.2 opentelemetry-sdk==1.45.2
uv add --dev pytest openai
httpx2 is the HTTP client the gateway uses to call upstreams (it is the library the openai SDK 3.x is built on, and FastAPI's TestClient needs it too). openai is only a dev dependency: the gateway never imports it; the example app and the tests do. Add a [tool.pytest.ini_options] table to pyproject.toml by hand with pythonpath = [".", "tests"] and testpaths = ["tests"]. Copy gateway.toml, .env, tests/conftest.py, tests/fakes.py and tests/test_m1.py from the solution.
gateway.toml is the gateway's own config, read with Python's built-in tomllib (TOML is the format of pyproject.toml). It has every section from the start; each comment says which milestone uses it. upstreams: name, base_url, api_key_env (the name of the environment variable that holds the key the gateway sends to that upstream) and timeout_s. routes: each alias apps may ask for, with an ordered list of "upstream/model" targets. teams, prices, limits, breaker and cache come later.
config.py has two parts. settings() returns a frozen dataclass Settings from environment variables (it loads .env from the project folder first; relative paths are relative to that folder): config_file (GATEWAY_CONFIG, default gateway.toml), db_path (GATEWAY_DB, gateway.db), admin_key (ADMIN_KEY, empty), log_file (LOG_FILE, gateway.log), log_prompts (LOG_PROMPTS, true only for the text true) and trace_exporter (TRACE_EXPORTER, none). And load_config(path) -> GatewayConfig reads the TOML into frozen dataclasses:
Upstream(name, base_url, api_key, timeout_s):api_keyis the value of the variable named byapi_key_env("none"if unset), and an environment variableUPSTREAM_<NAME>_URL(for exampleUPSTREAM_OLLAMA_URL) replacesbase_url. Docker needs that in milestone 8; you need it if your Ollama is not on localhost.Target(upstream, model), whosestr()is"ollama/llama3.2:3b".Team(name, models, daily_token_budget), in that order (a test builds one).GatewayConfig(upstreams, routes, teams, prices, default_max_tokens, breaker_failures, breaker_cooldown_s, cache_ttl_s, cache_max_entries):routesmaps an alias to a tuple ofTargets,pricesmaps a model to(input, output)dollars per million tokens.
Refuse to start (raise ValueError with a clear message) when a route names an unknown upstream or is not "upstream/model", when a team uses an unknown route, or when a routed model has no price. A config mistake should stop the gateway at startup, not fail a request at 3 a.m.
errors.py: GatewayError(status, message, type_="invalid_request_error", code=None, headers=None), an exception, and error_response(err), which turns it into the JSON every OpenAI-compatible API uses: {"error": {"message": ..., "type": ..., "code": ...}}. That shape is what makes the SDK raise the right class (NotFoundError for 404, AuthenticationError for 401, RateLimitError for 429), so apps' existing error handling keeps working.
upstream.py: Upstreams(upstreams, transport=None) creates one pooled httpx2.AsyncClient per upstream, with the upstream's base_url, an Authorization: Bearer <its api_key> header, its timeout, and the given transport (tests pass a fake one). await chat(target, body) POSTs to /chat/completions with model replaced by the target's model. It raises UpstreamError(target, kind, message, status=None) for failures that are not the caller's fault: kind is "timeout" (any httpx2.TimeoutException), "connect" (any other httpx2.TransportError), "auth" (the upstream answered 401 or 403: the gateway's key is wrong) or "status" (429 or 5xx). Any other answer (200, or a 4xx like 400 for a bad request) is returned as it is. await models(name) returns the ids from the upstream's GET /models. await aclose() closes the clients.
app.py: create_app(*, transport=None, clock=time.time) -> FastAPI builds everything from settings() and load_config(). The clock is for later milestones (rate limits, budgets, the cache); accept it now, because the tests pass a fake one. Close the upstream clients on shutdown (a FastAPI lifespan). The endpoints:
GET /healthreturns{"status": "ok"}.GET /health/upstreamsasks every upstream for its/modelsat the same time and returns{"status": "ok" | "degraded", "upstreams": {"ollama": {"ok": true, "models": [...], "missing": [...]}, "hosted": {"ok": false, "error": "ConnectError"}}}.missinglists the models your routes use that the upstream does not serve (a model you forgot to pull). Any problem makes the statusdegraded.GET /v1/modelslists the route names in the OpenAI shape:{"object": "list", "data": [{"id": "fast", "object": "model", "created": 0, "owned_by": "llm-gateway"}, ...]}.POST /v1/chat/completionschecks the body with a Pydantic model (model: a non-empty string;messages: a non-empty list of objects;stream: bool, default false) that allows extra fields, becausetemperature,max_tokens,toolsand the rest must reach the upstream untouched. An unknown model is 404 with codemodel_not_found(the message lists the aliases you may use). A body that fails validation is 400invalid_request_error(FastAPI says 422 by default; OpenAI clients expect 400). It sends the request to the first target of the route and returns the upstream's JSON with a headerx-gateway-upstream: ollama/llama3.2:3b. An upstream 4xx is passed through unchanged; anUpstreamErrorbecomes 504 for a timeout and 502 otherwise, with codeupstream_<kind>. A request with"stream": truecan answer 400 for now: that is milestone 2.
Finally try_gateway.py, an "app": the normal openai SDK with base_url from GATEWAY_URL (default http://localhost:8080/v1) and api_key from GATEWAY_KEY. It lists the models, asks one question at temperature 0 with with_raw_response (so it can print the x-gateway-upstream header), and prints the answer and the token usage. Catch openai.APIStatusError and openai.APIConnectionError and print a one-line message instead of a stack trace.
Run it. Keep the gateway running in a second terminal, in the project folder: uv run uvicorn --factory app:create_app --port 8080 --reload. --factory tells uvicorn to call create_app() to get the app; --reload restarts it each time you save a .py file, so you can leave it running through the next milestones (restart it by hand after changing gateway.toml or .env).
uv run python --versionprintsPython 3.12.x.uv run pytest -q tests/test_m1.pypasses (14 tests).- With the gateway running,
uv run try_gateway.pyprintsmodels: ['fast', 'smart'], then[ollama/llama3.2:3b]and an answer from your model, then the token usage. uv run try_gateway.py --model smartprints a one-linegateway error: ... 502 ... cannot reach the upstream (ConnectError): the hosted upstream does not exist yet (milestone 5), and the gateway says so cleanly.
Hints
tomllib.load()needs the file opened in binary mode:with open(path, "rb") as f:."ollama/llama3.2:3b".partition("/")gives("ollama", "/", "llama3.2:3b"), and an empty middle part means there was no slash.ConfigDict(extra="allow")on the Pydantic model keeps unknown fields, andreq.model_dump(exclude_unset=True)gives back exactly what the caller sent (no"stream": falseadded). Then{**body, "model": target.model}swaps the alias for the real model name.- FastAPI lets you replace its validation error:
@app.exception_handler(RequestValidationError)returning aJSONResponse(..., status_code=400). Register a second handler forGatewayErrorthat returnserror_response(err). - For
/health/upstreams, write one smallasync def check(name)that catches every exception, and run them all withawait asyncio.gather(*(check(n) for n in cfg.upstreams)).httpx2.TimeoutExceptionis a subclass ofhttpx2.TransportError, so catch it first, just likeAPITimeoutErrorbeforeAPIConnectionErrorin lab 1.
Show the reference solution for milestone 1
Try it yourself first. This is one good way to do it, not the only one.
3.12 - Written by
uv init --python 3.12. Everyuv runin this folder uses Python 3.12, even when a newer one is installed.line 1
[project]
name = "llm-gateway"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.165.0",
"httpx2>=2.16.2",
"opentelemetry-api==1.45.2",
"opentelemetry-sdk==1.45.2",
"python-dotenv>=1.2.4",
"uvicorn>=0.55.0",
]
[dependency-groups]
dev = [
"openai>=3.60.0",
"pytest>=9.2.0",
]
[tool.pytest.ini_options]
pythonpath = [".", "tests"]
testpaths = ["tests"] - The async HTTP client for the upstream calls.
MockTransportfrom the same package is how the tests fake the upstreams.line 7 - Tracing (milestone 7). The API and the SDK are released together: pin both to the same version.line 8
- A dev dependency: only
try_gateway.pyand the tests use the SDK. The gateway speaks plain HTTP, so the Docker image in milestone 8 does not include it.line 16 - Added by hand: pytest reads its settings from this table.line 20
- The project folder (so tests can
import app) andtests(so they canimport fakes).line 21
# The gateway's own config: where requests go, who may call, and what things cost.
# Secrets are not in this file: upstream keys come from environment variables (api_key_env),
# and the gateway's API keys live in SQLite, hashed (milestone 3).
# ---- upstreams: the model servers behind the gateway (milestone 1) ----
# UPSTREAM_<NAME>_URL in the environment overrides base_url, e.g. UPSTREAM_OLLAMA_URL in Docker.
[upstreams.ollama]
base_url = "http://localhost:11434/v1"
api_key_env = "OLLAMA_API_KEY" # Ollama ignores keys; a hosted provider needs one
timeout_s = 60
[upstreams.hosted]
base_url = "http://localhost:9001/v1" # fake_hosted.py (milestone 5) stands in for a paid API
api_key_env = "HOSTED_API_KEY"
timeout_s = 30
# ---- routes: the model names apps use, each an ordered list of "upstream/model" targets ----
# Milestone 1 uses the first target. Milestone 5 falls back to the next one when a target fails.
[routes]
fast = ["ollama/llama3.2:3b", "hosted/hosted-small"]
smart = ["hosted/hosted-large", "ollama/llama3.2:3b"]
# ---- teams: who may use which routes, and how many tokens a day (milestones 3 and 4) ----
[teams.search]
models = ["fast", "smart"]
daily_token_budget = 200000
[teams.support]
models = ["fast"]
daily_token_budget = 50000
# ---- prices in US dollars per 1 million tokens (milestone 4). The hosted rows are EXAMPLES. ----
[prices]
"llama3.2:3b" = { input = 0.0, output = 0.0 }
"hosted-small" = { input = 0.15, output = 0.60 }
"hosted-large" = { input = 3.00, output = 15.00 }
# ---- limits, circuit breaker and cache (milestones 4, 5 and 6) ----
[limits]
default_max_tokens = 512 # reserved from the budget when a request does not set max_tokens
[breaker]
failures = 3 # consecutive failures that open a target's breaker
cooldown_s = 30 # how long it stays open before one trial request
[cache]
ttl_s = 300
max_entries = 1000 - Config files hold the defaults; the environment overrides them per machine. In Docker,
localhostis the container itself.line 6 - The **name** of a variable, not the key. Keys never go in a file you commit.line 9
- Apps ask for
fastorsmart, never for a vendor model. Changing whatsmartmeans is one line here, and no app changes.line 19 - An ordered list: the first target answers unless it fails (milestone 5).line 20
- Milestone 3: which routes a team may use. Milestone 4: how many tokens a day.line 24
- Milestone 4. The hosted prices are examples, not any provider's real prices. The local model is free, but it still needs a row:
load_configrefuses a routed model without a price.line 33 - Milestone 5: after 3 failures in a row, stop calling that target for 30 seconds.line 42
# The gateway's settings. Apps do not read this file: they only need the gateway's URL and their key.
GATEWAY_CONFIG=gateway.toml
GATEWAY_DB=gateway.db
# Keys the gateway sends to each upstream (api_key_env in gateway.toml). Ollama ignores its key.
OLLAMA_API_KEY=ollama
HOSTED_API_KEY=fake-hosted-key
# The key for /admin/* (milestone 4). Empty turns the admin endpoints off. Use a long random value.
ADMIN_KEY=change-me-to-a-long-random-string
# Logs and traces (milestone 7). LOG_PROMPTS=true adds a redacted preview of the last user message.
LOG_FILE=gateway.log
LOG_PROMPTS=false
TRACE_EXPORTER=none - One SQLite file for the API keys (milestone 3) and the usage rows (milestone 4).line 3
- The key the gateway sends to the hosted upstream. The fake one in milestone 5 checks it.line 7
- Protects
/admin/*(milestone 4). It is not a team key: teams must not see each other's usage.line 10
.venv/
__pycache__/
.env
*.db
*.log - The keys and the usage are data, not code.
*.log: the logs too.line 4
import os
import tomllib
from dataclasses import dataclass
from pathlib import Path
from dotenv import load_dotenv
HERE = Path(__file__).resolve().parent
load_dotenv(HERE / ".env") # read .env next to this file (real env vars win)
def _path(name: str, default: str) -> Path:
"""A file path from the environment; relative paths are relative to the project folder."""
p = Path(os.environ.get(name, default))
return p if p.is_absolute() else HERE / p
@dataclass(frozen=True)
class Settings:
config_file: Path
db_path: Path
admin_key: str
log_file: Path
log_prompts: bool
trace_exporter: str
def settings() -> Settings:
return Settings(
config_file=_path("GATEWAY_CONFIG", "gateway.toml"),
db_path=_path("GATEWAY_DB", "gateway.db"),
admin_key=os.environ.get("ADMIN_KEY", ""),
log_file=_path("LOG_FILE", "gateway.log"),
log_prompts=os.environ.get("LOG_PROMPTS", "false").lower() == "true",
trace_exporter=os.environ.get("TRACE_EXPORTER", "none"),
)
# ---------------------------------------------------------------- gateway.toml
@dataclass(frozen=True)
class Upstream:
name: str
base_url: str
api_key: str
timeout_s: float
@dataclass(frozen=True)
class Target:
upstream: str
model: str
def __str__(self) -> str:
return f"{self.upstream}/{self.model}"
@dataclass(frozen=True)
class Team:
name: str
models: tuple[str, ...]
daily_token_budget: int
@dataclass(frozen=True)
class GatewayConfig:
upstreams: dict[str, Upstream]
routes: dict[str, tuple[Target, ...]]
teams: dict[str, Team]
prices: dict[str, tuple[float, float]] # model -> (input, output) USD per 1M tokens
default_max_tokens: int = 512
breaker_failures: int = 3
breaker_cooldown_s: float = 30.0
cache_ttl_s: float = 300.0
cache_max_entries: int = 1000
def load_config(path: Path) -> GatewayConfig:
"""Read gateway.toml and check that every route and team points at something that exists."""
with open(path, "rb") as f:
raw = tomllib.load(f)
upstreams = {}
for name, u in raw.get("upstreams", {}).items():
base_url = os.environ.get(f"UPSTREAM_{name.upper()}_URL", u["base_url"])
api_key = os.environ.get(u.get("api_key_env", ""), "") or "none"
upstreams[name] = Upstream(name, base_url.rstrip("/"), api_key, float(u.get("timeout_s", 60)))
routes = {}
for alias, targets in raw.get("routes", {}).items():
parsed = []
for t in targets:
upstream, sep, model = t.partition("/")
if not sep or upstream not in upstreams:
raise ValueError(f"route {alias!r}: {t!r} must look like 'upstream/model' with a known upstream")
parsed.append(Target(upstream, model))
if not parsed:
raise ValueError(f"route {alias!r} has no targets")
routes[alias] = tuple(parsed)
teams = {}
for name, t in raw.get("teams", {}).items():
unknown = [m for m in t.get("models", []) if m not in routes]
if unknown:
raise ValueError(f"team {name!r} uses unknown routes: {unknown}")
teams[name] = Team(name, tuple(t.get("models", [])), int(t.get("daily_token_budget", 0)))
prices = {m: (float(p["input"]), float(p["output"])) for m, p in raw.get("prices", {}).items()}
unpriced = sorted({t.model for ts in routes.values() for t in ts} - prices.keys())
if unpriced:
raise ValueError(f"no price for {unpriced}: add them to [prices] (0.0 for a free local model)")
limits, breaker, cache = raw.get("limits", {}), raw.get("breaker", {}), raw.get("cache", {})
return GatewayConfig(
upstreams=upstreams,
routes=routes,
teams=teams,
prices=prices,
default_max_tokens=int(limits.get("default_max_tokens", 512)),
breaker_failures=int(breaker.get("failures", 3)),
breaker_cooldown_s=float(breaker.get("cooldown_s", 30)),
cache_ttl_s=float(cache.get("ttl_s", 300)),
cache_max_entries=int(cache.get("max_entries", 1000)),
) - Reads
.envnext to this file, wherever you start the program from. Variables already set in your shell win.line 9 @dataclasswrites the constructor, like a Java record.frozen=Truemakes it read-only.line 18- Environment variables are always strings:
"false"is a non-empty string, so it would be truthy. Compare explicitly.line 34 str(target)isollama/llama3.2:3b: the name used in headers, usage rows, breakers and logs.line 55tomllibis in the standard library since Python 3.11. It reads TOML into plain dicts and lists.line 82- An f-string inside a call: the variable name is built from the upstream's name.line 86
- Split at the **first** slash only, so a model name may contain slashes (
Qwen/Qwen2.5-1.5B-Instructon vLLM).line 94 - A set difference: routed models minus priced models. Without a price the gateway cannot bill, so it refuses to start.line 110
from fastapi.responses import JSONResponse
class GatewayError(Exception):
"""An error the caller should see, in the same JSON shape as the OpenAI API, so SDKs raise the right class."""
def __init__(self, status: int, message: str, type_: str = "invalid_request_error",
code: str | None = None, headers: dict[str, str] | None = None):
super().__init__(message)
self.status, self.message, self.type, self.code = status, message, type_, code
self.headers = headers or {}
def error_body(message: str, type_: str, code: str | None = None) -> dict:
return {"error": {"message": message, "type": type_, "code": code}}
def error_response(err: GatewayError) -> JSONResponse:
return JSONResponse(error_body(err.message, err.type, err.code), status_code=err.status, headers=err.headers) - Raise it anywhere in a request; one exception handler turns it into the response. Like a Spring
@ExceptionHandler.line 4 - The OpenAI error shape.
typeandcodeare what SDKs and app code check, so keep them stable.line 14
import httpx2
from config import Target, Upstream
class UpstreamError(Exception):
"""A failure another upstream might not have: no connection, a timeout, 401/403 (our key), 429 or 5xx."""
def __init__(self, target: Target, kind: str, message: str, status: int | None = None):
super().__init__(f"{target}: {message}")
self.target, self.kind, self.status = target, kind, status
class Upstreams:
"""One pooled HTTP client per upstream. Every call to a model server goes through here."""
def __init__(self, upstreams: dict[str, Upstream], transport: httpx2.AsyncBaseTransport | None = None):
self.clients = {
name: httpx2.AsyncClient(
base_url=u.base_url,
headers={"Authorization": f"Bearer {u.api_key}"},
timeout=httpx2.Timeout(u.timeout_s, connect=5.0),
transport=transport,
)
for name, u in upstreams.items()
}
async def chat(self, target: Target, body: dict) -> httpx2.Response:
"""POST /chat/completions with the upstream's own model name. Raises UpstreamError for failures that are
not the caller's fault; other answers (200, or a 4xx such as 400 for a bad request) are returned as they are."""
try:
resp = await self.clients[target.upstream].post("/chat/completions", json={**body, "model": target.model})
except httpx2.TimeoutException as e: # before TransportError: it is a subclass
raise UpstreamError(target, "timeout", f"no answer in time ({type(e).__name__})") from e
except httpx2.TransportError as e:
raise UpstreamError(target, "connect", f"cannot reach the upstream ({type(e).__name__})") from e
if resp.status_code in (401, 403): # the gateway's own key for this upstream is wrong, not the caller's
raise UpstreamError(target, "auth", f"refused the gateway's key ({resp.status_code})", resp.status_code)
if resp.status_code == 429 or resp.status_code >= 500:
raise UpstreamError(target, "status", f"answered {resp.status_code}", resp.status_code)
return resp
async def models(self, name: str) -> list[str]:
"""The model ids an upstream serves (its own GET /models)."""
resp = await self.clients[name].get("/models")
resp.raise_for_status()
return [m["id"] for m in resp.json()["data"]]
async def aclose(self) -> None:
for client in self.clients.values():
await client.aclose() - Only for failures another upstream might not have. Milestone 5 falls back on exactly these.line 6
- One client per upstream, created once and reused: it keeps connections open (a pool), which saves a TCP and TLS handshake per request.line 19
- Up to
timeout_swaiting for the model, but only 5 seconds to connect: a server that is down fails fast.line 22 Nonemeans real network. The tests pass aMockTransport, so every upstream call goes to a Python function instead.line 23{**body, ...}copies the caller's body and replaces one key, like{...body, model}in JavaScript.line 32- Before
TransportError, which it is a subclass of: Python uses the firstexceptthat matches.line 33 - The upstream refused **our** key. Passing a 401 to the app would make it think its own gateway key is wrong.line 37
- 429 here is the provider limiting the gateway, not the caller: another upstream may still have room.line 39
import asyncio
import time
from contextlib import asynccontextmanager
from typing import Any, Callable
import httpx2
from fastapi import FastAPI, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, ConfigDict, Field
from config import Target, load_config, settings
from errors import GatewayError, error_body, error_response
from upstream import UpstreamError, Upstreams
class ChatRequest(BaseModel):
"""What the gateway checks. Every other field (temperature, max_tokens, tools...) is passed through."""
model_config = ConfigDict(extra="allow")
model: str = Field(min_length=1)
messages: list[dict[str, Any]] = Field(min_length=1)
stream: bool = False
def create_app(*, transport: httpx2.AsyncBaseTransport | None = None,
clock: Callable[[], float] = time.time) -> FastAPI:
"""Build the gateway. Tests pass a fake transport (the upstreams) and a fake clock (used from milestone 3)."""
cfg = load_config(settings().config_file)
upstreams = Upstreams(cfg.upstreams, transport)
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await upstreams.aclose() # close the pooled connections on shutdown
app = FastAPI(title="LLM gateway", lifespan=lifespan)
@app.exception_handler(GatewayError)
async def gateway_error(request: Request, err: GatewayError):
return error_response(err)
@app.exception_handler(RequestValidationError)
async def bad_request(request: Request, err: RequestValidationError):
first = err.errors()[0]
where = ".".join(str(p) for p in first["loc"] if p != "body")
return JSONResponse(error_body(f"{where}: {first['msg']}", "invalid_request_error"), status_code=400)
def route(alias: str) -> tuple[Target, ...]:
if alias not in cfg.routes:
raise GatewayError(404, f"model '{alias}' does not exist; use one of: {', '.join(cfg.routes)}",
code="model_not_found")
return cfg.routes[alias]
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/health/upstreams")
async def health_upstreams():
"""Ask every upstream for its models (GET /models) and say which routed models are missing."""
async def check(name: str) -> dict:
wanted = sorted({t.model for ts in cfg.routes.values() for t in ts if t.upstream == name})
try:
served = await upstreams.models(name)
except Exception as e:
return {"ok": False, "error": type(e).__name__}
return {"ok": True, "models": served, "missing": [m for m in wanted if m not in served]}
results = await asyncio.gather(*(check(n) for n in cfg.upstreams))
report = dict(zip(cfg.upstreams, results))
healthy = all(r["ok"] and not r["missing"] for r in report.values())
return {"status": "ok" if healthy else "degraded", "upstreams": report}
@app.get("/v1/models")
async def list_models():
return {"object": "list",
"data": [{"id": alias, "object": "model", "created": 0, "owned_by": "llm-gateway"} for alias in cfg.routes]}
@app.post("/v1/chat/completions")
async def chat(req: ChatRequest):
if req.stream:
raise GatewayError(400, "streaming is not supported yet")
target = route(req.model)[0]
body = req.model_dump(exclude_unset=True)
try:
resp = await upstreams.chat(target, body)
except UpstreamError as e:
status = 504 if e.kind == "timeout" else 502
raise GatewayError(status, str(e), "upstream_error", code=f"upstream_{e.kind}") from e
headers = {"x-gateway-upstream": str(target)}
if resp.status_code != 200: # the upstream refused the request itself (a 4xx): pass it on unchanged
return Response(resp.content, resp.status_code, headers=headers,
media_type=resp.headers.get("content-type", "application/json"))
return JSONResponse(resp.json(), headers=headers)
return app - Checks only what the gateway needs. Everything else in the body is the upstream's business.line 17
- Keep unknown fields (
temperature,tools,response_format...) instead of dropping them.line 20 - A factory instead of a global
app: each test builds its own gateway with its own fake upstreams, database and clock.line 26 - Code before
yieldruns at startup, code after it at shutdown.line 33 - Turn FastAPI's 422 into the 400 and error shape OpenAI clients expect.line 43
- A readiness check: is every upstream reachable, and does it serve the models the routes need?
/healthalone only says the process is alive.line 60 - Runs the checks at the same time, like
Promise.allin JavaScript: the slowest upstream sets the time, not the sum.line 70 - Only the fields the caller sent, extras included.line 85
- A 400 from the upstream (a bad request) is the caller's to fix. Pass it on as it is.line 92
"""An "app" that uses the gateway: the normal openai SDK, with the gateway's URL and a gateway key."""
import argparse
import os
import sys
import openai
from openai import OpenAI
def main() -> None:
parser = argparse.ArgumentParser(description="Ask the gateway one question.")
parser.add_argument("question", nargs="?", default="In one sentence, what is an API gateway?")
parser.add_argument("--model", default="fast")
args = parser.parse_args()
client = OpenAI(base_url=os.environ.get("GATEWAY_URL", "http://localhost:8080/v1"),
api_key=os.environ.get("GATEWAY_KEY", "no-key-yet"), max_retries=0)
try:
print("models:", [m.id for m in client.models.list()])
raw = client.chat.completions.with_raw_response.create(
model=args.model, messages=[{"role": "user", "content": args.question}], temperature=0)
except openai.APIStatusError as e: # the gateway answered with an error: show its message
sys.exit(f"gateway error: {e.message}")
except openai.APIConnectionError:
sys.exit("cannot reach the gateway: is it running? (uv run uvicorn --factory app:create_app --port 8080)")
reply = raw.parse()
print(f"[{raw.headers.get('x-gateway-upstream')}]", reply.choices[0].message.content)
print(f"usage: {reply.usage.prompt_tokens} in, {reply.usage.completion_tokens} out")
if __name__ == "__main__":
main() - The only change an app makes to use the gateway: the base URL and the key.line 16
- Returns the HTTP response too, so you can read headers;
.parse()gives the usual typed object.line 20 - The gateway answered with an error status.
e.messageholds the gateway's own message.line 22
import os
from dataclasses import dataclass
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from fakes import TEST_TOML, FakeClock, FakeUpstream, FakeUpstreams
# Set before any test builds the gateway, so tests never use your .env values.
os.environ["ADMIN_KEY"] = "admin-test-key"
os.environ["TRACE_EXPORTER"] = "none"
os.environ["LOG_PROMPTS"] = "false"
os.environ["TEST_OLLAMA_KEY"] = "ollama-upstream-key"
os.environ["TEST_HOSTED_KEY"] = "hosted-upstream-key"
@dataclass
class Gateway:
app: object
client: TestClient # sends this test's API key on every request
key: str
ollama: FakeUpstream
hosted: FakeUpstream
clock: FakeClock
db_path: Path
log_file: Path
def chat(self, model: str = "fast", content: str = "Hi", **extra):
return self.client.post("/v1/chat/completions",
json={"model": model, "messages": [{"role": "user", "content": content}], **extra})
def new_key(self, team: str = "search", **limits) -> str:
"""Another API key (milestone 3 on)."""
from keys import KeyStore
return KeyStore(self.db_path).create(team, "test", **limits)
@pytest.fixture
def gateway(tmp_path, monkeypatch):
"""make_gateway(toml=..., **create_app_kwargs) builds a gateway in front of two fake upstreams."""
opened = []
def make(toml: str = TEST_TOML, team: str = "search", **app_kwargs) -> Gateway:
(tmp_path / "gateway.toml").write_text(toml)
monkeypatch.setenv("GATEWAY_CONFIG", str(tmp_path / "gateway.toml"))
monkeypatch.setenv("GATEWAY_DB", str(tmp_path / "gateway.db"))
monkeypatch.setenv("LOG_FILE", str(tmp_path / "gateway.log"))
from app import create_app
fakes, clock = FakeUpstreams(), FakeClock()
app = create_app(transport=fakes.transport(), clock=clock, **app_kwargs)
client = TestClient(app)
client.__enter__() # runs the app's startup; the fixture runs its shutdown after the test
opened.append(client)
gw = Gateway(app, client, "", fakes.ollama, fakes.hosted, clock, tmp_path / "gateway.db", tmp_path / "gateway.log")
try:
gw.key = gw.new_key(team, rpm=100_000, burst=100_000)
except ModuleNotFoundError: # milestones 1 and 2: no keys.py yet, any key will do
gw.key = "gw-no-keys-yet"
client.headers["Authorization"] = f"Bearer {gw.key}"
return gw
yield make
for client in opened:
client.__exit__(None, None, None) - Set before any test builds the gateway, so tests never use the values in your
.env.line 11 - What each test gets: the app, a
TestClientthat sends the test's key, both fake upstreams, the fake clock and the file paths.line 19 - Milestone 3 on. Imported inside the function, so this file works before
keys.pyexists.line 33 - A fixture that returns a function:
gateway()builds a gateway,gateway(team="support")one whose key belongs to another team.line 41 - Each test has its own config, database and log in a temporary folder (
tmp_path).line 47 - Starts the app (runs the lifespan) the way
with TestClient(app) as client:does. The fixture shuts it down after the test.line 55 - Milestones 1 and 2 have no API keys yet, so any key is accepted.line 60
"""Test helpers: fake upstreams (OpenAI-compatible model servers), a fake clock, and the test config."""
import json
import httpx2
# The config every test uses unless it passes its own: two upstreams on fake hosts, two routes, two teams.
TEST_TOML = """
[upstreams.ollama]
base_url = "http://ollama.test/v1"
api_key_env = "TEST_OLLAMA_KEY"
timeout_s = 5
[upstreams.hosted]
base_url = "http://hosted.test/v1"
api_key_env = "TEST_HOSTED_KEY"
timeout_s = 5
[routes]
fast = ["ollama/llama3.2:3b", "hosted/hosted-small"]
smart = ["hosted/hosted-large", "ollama/llama3.2:3b"]
[teams.search]
models = ["fast", "smart"]
daily_token_budget = 10000
[teams.support]
models = ["fast"]
daily_token_budget = 1000
[prices]
"llama3.2:3b" = { input = 0.0, output = 0.0 }
"hosted-small" = { input = 0.15, output = 0.60 }
"hosted-large" = { input = 3.00, output = 15.00 }
[limits]
default_max_tokens = 100
[breaker]
failures = 2
cooldown_s = 30
[cache]
ttl_s = 60
max_entries = 3
"""
START = 1795176000.0 # 2026-11-20 12:00:00 UTC
class FakeClock:
"""time.time() that only moves when a test says so."""
def __init__(self, t: float = START):
self.t = t
def __call__(self) -> float:
return self.t
def advance(self, seconds: float) -> None:
self.t += seconds
class FakeUpstream:
"""One fake model server. Records every request; answers like an OpenAI-compatible API.
Set .fail to make it fail: an HTTP status (500, 503, 429, 400...), "timeout" or "connect".
Set .break_stream_after to cut a stream after that many content chunks.
Set .message to answer with that assistant message instead (for example one with tool_calls)."""
def __init__(self, name: str, models: list[str], words: list[str] | None = None,
prompt_tokens: int = 20, completion_tokens: int = 5):
self.name, self.models = name, models
self.words = words or ["Hello", " from", f" {name}", "."]
self.prompt_tokens, self.completion_tokens = prompt_tokens, completion_tokens
self.fail: int | str | None = None
self.break_stream_after: int | None = None
self.message: dict | None = None
self.requests: list[dict] = [] # JSON bodies of chat requests, in order
self.headers: list[dict] = [] # their headers
@property
def calls(self) -> int:
return len(self.requests)
def handle(self, request: httpx2.Request) -> httpx2.Response:
if request.method == "GET" and request.url.path.endswith("/models"):
return httpx2.Response(200, json={"object": "list", "data": [{"id": m, "object": "model"} for m in self.models]})
body = json.loads(request.content)
self.requests.append(body)
self.headers.append(dict(request.headers))
if self.fail == "timeout":
raise httpx2.ReadTimeout("fake timeout", request=request)
if self.fail == "connect":
raise httpx2.ConnectError("fake connection refused", request=request)
if isinstance(self.fail, int):
return httpx2.Response(self.fail, json={"error": {"message": f"{self.name} says {self.fail}", "type": "server_error"}})
if body.get("stream"):
return httpx2.Response(200, headers={"content-type": "text/event-stream"}, content=self._sse(body))
return httpx2.Response(200, json=self.reply(body))
def usage(self) -> dict:
return {"prompt_tokens": self.prompt_tokens, "completion_tokens": self.completion_tokens,
"total_tokens": self.prompt_tokens + self.completion_tokens}
def reply(self, body: dict) -> dict:
return {"id": "chatcmpl-fake", "object": "chat.completion", "created": 0, "model": body["model"],
"choices": [{"index": 0, "message": self.message or {"role": "assistant", "content": "".join(self.words)},
"finish_reason": "tool_calls" if self.message and self.message.get("tool_calls") else "stop"}],
"usage": self.usage()}
async def _sse(self, body: dict):
def chunk(delta: dict, finish=None) -> bytes:
data = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": 0, "model": body["model"],
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}]}
return f"data: {json.dumps(data)}\n\n".encode()
yield chunk({"role": "assistant", "content": ""})
for i, w in enumerate(self.words):
if self.break_stream_after is not None and i >= self.break_stream_after:
raise httpx2.ReadError("fake: connection lost mid-stream")
yield chunk({"content": w})
yield chunk({}, "stop")
if (body.get("stream_options") or {}).get("include_usage"):
usage = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": 0, "model": body["model"],
"choices": [], "usage": self.usage()}
yield f"data: {json.dumps(usage)}\n\n".encode()
yield b"data: [DONE]\n\n"
class FakeUpstreams:
"""Both fake servers behind one httpx2 transport. The gateway's requests are routed by host name."""
def __init__(self):
self.ollama = FakeUpstream("ollama", ["llama3.2:3b"])
self.hosted = FakeUpstream("hosted", ["hosted-small", "hosted-large"], prompt_tokens=1000, completion_tokens=200)
def handler(self, request: httpx2.Request) -> httpx2.Response:
server = {"ollama.test": self.ollama, "hosted.test": self.hosted}[request.url.host]
return server.handle(request)
def transport(self) -> httpx2.MockTransport:
return httpx2.MockTransport(self.handler)
def sse_events(text: str) -> list:
"""The data of every Server-Sent Event in a response body: parsed JSON, or the string "[DONE]"."""
out = []
for line in text.splitlines():
if line.startswith("data: "):
data = line[len("data: "):]
out.append(data if data == "[DONE]" else json.loads(data))
return out - The test config: small budgets and a tiny cache, so tests can reach the limits with a few requests.line 7
time.time()that only moves when a test callsadvance(). Rate limits, budgets, breakers and the cache all read the clock they are given.line 50- An OpenAI-compatible server as a plain function. It records every request so tests can check what the gateway sent.line 63
- Raising the exception httpx2 would raise is how you fake a slow or dead server without waiting.line 90
- A streamed answer, exactly as the API sends it:
data: {json}lines, a final usage chunk when asked, thendata: [DONE].line 110 - A connection that dies in the middle of an answer (milestone 2).line 119
- Both servers behind one transport: the gateway's request goes to whichever host it names,
ollama.testorhosted.test.line 129
"""Milestone 1: a pass-through proxy. Routes resolve to an upstream model, errors look like OpenAI errors."""
import httpx2
import openai
import pytest
def test_chat_is_forwarded_to_the_first_target(gateway):
gw = gateway()
r = gw.chat("fast", "What is a hash map?", temperature=0.2)
assert r.status_code == 200
assert r.json()["choices"][0]["message"]["content"] == "Hello from ollama."
assert r.headers["x-gateway-upstream"] == "ollama/llama3.2:3b"
sent = gw.ollama.requests[0]
assert sent["model"] == "llama3.2:3b" # the alias was replaced by the upstream's model name
assert sent["temperature"] == 0.2 # fields the gateway does not know are passed through
assert sent["messages"] == [{"role": "user", "content": "What is a hash map?"}]
def test_the_upstream_gets_its_own_key_not_the_callers(gateway):
gw = gateway()
gw.chat("smart")
assert gw.hosted.headers[0]["authorization"] == "Bearer hosted-upstream-key"
assert gw.key not in str(gw.hosted.headers[0])
def test_tools_and_tool_calls_pass_through_untouched(gateway):
gw = gateway()
tools = [{"type": "function", "function": {"name": "lookup_order", "parameters": {"type": "object",
"properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}}}]
call = {"id": "call_1", "type": "function", "function": {"name": "lookup_order", "arguments": '{"order_id": "A1001"}'}}
gw.ollama.message = {"role": "assistant", "content": None, "tool_calls": [call]}
r = gw.chat("fast", "Where is order A1001?", tools=tools, tool_choice="auto")
assert gw.ollama.requests[0]["tools"] == tools and gw.ollama.requests[0]["tool_choice"] == "auto"
assert r.json()["choices"][0]["message"]["tool_calls"] == [call]
assert r.json()["choices"][0]["finish_reason"] == "tool_calls"
def test_unknown_model_is_404_in_openai_shape(gateway):
r = gateway().chat("gpt-99")
assert r.status_code == 404
err = r.json()["error"]
assert err["code"] == "model_not_found" and "fast" in err["message"]
def test_bad_body_is_400_in_openai_shape(gateway):
gw = gateway()
r = gw.client.post("/v1/chat/completions", json={"model": "fast", "messages": []})
assert r.status_code == 400
assert r.json()["error"]["type"] == "invalid_request_error"
assert gw.ollama.calls == 0
@pytest.mark.parametrize("fail, status, code", [(500, 502, "upstream_status"), (429, 502, "upstream_status"),
(401, 502, "upstream_auth"), ("connect", 502, "upstream_connect"),
("timeout", 504, "upstream_timeout")])
def test_upstream_failures_become_502_or_504(gateway, fail, status, code):
gw = gateway()
gw.ollama.fail = gw.hosted.fail = fail # both, so it holds after milestone 5's fallback too
r = gw.chat("fast")
assert r.status_code == status
assert r.json()["error"]["code"] == code
def test_a_4xx_from_the_upstream_is_passed_through(gateway):
gw = gateway()
gw.ollama.fail = 400
r = gw.chat("fast")
assert r.status_code == 400
assert r.json()["error"]["message"] == "ollama says 400"
assert gw.hosted.calls == 0 # a bad request is not retried elsewhere
def test_models_lists_the_routes(gateway):
r = gateway().client.get("/v1/models")
assert r.status_code == 200
assert [m["id"] for m in r.json()["data"]] == ["fast", "smart"]
def test_health_upstreams_proxies_each_upstreams_model_list(gateway):
gw = gateway()
gw.hosted.models = ["hosted-small"] # hosted-large is routed but not served
body = gw.client.get("/health/upstreams").json()
assert body["status"] == "degraded"
assert body["upstreams"]["ollama"]["ok"] and body["upstreams"]["ollama"]["missing"] == []
assert body["upstreams"]["hosted"]["missing"] == ["hosted-large"]
def test_the_openai_sdk_works_against_the_gateway(gateway):
gw = gateway()
# The SDK sends its requests through the gateway app instead of the network.
sdk = openai.OpenAI(base_url="http://gateway/v1", api_key=gw.key, max_retries=0, http_client=gw.client)
reply = sdk.chat.completions.create(model="fast", messages=[{"role": "user", "content": "Hi"}])
assert reply.choices[0].message.content == "Hello from ollama."
assert reply.usage.total_tokens == 25
with pytest.raises(openai.NotFoundError):
sdk.chat.completions.create(model="nope", messages=[{"role": "user", "content": "Hi"}]) - The gateway must not drop or change fields it does not know.line 15
- The app's key stays at the gateway; the provider only ever sees the gateway's key.line 19
- Tool calling must survive the proxy in both directions. Whether a small model **uses** the tools well is the app's problem (the support agent capstone checks it in code); the gateway must not make it worse.line 26
- Both upstreams fail, so this test still holds after milestone 5 adds fallback.line 58
- The real openai SDK, sending its requests into the gateway app through the
TestClient. If this passes, apps can use the gateway.line 91
uv init --python 3.12 llm-gateway
cd llm-gateway
rm main.py
uv add fastapi uvicorn httpx2 python-dotenv opentelemetry-api==1.45.2 opentelemetry-sdk==1.45.2
uv add --dev pytest openai
uv run python --version
uv run pytest -q tests/test_m1.py
uv run try_gateway.py
uv run try_gateway.py --model smart Initialized project `llm-gateway` at `.../llm-gateway` Using CPython 3.12.13 Creating virtual environment at: .venv Resolved 22 packages in 16ms Installed 20 packages in 17ms + fastapi==0.165.0 + httpx2==2.16.2 + opentelemetry-api==1.45.2 + opentelemetry-sdk==1.45.2 + uvicorn==0.55.0 ... + openai==3.60.0 + pytest==9.2.0 Python 3.12.13 .............. [100%] 14 passed in 0.93s models: ['fast', 'smart'] [ollama/llama3.2:3b] An API gateway is a single entry point that receives client requests and routes them to the right backend services. usage: 38 in, 24 out models: ['fast', 'smart'] gateway error: Error code: 502 - hosted/hosted-large: cannot reach the upstream (ConnectError)
smart should mean a different provider, you change one line in gateway.toml. The two error types (the caller's 4xx passed through, the upstream's failure turned into 502 or 504) are the base of everything that follows: milestone 5 falls back on exactly the second kind.Stuck on this milestone?
uv: command not found- Run
export PATH="$HOME/.local/bin:$PATH"(macOS and Linux), or open a new terminal so the installer's PATH change applies. uv run python --versionprints 3.13, 3.14 or 3.15- The project was created without
--python 3.12. Runuv python pin 3.12(it writes.python-version), thenuv sync. ModuleNotFoundError: No module named 'fakes'(or'app') in pytest- The
[tool.pytest.ini_options]table withpythonpath = [".", "tests"]is missing frompyproject.toml, or you ran pytest from another folder. ERROR: Error loading ASGI app. Attribute "create_app" not found in module "app", or uvicorn says the app is not callable- The module must define
create_app, and the command needs--factory: without it, uvicorn treatscreate_appitself as the app. - Every request is 502
upstream_connectalthough Ollama runs - Check
curl -s localhost:11434/v1/models. If Ollama runs on another machine or port, setUPSTREAM_OLLAMA_URL=http://host:port/v1in.envand restart the gateway:--reloadonly watches.pyfiles. - Windows:
rm main.pyfails - In PowerShell use
Remove-Item main.py.
Streaming: pass every event through as it arrives
With `"stream": true`, the caller gets the upstream's Server-Sent Events one by one, the gateway always learns the token usage, and failures before and during the stream are handled differently.
A streamed answer is a normal HTTP response that stays open: the upstream writes data: {json chunk} lines, each followed by a blank line, as tokens are generated, and ends with data: [DONE]. Each chunk has choices[0].delta.content, a few characters of the answer. The gateway must forward each event when it arrives, not collect the whole answer first, or the app loses the reason it streamed.
upstream.py: add await open_stream(target, body) -> httpx2.Response. Build the request with client.build_request(...) and send it with client.send(request, stream=True): that returns as soon as the status and headers arrive, with the body still unread. Map exceptions to UpstreamError exactly like chat(). When the status is not 200, read the (small) error body, close the response, and raise UpstreamError for 401, 403, 429 and 5xx; return any other 4xx response (already read) so the app can pass it on. A 200 response is returned open: whoever reads it must close it.
streaming.py: a dataclass StreamStats (usage: dict | None, chars: int, chunks: int, finished: bool, error: str | None) and an async generator relay(resp, stats, keep_usage_chunk) that reads the upstream with resp.aiter_lines() and yields strings to send to the caller:
- skip lines that do not start with
data:(the blank separators, and: keep-alivecomments some servers send); - for
[DONE]: setfinished, yield it, stop; - otherwise parse the JSON, add the length of every
delta.contenttochars, rememberusagewhen the chunk has one, and yield the original data asdata: <json>\n\n; - a chunk with
usageand an emptychoiceslist is only passed on whenkeep_usage_chunkis true; - if reading fails with an
httpx2.TransportError(the upstream died mid-answer), seterrorand yield one last event in the error shape,{"error": {..., "code": "upstream_stream_broken"}}. The 200 status is already sent, so this is the only way left to tell the caller; - close the upstream response in a
finally, so it is also closed when the caller hangs up.
app.py: when stream is true, add "stream_options": {"include_usage": true} to the body sent upstream (keep any other stream_options the caller sent). With it, OpenAI-compatible servers, Ollama included, send one extra chunk at the end with the token counts and no choices; the gateway needs those numbers in milestone 4. Remember whether the caller asked for it: if not, relay drops that chunk, because app code that reads chunk.choices[0] on every chunk crashes on an empty list. Never add stream_options to a request that does not stream (OpenAI rejects it). Then return a StreamingResponse(relay(...), media_type="text/event-stream") with the x-gateway-upstream header, Cache-Control: no-cache and X-Accel-Buffering: no (which tells nginx-style proxies not to buffer the stream). A failure before the stream starts is the same JSON error as in milestone 1.
try_gateway.py: add --stream, which prints each delta.content as it arrives (print(..., end="", flush=True)). Skip chunks whose choices list is empty.
uv run pytest -q tests/test_m1.py tests/test_m2.pypasses (21 tests).uv run try_gateway.py --streamprints the answer word by word, not all at once.curl -sNto/v1/chat/completionswith"stream": true(the command below) printsdata: {...}lines and ends withdata: [DONE].
Hints
- Starlette sends each string your async generator yields as soon as it is yielded. So
relayonly has toyieldinside theasync forloop: no buffering, no threads. async for line in resp.aiter_lines()gives you the body line by line, without the line endings. A line isdata: {...},data: [DONE]or empty.- Pass the upstream's JSON text on as it is (
yield f"data: {data}\n\n") instead ofjson.dumps(chunk)again: cheaper, and nothing changes by accident. - To test the mid-stream break,
FakeUpstream.break_stream_after = 2makes the fake raisehttpx2.ReadErrorafter two content chunks.except httpx2.TransportErrorcatches it.
Show the reference solution for milestone 2
Try it yourself first. This is one good way to do it, not the only one.
import httpx2
from config import Target, Upstream
class UpstreamError(Exception):
"""A failure another upstream might not have: no connection, a timeout, 401/403 (our key), 429 or 5xx."""
def __init__(self, target: Target, kind: str, message: str, status: int | None = None):
super().__init__(f"{target}: {message}")
self.target, self.kind, self.status = target, kind, status
class Upstreams:
"""One pooled HTTP client per upstream. Every call to a model server goes through here."""
def __init__(self, upstreams: dict[str, Upstream], transport: httpx2.AsyncBaseTransport | None = None):
self.clients = {
name: httpx2.AsyncClient(
base_url=u.base_url,
headers={"Authorization": f"Bearer {u.api_key}"},
timeout=httpx2.Timeout(u.timeout_s, connect=5.0),
transport=transport,
)
for name, u in upstreams.items()
}
async def chat(self, target: Target, body: dict) -> httpx2.Response:
"""POST /chat/completions with the upstream's own model name. Raises UpstreamError for failures that are
not the caller's fault; other answers (200, or a 4xx such as 400 for a bad request) are returned as they are."""
try:
resp = await self.clients[target.upstream].post("/chat/completions", json={**body, "model": target.model})
except httpx2.TimeoutException as e: # before TransportError: it is a subclass
raise UpstreamError(target, "timeout", f"no answer in time ({type(e).__name__})") from e
except httpx2.TransportError as e:
raise UpstreamError(target, "connect", f"cannot reach the upstream ({type(e).__name__})") from e
if resp.status_code in (401, 403): # the gateway's own key for this upstream is wrong, not the caller's
raise UpstreamError(target, "auth", f"refused the gateway's key ({resp.status_code})", resp.status_code)
if resp.status_code == 429 or resp.status_code >= 500:
raise UpstreamError(target, "status", f"answered {resp.status_code}", resp.status_code)
return resp
async def open_stream(self, target: Target, body: dict) -> httpx2.Response:
"""Start a streaming POST /chat/completions and return as soon as the status and headers arrive.
A 200 response is still open: the caller reads it line by line and must close it (aclose)."""
client = self.clients[target.upstream]
request = client.build_request("POST", "/chat/completions", json={**body, "model": target.model})
try:
resp = await client.send(request, stream=True)
except httpx2.TimeoutException as e:
raise UpstreamError(target, "timeout", f"no answer in time ({type(e).__name__})") from e
except httpx2.TransportError as e:
raise UpstreamError(target, "connect", f"cannot reach the upstream ({type(e).__name__})") from e
if resp.status_code != 200:
await resp.aread() # an error body is small: read it, then close the connection
await resp.aclose()
if resp.status_code in (401, 403):
raise UpstreamError(target, "auth", f"refused the gateway's key ({resp.status_code})", resp.status_code)
if resp.status_code == 429 or resp.status_code >= 500:
raise UpstreamError(target, "status", f"answered {resp.status_code}", resp.status_code)
return resp
async def models(self, name: str) -> list[str]:
"""The model ids an upstream serves (its own GET /models)."""
resp = await self.clients[name].get("/models")
resp.raise_for_status()
return [m["id"] for m in resp.json()["data"]]
async def aclose(self) -> None:
for client in self.clients.values():
await client.aclose() - The streaming twin of
chat(). It returns at the headers, so the gateway can still fall back (milestone 5) if the status is an error.line 43 post()would read the whole body before returning.build_request+send(stream=True)returns at the headers, with the body still on the wire.line 47- An error body is small and needed (to pass a 400 on): read it, then close.line 55
import json
from collections.abc import AsyncIterator
from dataclasses import dataclass
import httpx2
from errors import error_body
@dataclass
class StreamStats:
"""What the gateway learns while a stream passes through."""
usage: dict | None = None # the upstream's usage chunk, when it sends one
chars: int = 0 # characters of answer text, for an estimate when there is no usage
chunks: int = 0
finished: bool = False # saw [DONE]
error: str | None = None # set when the upstream broke off mid-answer
def sse(data: str) -> str:
"""One Server-Sent Event: a data line, then a blank line."""
return f"data: {data}\n\n"
async def relay(resp: httpx2.Response, stats: StreamStats, keep_usage_chunk: bool) -> AsyncIterator[str]:
"""Pass the upstream's events to the caller one by one, as they arrive, and note the usage on the way."""
try:
async for line in resp.aiter_lines():
if not line.startswith("data:"):
continue # blank separators, ": keep-alive" comments
data = line[len("data:"):].strip()
if data == "[DONE]":
stats.finished = True
yield sse("[DONE]")
break
chunk = json.loads(data)
if chunk.get("usage"):
stats.usage = chunk["usage"]
if not chunk.get("choices") and not keep_usage_chunk:
continue # the caller did not ask for it: an empty choices list breaks naive clients
for choice in chunk.get("choices", []):
stats.chars += len((choice.get("delta") or {}).get("content") or "")
stats.chunks += 1
yield sse(data) # the upstream's JSON, unchanged
except httpx2.TransportError as e: # the upstream died mid-answer: too late for a status code, say it in-band
stats.error = type(e).__name__
yield sse(json.dumps(error_body("the upstream stopped in the middle of the answer", "upstream_error",
"upstream_stream_broken")))
finally:
await resp.aclose() # also runs when the caller hangs up: stop reading, free the upstream connection - What the gateway learns while the answer passes through. The relay fills it in; milestone 4 bills from it.line 11
- An async generator:
yieldinsideasync def. The caller consumes it withasync for, which is exactly whatStreamingResponsedoes.line 25 - Blank lines separate events; lines starting with
:are comments some servers send as keep-alives.line 29 - The usage chunk has
choices: []. Only pass it to callers that asked for it.line 39 - The upstream's JSON, unchanged: the gateway is a pipe, not an editor.line 44
- The status line went out long ago, so the error goes in-band, as one more event. Never switch to another model here: half an answer from one model and half from another is wrong.line 45
- When the caller hangs up, the server cancels the generator, and
finallystill runs: the upstream connection is freed and the model stops generating for nobody.line 50
import asyncio
import time
from contextlib import asynccontextmanager
from typing import Any, Callable
import httpx2
from fastapi import FastAPI, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from config import Target, load_config, settings
from errors import GatewayError, error_body, error_response
from streaming import StreamStats, relay
from upstream import UpstreamError, Upstreams
class ChatRequest(BaseModel):
"""What the gateway checks. Every other field (temperature, max_tokens, tools...) is passed through."""
model_config = ConfigDict(extra="allow")
model: str = Field(min_length=1)
messages: list[dict[str, Any]] = Field(min_length=1)
stream: bool = False
def create_app(*, transport: httpx2.AsyncBaseTransport | None = None,
clock: Callable[[], float] = time.time) -> FastAPI:
"""Build the gateway. Tests pass a fake transport (the upstreams) and a fake clock (used from milestone 3)."""
cfg = load_config(settings().config_file)
upstreams = Upstreams(cfg.upstreams, transport)
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await upstreams.aclose() # close the pooled connections on shutdown
app = FastAPI(title="LLM gateway", lifespan=lifespan)
@app.exception_handler(GatewayError)
async def gateway_error(request: Request, err: GatewayError):
return error_response(err)
@app.exception_handler(RequestValidationError)
async def bad_request(request: Request, err: RequestValidationError):
first = err.errors()[0]
where = ".".join(str(p) for p in first["loc"] if p != "body")
return JSONResponse(error_body(f"{where}: {first['msg']}", "invalid_request_error"), status_code=400)
def route(alias: str) -> tuple[Target, ...]:
if alias not in cfg.routes:
raise GatewayError(404, f"model '{alias}' does not exist; use one of: {', '.join(cfg.routes)}",
code="model_not_found")
return cfg.routes[alias]
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/health/upstreams")
async def health_upstreams():
"""Ask every upstream for its models (GET /models) and say which routed models are missing."""
async def check(name: str) -> dict:
wanted = sorted({t.model for ts in cfg.routes.values() for t in ts if t.upstream == name})
try:
served = await upstreams.models(name)
except Exception as e:
return {"ok": False, "error": type(e).__name__}
return {"ok": True, "models": served, "missing": [m for m in wanted if m not in served]}
results = await asyncio.gather(*(check(n) for n in cfg.upstreams))
report = dict(zip(cfg.upstreams, results))
healthy = all(r["ok"] and not r["missing"] for r in report.values())
return {"status": "ok" if healthy else "degraded", "upstreams": report}
@app.get("/v1/models")
async def list_models():
return {"object": "list",
"data": [{"id": alias, "object": "model", "created": 0, "owned_by": "llm-gateway"} for alias in cfg.routes]}
async def call(target: Target, body: dict, stream: bool) -> httpx2.Response:
try:
return await (upstreams.open_stream(target, body) if stream else upstreams.chat(target, body))
except UpstreamError as e:
status = 504 if e.kind == "timeout" else 502
raise GatewayError(status, str(e), "upstream_error", code=f"upstream_{e.kind}") from e
@app.post("/v1/chat/completions")
async def chat(req: ChatRequest):
target = route(req.model)[0]
body = req.model_dump(exclude_unset=True)
caller_wants_usage = bool((body.get("stream_options") or {}).get("include_usage"))
if req.stream: # always ask for usage: the gateway needs the token counts (milestone 4)
body["stream_options"] = {**(body.get("stream_options") or {}), "include_usage": True}
resp = await call(target, body, req.stream)
headers = {"x-gateway-upstream": str(target)}
if resp.status_code != 200: # the upstream refused the request itself (a 4xx): pass it on unchanged
return Response(resp.content, resp.status_code, headers=headers,
media_type=resp.headers.get("content-type", "application/json"))
if req.stream:
stats = StreamStats()
return StreamingResponse(relay(resp, stats, caller_wants_usage), media_type="text/event-stream",
headers={**headers, "Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
return JSONResponse(resp.json(), headers=headers)
return app - Remember what the caller asked for before changing the body.line 92
- Always ask the upstream for usage. Without it, the gateway could only guess the tokens of a streamed answer.line 94
- FastAPI sends the status and headers now, then each string the generator yields.line 102
- nginx and similar proxies buffer responses by default, which turns a stream back into one late blob.line 103
"""An "app" that uses the gateway: the normal openai SDK, with the gateway's URL and a gateway key."""
import argparse
import os
import sys
import openai
from openai import OpenAI
def main() -> None:
parser = argparse.ArgumentParser(description="Ask the gateway one question.")
parser.add_argument("question", nargs="?", default="In one sentence, what is an API gateway?")
parser.add_argument("--model", default="fast")
parser.add_argument("--stream", action="store_true", help="print the answer as it arrives")
args = parser.parse_args()
client = OpenAI(base_url=os.environ.get("GATEWAY_URL", "http://localhost:8080/v1"),
api_key=os.environ.get("GATEWAY_KEY", "no-key-yet"), max_retries=0)
messages = [{"role": "user", "content": args.question}]
try:
print("models:", [m.id for m in client.models.list()])
if args.stream:
for chunk in client.chat.completions.create(model=args.model, messages=messages, stream=True):
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
return
raw = client.chat.completions.with_raw_response.create(model=args.model, messages=messages, temperature=0)
except openai.APIStatusError as e: # the gateway answered with an error: show its message
sys.exit(f"gateway error: {e.message}")
except openai.APIConnectionError:
sys.exit("cannot reach the gateway: is it running? (uv run uvicorn --factory app:create_app --port 8080)")
reply = raw.parse()
print(f"[{raw.headers.get('x-gateway-upstream')}]", reply.choices[0].message.content)
print(f"usage: {reply.usage.prompt_tokens} in, {reply.usage.completion_tokens} out")
if __name__ == "__main__":
main() - The defensive way to read chunks: any server may send one with no choices.line 24
- Print each piece now instead of when the line ends.line 25
"""Milestone 2: streaming. Events pass through as they come, usage is always requested, errors are handled."""
import openai
from fakes import sse_events
def stream(gw, **extra):
return gw.chat("fast", "Hi", stream=True, **extra)
def text_of(events) -> str:
return "".join(c["delta"].get("content") or "" for e in events if isinstance(e, dict) for c in e.get("choices", []))
def test_events_pass_through_in_order_and_end_with_done(gateway):
r = stream(gateway())
assert r.status_code == 200
assert r.headers["content-type"].startswith("text/event-stream")
events = sse_events(r.text)
assert text_of(events) == "Hello from ollama."
assert events[-1] == "[DONE]"
def test_the_gateway_always_asks_the_upstream_for_usage(gateway):
gw = gateway()
events = sse_events(stream(gw).text)
assert gw.ollama.requests[0]["stream_options"] == {"include_usage": True}
# the caller did not ask, so the usage-only chunk (empty choices) is not passed on
assert all(e == "[DONE]" or e["choices"] for e in events)
def test_the_usage_chunk_is_kept_when_the_caller_asks(gateway):
events = sse_events(stream(gateway(), stream_options={"include_usage": True}).text)
assert events[-2]["choices"] == [] and events[-2]["usage"]["total_tokens"] == 25
def test_no_stream_options_without_stream(gateway):
gw = gateway()
gw.chat("fast")
assert "stream_options" not in gw.ollama.requests[0]
def test_a_failure_before_the_first_event_is_a_normal_json_error(gateway):
gw = gateway()
gw.ollama.fail = gw.hosted.fail = 503
r = stream(gw)
assert r.status_code == 502
assert r.headers["content-type"].startswith("application/json")
assert r.json()["error"]["code"] == "upstream_status"
def test_a_break_mid_stream_ends_with_an_error_event(gateway):
gw = gateway()
gw.ollama.break_stream_after = 2 # "Hello", " from", then the connection drops
r = stream(gw)
assert r.status_code == 200 # already sent before the upstream broke
events = sse_events(r.text)
assert text_of(events) == "Hello from"
assert events[-1]["error"]["code"] == "upstream_stream_broken"
assert "[DONE]" not in events
def test_the_openai_sdk_streams_through_the_gateway(gateway):
gw = gateway()
sdk = openai.OpenAI(base_url="http://gateway/v1", api_key=gw.key, max_retries=0, http_client=gw.client)
parts = [c.choices[0].delta.content or "" for c in
sdk.chat.completions.create(model="fast", messages=[{"role": "user", "content": "Hi"}], stream=True)]
assert "".join(parts) == "Hello from ollama." - The caller did not ask for usage, but the upstream was asked, and the usage chunk was then held back.line 24
- Before the first byte the gateway can still choose the status code. After it, it cannot.line 43
- A broken stream must not look like a finished one: no
[DONE]after the error event.line 60 - The SDK reads
chunk.choices[0]on every chunk here. It would crash on the usage chunk if the gateway passed it on.line 63
uv run pytest -q tests/test_m1.py tests/test_m2.py
uv run try_gateway.py --stream "Name three HTTP methods."
curl -sN localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "fast", "stream": true, "messages": [{"role": "user", "content": "Say hi"}]}'uv run pytest -q tests/test_m1.py tests/test_m2.py
uv run try_gateway.py --stream "Name three HTTP methods."
curl -sN localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{"model": "fast", "stream": true, "messages": [{"role": "user", "content": "Say hi"}]}'uv run pytest -q tests/test_m1.py tests/test_m2.py
uv run try_gateway.py --stream "Name three HTTP methods."
curl.exe -sN localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{\"model\": \"fast\", \"stream\": true, \"messages\": [{\"role\": \"user\", \"content\": \"Say hi\"}]}' ..................... [100%]
21 passed in 0.95s
models: ['fast', 'smart']
GET, POST and DELETE.
data: {"id":"chatcmpl-511","object":"chat.completion.chunk","created":1764417900,"model":"llama3.2:3b","system_fingerprint":"fp_ollama","choices":[{"index":0,"delta":{"role":"assistant","content":"Hi"},"finish_reason":null}]}
data: {"id":"chatcmpl-511","object":"chat.completion.chunk","created":1764417900,"model":"llama3.2:3b","system_fingerprint":"fp_ollama","choices":[{"index":0,"delta":{"role":"assistant","content":"!"},"finish_reason":null}]}
...
data: {"id":"chatcmpl-511","object":"chat.completion.chunk","created":1764417900,"model":"llama3.2:3b","system_fingerprint":"fp_ollama","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":"stop"}]}
data: [DONE] [DONE].Stuck on this milestone?
- The whole answer arrives at once in the terminal
- Something buffers. Check that
relayyields inside the loop (not after it), that you return aStreamingResponse, and usecurl -N(-Nturns off curl's own buffering). httpx2.ResponseNotReadorStreamClosederrors- You read a streamed response after closing it, or with
.json()instead ofaiter_lines(). For a 200 stream, onlyrelayreads it, and onlyrelaycloses it. - The SDK raises
IndexError: list index out of rangewhile streaming - It received the usage chunk (
choices: []) without asking. Drop that chunk inrelayunless the caller sentstream_options.include_usage. - Windows: the curl command fails with JSON errors
- PowerShell handles quotes differently. Use the Windows tab of the command (with
curl.exeand escaped quotes), or put the JSON in a file and pass-d "@hi.json".
API keys per team, allowed routes and a token bucket per key
Every request needs a gateway key; keys are stored as hashes in SQLite, belong to a team, and each has its own requests-per-minute limit.
db.py: a small connect(path) context manager around sqlite3: open, set row_factory = sqlite3.Row (rows that work like dicts), commit on success, roll back on an error, always close. Milestone 4 reuses it.
keys.py: a frozen dataclass ApiKey(id, team, name, prefix, rpm, burst) and KeyStore(path), which creates an api_keys table on first use. create(team, name, rpm=60, burst=10) -> str makes a random key, "gw-" plus secrets.token_urlsafe(24), and stores only its SHA-256 hash, the first 7 characters (prefix, so people can tell keys apart in lists and logs), the team, a name, the limits and the creation time. It returns the key itself: the only time anyone sees it. lookup(key) -> ApiKey | None hashes the given key and finds an active (not revoked) row. list() returns every key's row without the hash, and revoke(key_id) -> bool sets revoked_at.
Why SHA-256 and not bcrypt, as for passwords? Bcrypt is slow on purpose, to protect short human passwords from guessing. These keys are 24 random bytes: nobody can guess them, so a fast hash is enough, and it lets lookup find the row with one index search on every request.
ratelimit.py: TokenBucket(capacity, rate, now) holds up to capacity tokens, starts full, and refills rate tokens per second. take(now, n=1.0) -> float first adds the tokens earned since the last call (never above the capacity), then takes n and returns 0.0, or, if there are not enough, takes nothing and returns how many seconds until there will be. RateLimiter(clock) keeps one bucket per key id, created on first use with capacity = key.burst and rate = key.rpm / 60; take(key) -> (seconds_to_wait, whole_tokens_left). The burst is what lets an app send 10 requests at once after a quiet minute; the rate is the long-run limit.
app.py: a FastAPI dependency caller reads Authorization: Bearer <key>. A missing header (or one without Bearer ) is 401 missing_api_key; an unknown or revoked key is 401 invalid_api_key (both with type authentication_error); a key whose team is no longer in gateway.toml is 403 unknown_team. /v1/models and /v1/chat/completions need a key; /health and /health/upstreams do not (load balancers call them). /v1/models lists only the team's routes. In chat, in this order: the rate limit (429, type rate_limit_error, code rate_limit_exceeded, with Retry-After in whole seconds rounded up), then an unknown model (404), then a route the team may not use (403, type permission_error, code model_not_allowed). Successful answers carry x-ratelimit-remaining-requests. Refused requests never reach an upstream.
admin.py, a command-line tool: create-key --team T --name N [--rpm 60] [--burst 10] checks the team exists in gateway.toml and prints the new key once; list-keys prints id, prefix, team, name, rpm and state; revoke-key ID.
Then create a key for yourself and give it to the example app. From now on try_gateway.py needs it: export GATEWAY_KEY=gw-... in the terminal where you run it.
uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.pypasses (30 tests).uv run admin.py create-key --team search --name try-gatewayprints a key starting withgw-, anduv run admin.py list-keysshows it by its prefix only.- With
GATEWAY_KEYset to that key,uv run try_gateway.pyanswers; withGATEWAY_KEY=wrongit printsgateway error: Error code: 401 - invalid or revoked API key. - Twelve quick requests with the default key (
--burst 10) give about ten 200s and then 429s, each with aRetry-Afterheader.
Hints
- A FastAPI dependency is a function the endpoint names in its parameters:
async def chat(req: ChatRequest, key: ApiKey = Depends(caller)). FastAPI callscallerfirst (it can ask for the header withauthorization: str | None = Header(default=None)); ifcallerraises, the endpoint never runs. Like a SpringHandlerInterceptor, but typed. - Refill first, then decide:
tokens = min(capacity, tokens + (now - updated) * rate). When there are not enough, the wait is(n - tokens) / rate. - Key lookups:
hashlib.sha256(key.encode()).hexdigest(), and aUNIQUEcolumn for the hash, which SQLite indexes automatically. - The tests' clock is fake (
gw.clock.advance(1.0)), so read the time through theclockthatcreate_appwas given, nevertime.time()directly.
Show the reference solution for milestone 3
Try it yourself first. This is one good way to do it, not the only one.
import sqlite3
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
@contextmanager
def connect(path: Path) -> Iterator[sqlite3.Connection]:
"""One short-lived SQLite connection: commit on success, roll back on error, always close."""
db = sqlite3.connect(path)
db.row_factory = sqlite3.Row # rows behave like dicts: row["team"]
try:
with db:
yield db
finally:
db.close() - Turns a generator into something you can use in
with, like try-with-resources in Java: code beforeyieldopens, thefinallycloses.line 7 - A
sqlite3connection used inwithcommits when the block succeeds and rolls back when it raises. It does **not** close the connection; thefinallydoes.line 13
import hashlib
import secrets
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from db import connect
SCHEMA = """
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY,
key_hash TEXT NOT NULL UNIQUE,
prefix TEXT NOT NULL,
team TEXT NOT NULL,
name TEXT NOT NULL,
rpm INTEGER NOT NULL,
burst INTEGER NOT NULL,
created_at TEXT NOT NULL,
revoked_at TEXT
)"""
@dataclass(frozen=True)
class ApiKey:
id: int
team: str
name: str
prefix: str
rpm: int # requests per minute, refilled continuously
burst: int # how many requests may arrive at once
def hash_key(key: str) -> str:
return hashlib.sha256(key.encode()).hexdigest()
class KeyStore:
"""API keys in SQLite. Only a hash of each key is stored: the key itself is shown once, when created."""
def __init__(self, path: Path):
self.path = path
with connect(path) as db:
db.execute(SCHEMA)
def create(self, team: str, name: str, rpm: int = 60, burst: int = 10) -> str:
key = "gw-" + secrets.token_urlsafe(24)
with connect(self.path) as db:
db.execute("INSERT INTO api_keys (key_hash, prefix, team, name, rpm, burst, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
(hash_key(key), key[:7], team, name, rpm, burst, datetime.now(timezone.utc).isoformat()))
return key
def lookup(self, key: str) -> ApiKey | None:
with connect(self.path) as db:
row = db.execute("SELECT id, team, name, prefix, rpm, burst FROM api_keys "
"WHERE key_hash = ? AND revoked_at IS NULL", (hash_key(key),)).fetchone()
return ApiKey(**dict(row)) if row else None
def list(self) -> list[dict]:
with connect(self.path) as db:
rows = db.execute("SELECT id, prefix, team, name, rpm, burst, created_at, revoked_at FROM api_keys ORDER BY id")
return [dict(r) for r in rows]
def revoke(self, key_id: int) -> bool:
with connect(self.path) as db:
cur = db.execute("UPDATE api_keys SET revoked_at = ? WHERE id = ? AND revoked_at IS NULL",
(datetime.now(timezone.utc).isoformat(), key_id))
return cur.rowcount == 1 - Only the hash. A copy of this database is useless to an attacker, unlike a table of keys.line 12
gw-3fK9q: enough to recognise a key in a list or a log line, not enough to use it.line 13secretsis the module for anything security-related (randomis predictable). 24 bytes is 192 random bits. Thegw-prefix makes leaked keys easy to find with a secret scanner.line 46- The one and only time the key exists in plain text.line 50
?placeholders, never string formatting: SQLite inserts the value safely.line 55**dict(row)passes the columns as keyword arguments; the SELECT lists exactly the dataclass fields.line 56
from collections.abc import Callable
from keys import ApiKey
class TokenBucket:
"""Holds up to `capacity` tokens and refills `rate` tokens per second. Each request takes one."""
def __init__(self, capacity: float, rate: float, now: float):
self.capacity, self.rate = capacity, rate
self.tokens, self.updated = capacity, now
def take(self, now: float, n: float = 1.0) -> float:
"""Take n tokens. Returns 0.0 when allowed, otherwise the seconds until n tokens will be there."""
self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
self.updated = now
if self.tokens >= n:
self.tokens -= n
return 0.0
return (n - self.tokens) / self.rate
class RateLimiter:
"""One bucket per API key, in this process's memory."""
def __init__(self, clock: Callable[[], float]):
self.clock = clock
self.buckets: dict[int, TokenBucket] = {}
def take(self, key: ApiKey) -> tuple[float, int]:
"""(seconds to wait, 0.0 when allowed; whole requests left right now)."""
now = self.clock()
bucket = self.buckets.get(key.id)
if bucket is None:
bucket = self.buckets[key.id] = TokenBucket(key.burst, key.rpm / 60, now)
wait = bucket.take(now)
return wait, int(bucket.tokens) - The classic rate limiter: bursts up to the capacity, then a steady rate. No timers: the refill is computed from the time that passed.line 6
- Refill for the time since the last call, but a bucket never holds more than it can.line 15
- How long until enough tokens have refilled: that becomes
Retry-After.line 20 - In this process's memory. Run two gateway processes and each allows the full rate: production keeps the buckets in Redis.line 28
"""Manage API keys: uv run admin.py create-key --team search --name search-api"""
import argparse
from config import load_config, settings
from keys import KeyStore
def main() -> None:
parser = argparse.ArgumentParser(description="Manage the gateway's API keys.")
sub = parser.add_subparsers(dest="cmd", required=True)
create = sub.add_parser("create-key", help="create a key for a team (shown once)")
create.add_argument("--team", required=True)
create.add_argument("--name", required=True, help="what uses the key, e.g. search-api")
create.add_argument("--rpm", type=int, default=60, help="requests per minute")
create.add_argument("--burst", type=int, default=10, help="requests allowed at once")
sub.add_parser("list-keys", help="list keys (never the keys themselves)")
revoke = sub.add_parser("revoke-key", help="revoke a key by its id")
revoke.add_argument("id", type=int)
args = parser.parse_args()
s = settings()
store = KeyStore(s.db_path)
if args.cmd == "create-key":
teams = load_config(s.config_file).teams
if args.team not in teams:
raise SystemExit(f"unknown team {args.team!r}; gateway.toml has: {', '.join(teams)}")
key = store.create(args.team, args.name, args.rpm, args.burst)
print(f"Created a key for team {args.team} ({args.rpm} requests/minute, burst {args.burst}).")
print("It is shown only once. Store it like a password:")
print(key)
elif args.cmd == "list-keys":
for k in store.list():
state = f"revoked {k['revoked_at'][:10]}" if k["revoked_at"] else "active"
print(f"{k['id']:>3} {k['prefix']}... team={k['team']:<8} name={k['name']:<12} rpm={k['rpm']:<5} {state}")
elif args.cmd == "revoke-key":
print("revoked" if store.revoke(args.id) else f"no active key with id {args.id}")
if __name__ == "__main__":
main() - Sub-commands like
git commitandgit push: each has its own arguments.line 10 - Keys for a team that does not exist would be refused on every request anyway: catch the typo now.line 25
import asyncio
import math
import time
from contextlib import asynccontextmanager
from typing import Any, Callable
import httpx2
from fastapi import Depends, FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from config import Target, Team, load_config, settings
from errors import GatewayError, error_body, error_response
from keys import ApiKey, KeyStore
from ratelimit import RateLimiter
from streaming import StreamStats, relay
from upstream import UpstreamError, Upstreams
class ChatRequest(BaseModel):
"""What the gateway checks. Every other field (temperature, max_tokens, tools...) is passed through."""
model_config = ConfigDict(extra="allow")
model: str = Field(min_length=1)
messages: list[dict[str, Any]] = Field(min_length=1)
stream: bool = False
def create_app(*, transport: httpx2.AsyncBaseTransport | None = None,
clock: Callable[[], float] = time.time) -> FastAPI:
"""Build the gateway. Tests pass a fake transport (the upstreams) and a fake clock (used from milestone 3)."""
s = settings()
cfg = load_config(s.config_file)
upstreams = Upstreams(cfg.upstreams, transport)
keys = KeyStore(s.db_path)
limiter = RateLimiter(clock)
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await upstreams.aclose() # close the pooled connections on shutdown
app = FastAPI(title="LLM gateway", lifespan=lifespan)
@app.exception_handler(GatewayError)
async def gateway_error(request: Request, err: GatewayError):
return error_response(err)
@app.exception_handler(RequestValidationError)
async def bad_request(request: Request, err: RequestValidationError):
first = err.errors()[0]
where = ".".join(str(p) for p in first["loc"] if p != "body")
return JSONResponse(error_body(f"{where}: {first['msg']}", "invalid_request_error"), status_code=400)
def caller(authorization: str | None = Header(default=None)) -> ApiKey:
"""The API key in "Authorization: Bearer gw-...". FastAPI runs this before every endpoint that asks for it."""
if not authorization or not authorization.startswith("Bearer "):
raise GatewayError(401, "missing API key: send Authorization: Bearer <your gateway key>",
"authentication_error", "missing_api_key")
key = keys.lookup(authorization.removeprefix("Bearer ").strip())
if key is None:
raise GatewayError(401, "invalid or revoked API key", "authentication_error", "invalid_api_key")
if key.team not in cfg.teams:
raise GatewayError(403, f"team '{key.team}' is not in gateway.toml", "permission_error", "unknown_team")
return key
def team_of(key: ApiKey) -> Team:
return cfg.teams[key.team]
def route(alias: str, team: Team) -> tuple[Target, ...]:
if alias not in cfg.routes:
raise GatewayError(404, f"model '{alias}' does not exist; use one of: {', '.join(team.models)}",
code="model_not_found")
if alias not in team.models:
raise GatewayError(403, f"team '{team.name}' may not use '{alias}'; allowed: {', '.join(team.models)}",
"permission_error", "model_not_allowed")
return cfg.routes[alias]
def rate_limit(key: ApiKey) -> dict[str, str]:
wait, left = limiter.take(key)
if wait > 0:
raise GatewayError(429, f"rate limit of {key.rpm} requests per minute reached; retry in {wait:.1f} s",
"rate_limit_error", "rate_limit_exceeded",
headers={"Retry-After": str(math.ceil(wait)), "x-ratelimit-remaining-requests": "0"})
return {"x-ratelimit-remaining-requests": str(left)}
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/health/upstreams")
async def health_upstreams():
"""Ask every upstream for its models (GET /models) and say which routed models are missing."""
async def check(name: str) -> dict:
wanted = sorted({t.model for ts in cfg.routes.values() for t in ts if t.upstream == name})
try:
served = await upstreams.models(name)
except Exception as e:
return {"ok": False, "error": type(e).__name__}
return {"ok": True, "models": served, "missing": [m for m in wanted if m not in served]}
results = await asyncio.gather(*(check(n) for n in cfg.upstreams))
report = dict(zip(cfg.upstreams, results))
healthy = all(r["ok"] and not r["missing"] for r in report.values())
return {"status": "ok" if healthy else "degraded", "upstreams": report}
@app.get("/v1/models")
async def list_models(key: ApiKey = Depends(caller)):
return {"object": "list", "data": [{"id": alias, "object": "model", "created": 0, "owned_by": "llm-gateway"}
for alias in team_of(key).models]}
async def call(target: Target, body: dict, stream: bool) -> httpx2.Response:
try:
return await (upstreams.open_stream(target, body) if stream else upstreams.chat(target, body))
except UpstreamError as e:
status = 504 if e.kind == "timeout" else 502
raise GatewayError(status, str(e), "upstream_error", code=f"upstream_{e.kind}") from e
@app.post("/v1/chat/completions")
async def chat(req: ChatRequest, key: ApiKey = Depends(caller)):
limit_headers = rate_limit(key)
target = route(req.model, team_of(key))[0]
body = req.model_dump(exclude_unset=True)
caller_wants_usage = bool((body.get("stream_options") or {}).get("include_usage"))
if req.stream: # always ask for usage: the gateway needs the token counts (milestone 4)
body["stream_options"] = {**(body.get("stream_options") or {}), "include_usage": True}
resp = await call(target, body, req.stream)
headers = {"x-gateway-upstream": str(target), **limit_headers}
if resp.status_code != 200: # the upstream refused the request itself (a 4xx): pass it on unchanged
return Response(resp.content, resp.status_code, headers=headers,
media_type=resp.headers.get("content-type", "application/json"))
if req.stream:
stats = StreamStats()
return StreamingResponse(relay(resp, stats, caller_wants_usage), media_type="text/event-stream",
headers={**headers, "Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
return JSONResponse(resp.json(), headers=headers)
return app - A dependency: FastAPI fills
authorizationfrom theAuthorizationheader and runs this before any endpoint that asks forDepends(caller).line 56 - The OpenAI SDK sends
Authorization: Bearer <api_key>, so an app only changes the key it already passes.line 61 - Removing a team from
gateway.tomlswitches off all its keys at the next restart.line 64 - An unknown model is 404 for everyone; a known one the team may not use is 403, so the team knows to ask for access.line 71
- Whole seconds, rounded up. The openai SDK waits this long before its automatic retries.line 85
- Each team only sees the routes it may use.line 109
- First thing after the key: a client stuck in a retry loop must cost the gateway as little as possible.line 122
"""Milestone 3: API keys per team (stored hashed), the team's allowed routes, and a token bucket per key."""
import hashlib
import sqlite3
import openai
import pytest
from keys import KeyStore
from ratelimit import TokenBucket
def test_no_key_or_a_wrong_key_is_401(gateway):
gw = gateway()
for headers in ({}, {"Authorization": "Bearer gw-not-a-real-key"}, {"Authorization": "gw-no-bearer"}):
gw.client.headers.pop("Authorization", None)
r = gw.client.post("/v1/chat/completions", headers=headers,
json={"model": "fast", "messages": [{"role": "user", "content": "Hi"}]})
assert r.status_code == 401
assert r.json()["error"]["type"] == "authentication_error"
assert gw.ollama.calls == 0
def test_the_sdk_raises_authentication_error(gateway):
gw = gateway()
sdk = openai.OpenAI(base_url="http://gateway/v1", api_key="gw-wrong", max_retries=0, http_client=gw.client)
with pytest.raises(openai.AuthenticationError):
sdk.models.list()
def test_keys_are_stored_as_hashes_only(gateway):
gw = gateway()
with sqlite3.connect(gw.db_path) as db:
rows = db.execute("SELECT * FROM api_keys").fetchall()
assert gw.key not in str(rows)
assert hashlib.sha256(gw.key.encode()).hexdigest() in str(rows)
def test_a_revoked_key_stops_working(gateway):
gw = gateway()
assert gw.chat().status_code == 200
store = KeyStore(gw.db_path)
assert store.revoke(store.lookup(gw.key).id)
assert gw.chat().status_code == 401
def test_teams_only_see_and_use_their_routes(gateway):
gw = gateway(team="support") # gateway.toml: support may use "fast" only
assert [m["id"] for m in gw.client.get("/v1/models").json()["data"]] == ["fast"]
r = gw.chat("smart")
assert r.status_code == 403
assert r.json()["error"]["code"] == "model_not_allowed"
assert gw.hosted.calls == 0
def test_rate_limit_per_key_with_retry_after(gateway):
gw = gateway()
slow = gw.new_key("search", rpm=60, burst=2) # one request per second, two at once
gw.client.headers["Authorization"] = f"Bearer {slow}"
assert [gw.chat().status_code for _ in range(3)] == [200, 200, 429]
r = gw.chat()
assert r.json()["error"]["code"] == "rate_limit_exceeded"
assert r.headers["Retry-After"] == "1"
gw.clock.advance(1.0)
assert gw.chat().status_code == 200
assert gw.ollama.calls == 3 # refused requests never reach the upstream
gw.client.headers["Authorization"] = f"Bearer {gw.key}" # another key has its own bucket
assert gw.chat().status_code == 200
def test_remaining_requests_header(gateway):
gw = gateway()
gw.client.headers["Authorization"] = f"Bearer {gw.new_key('search', rpm=60, burst=5)}"
assert gw.chat().headers["x-ratelimit-remaining-requests"] == "4"
def test_token_bucket_refills_over_time():
bucket = TokenBucket(capacity=3, rate=0.5, now=0.0) # 3 at once, then one every 2 seconds
assert [bucket.take(0.0) for _ in range(3)] == [0.0, 0.0, 0.0]
assert bucket.take(0.0) == pytest.approx(2.0)
assert bucket.take(1.0) == pytest.approx(1.0) # half a token came back
assert bucket.take(2.0) == 0.0
assert bucket.take(100.0) == 0.0 and bucket.tokens == pytest.approx(2.0) # never more than the capacity
def test_health_needs_no_key(gateway):
gw = gateway()
gw.client.headers.pop("Authorization")
assert gw.client.get("/health").json() == {"status": "ok"} - Reads the SQLite file directly: the plain key must not be anywhere in it.line 30
- One request a second, two at once: small numbers make the bucket easy to see.line 57
- One second later, exactly one token is back. No
sleepin tests.line 63 - The refused requests never reached the upstream.line 65
- The bucket on its own, with plain numbers for the time.line 77
uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py
uv run admin.py create-key --team search --name try-gateway
export GATEWAY_KEY=gw-paste-the-key-here
uv run admin.py list-keys
uv run try_gateway.py
GATEWAY_KEY=wrong uv run try_gateway.py
for i in $(seq 12); do curl -s -o /dev/null -w "%{http_code} " localhost:8080/v1/chat/completions -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" -d '{"model": "fast", "messages": [{"role": "user", "content": "hi"}]}'; done; echouv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py
uv run admin.py create-key --team search --name try-gateway
export GATEWAY_KEY=gw-paste-the-key-here
uv run admin.py list-keys
uv run try_gateway.py
GATEWAY_KEY=wrong uv run try_gateway.py
for i in $(seq 12); do curl -s -o /dev/null -w "%{http_code} " localhost:8080/v1/chat/completions -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" -d '{"model": "fast", "messages": [{"role": "user", "content": "hi"}]}'; done; echouv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py
uv run admin.py create-key --team search --name try-gateway
$env:GATEWAY_KEY="gw-paste-the-key-here"
uv run admin.py list-keys
uv run try_gateway.py
1..12 | ForEach-Object { curl.exe -s -o NUL -w "%{http_code} " localhost:8080/v1/chat/completions -H "Authorization: Bearer $env:GATEWAY_KEY" -H "Content-Type: application/json" -d '{\"model\": \"fast\", \"messages\": [{\"role\": \"user\", \"content\": \"hi\"}]}' } .............................. [100%] 30 passed in 1.32s Created a key for team search (60 requests/minute, burst 10). It is shown only once. Store it like a password: gw-xY3fK9qL2mWbT7vRzA1nEo5sHc8dJu4g 1 gw-xY3f... team=search name=try-gateway rpm=60 active models: ['fast', 'smart'] [ollama/llama3.2:3b] An API gateway is a single entry point that receives client requests and routes them to the right backend services. usage: 38 in, 24 out models: ['fast', 'smart'] gateway error: Error code: 401 - invalid or revoked API key 200 200 200 200 200 200 200 200 200 200 429 429
Stuck on this milestone?
- Every request is 401 although you just created a key
- The gateway and
admin.pyuse different databases: both readGATEWAY_DBfrom.env, relative to the project folder. Also check thatGATEWAY_KEYis set in the terminal that runstry_gateway.py(echo $GATEWAY_KEY). - The SDK waits a few seconds and then succeeds instead of showing the 429
- The openai SDK retries 429s by itself (
max_retries, 2 by default), waitingRetry-After.try_gateway.pysetsmax_retries=0so you see every answer; real apps usually keep the retries. - The
forloop prints fewer than ten 200s - The
try_gateway.pycalls just before used tokens from the same bucket (one each). Wait a few seconds, or create a key with a larger--burst. sqlite3.OperationalError: no such table: api_keysin a testKeyStore.__init__must create the table (CREATE TABLE IF NOT EXISTS), because every test starts with an empty database file.
Usage, cost per team and daily token budgets
One usage row per request in SQLite with tokens and cost, a daily token budget per team that refuses requests before they reach an upstream, and an `/admin/usage` report.
Requests per minute protect the gateway; tokens are what cost money. One request can be 50 tokens or 50,000. This milestone counts every token, prices it, and stops a team at its daily budget.
usage.py: a dataclass UsageRecord with ts (Unix seconds from the clock), request_id, team, key_id, route, upstream ("ollama/llama3.2:3b", or None when no upstream answered), status (default 500), prompt_tokens, completion_tokens, cost_usd, latency_ms, cached and estimated (both False). UsageStore(path) creates a usage table with those columns plus day (the UTC date of ts, like "2026-11-20") and an index on (team, day). Methods: record(rec), tokens_on(team, day) -> int (prompt plus completion tokens, of rows that are not cache hits) and report(day) -> {team: {...}} with requests, ok (status 200), rejected (4xx), errors (5xx), cache_hits, prompt_tokens and completion_tokens (cache hits excluded), cost_usd (rounded to 6 places) and avg_latency_ms. Also small helpers: day_of(ts), cost_usd(prices, model, prompt_tokens, completion_tokens) (dollars per million, like lab 1), estimate_tokens(text) (characters divided by 4, plus 1) and message_text(messages) (all the text in a message list, including content given as a list of {"type": "text", "text": ...} parts).
budget.py: Budgets(usage, clock) with reserve(team, tokens) -> int and release(team, tokens). Before a call, reserve the most the request can use: the estimated prompt tokens plus max_completion_tokens, or max_tokens, or default_max_tokens from gateway.toml. If tokens used today plus tokens reserved by requests still running plus this reservation exceed team.daily_token_budget, raise BudgetExceeded (with retry_after_s, the seconds until midnight UTC). After the call, release the reservation: by then the real tokens are in the usage table. Without the reservations, ten requests that arrive together would all pass a check that only one of them should.
app.py: every request that came with a valid key produces exactly one usage row, whatever happens: answered, refused by the rate limit or the budget (429), unknown model (404), upstream error (502). Requests without a valid key produce none (otherwise anyone could fill your database). The request id comes from the caller's x-request-id header when it is 1 to 64 letters, digits, ., _ or -, and is a new uuid4().hex otherwise; it goes back in the x-request-id response header. Tokens come from the upstream's usage; when there is none (a server that does not send it, or a stream that broke), estimate them and set estimated. A stream is billed when it ends, in the generator's finally: also when it broke midway or the caller hung up, because the model generated those tokens either way. The budget check comes after the route check and refuses with 429, type rate_limit_error, code daily_budget_exceeded and Retry-After.
GET /admin/usage?day=2026-11-20 (default: today, by the clock) needs Authorization: Bearer <ADMIN_KEY>, compared with hmac.compare_digest: 401 for a wrong key, 403 admin_disabled when ADMIN_KEY is empty. It returns {"day": ..., "teams": [...]} with every team in gateway.toml (zeros for a team with no traffic), each with the report fields plus daily_token_budget and budget_used_pct.
uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.pypasses (40 tests).- After a few
try_gateway.pyruns,/admin/usage(the curl command below) shows your requests, tokens andcost_usdunder teamsearch, andsupportwith zeros. - The same curl without the admin key (or with a team key) answers 401.
Hints
- Write the one row in one place: a small
finish(status, tokens=None, answer_chars=0)function inside the endpoint that fills in the record, writes it and releases the reservation. Call it from anexcept GatewayErrorblock (then re-raise), after a normal answer, and from the stream'sfinally. - Python closures read variables when they run, so
finishcan be defined before the code that setsrec.upstreamor the reservation, as long as it is called after. - SQLite counts booleans in SQL:
SUM(status = 200)is the number of rows with status 200.COALESCE(SUM(...), 0)turns "no rows" into 0 instead ofNULL. - Seconds to midnight UTC:
datetime.combine(today + timedelta(days=1), datetime.min.time(), timezone.utc) - now. The tests' clock starts at 12:00 UTC, so it is exactly 43,200.
Show the reference solution for milestone 4
Try it yourself first. This is one good way to do it, not the only one.
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from db import connect
SCHEMA = """
CREATE TABLE IF NOT EXISTS usage (
id INTEGER PRIMARY KEY,
ts REAL NOT NULL,
day TEXT NOT NULL,
request_id TEXT NOT NULL,
team TEXT NOT NULL,
key_id INTEGER NOT NULL,
route TEXT NOT NULL,
upstream TEXT,
status INTEGER NOT NULL,
prompt_tokens INTEGER NOT NULL,
completion_tokens INTEGER NOT NULL,
cost_usd REAL NOT NULL,
latency_ms REAL NOT NULL,
cached INTEGER NOT NULL,
estimated INTEGER NOT NULL
)"""
INDEX = "CREATE INDEX IF NOT EXISTS usage_team_day ON usage (team, day)"
@dataclass
class UsageRecord:
"""One row per request that came with a valid key, filled in as the request goes along."""
ts: float
request_id: str
team: str
key_id: int
route: str
upstream: str | None = None # "ollama/llama3.2:3b", once a target answered
status: int = 500
prompt_tokens: int = 0
completion_tokens: int = 0
cost_usd: float = 0.0
latency_ms: float = 0.0
cached: bool = False
estimated: bool = False # tokens guessed from text length: the upstream sent no usage
def day_of(ts: float) -> str:
"""The UTC day of a Unix timestamp, e.g. "2026-11-20". Budgets reset at midnight UTC."""
return datetime.fromtimestamp(ts, timezone.utc).date().isoformat()
def cost_usd(prices: dict[str, tuple[float, float]], model: str, prompt_tokens: int, completion_tokens: int) -> float:
price_in, price_out = prices[model] # load_config checked that every routed model has a price
return (prompt_tokens * price_in + completion_tokens * price_out) / 1_000_000
def estimate_tokens(text: str) -> int:
"""About four characters per token for English. Good enough for a budget check, not for a bill."""
return len(text) // 4 + 1
def message_text(messages: list[dict]) -> str:
"""All the text in a message list, including content given as a list of parts."""
out = []
for m in messages:
content = m.get("content")
if isinstance(content, str):
out.append(content)
elif isinstance(content, list):
out.extend(p.get("text", "") for p in content if isinstance(p, dict))
return "\n".join(out)
class UsageStore:
def __init__(self, path: Path):
self.path = path
with connect(path) as db:
db.execute(SCHEMA)
db.execute(INDEX)
def record(self, rec: UsageRecord) -> None:
row = asdict(rec) | {"day": day_of(rec.ts)}
cols = ", ".join(row)
with connect(self.path) as db:
db.execute(f"INSERT INTO usage ({cols}) VALUES ({', '.join('?' * len(row))})", list(row.values()))
def tokens_on(self, team: str, day: str) -> int:
"""Tokens a team used on a day. Cache hits are free, so they do not count."""
with connect(self.path) as db:
row = db.execute("SELECT COALESCE(SUM(prompt_tokens + completion_tokens), 0) FROM usage "
"WHERE team = ? AND day = ? AND cached = 0", (team, day)).fetchone()
return row[0]
def report(self, day: str) -> dict[str, dict]:
"""Per team for one day: requests by outcome, tokens, cost, cache hits and average latency."""
with connect(self.path) as db:
rows = db.execute("""
SELECT team,
COUNT(*) AS requests,
SUM(status = 200) AS ok,
SUM(status >= 400 AND status < 500) AS rejected,
SUM(status >= 500) AS errors,
SUM(cached) AS cache_hits,
SUM(CASE WHEN cached = 0 THEN prompt_tokens ELSE 0 END) AS prompt_tokens,
SUM(CASE WHEN cached = 0 THEN completion_tokens ELSE 0 END) AS completion_tokens,
ROUND(SUM(cost_usd), 6) AS cost_usd,
ROUND(AVG(latency_ms), 1) AS avg_latency_ms
FROM usage WHERE day = ? GROUP BY team ORDER BY team""", (day,))
return {r["team"]: dict(r) for r in rows} - Stored as a text date:
WHERE day = ?with the index is a fast lookup, and budgets reset at midnight UTC without any job.line 11 - Filled in as the request goes along, written once at the end.line 29
- Honest accounting: a guessed number is marked as a guess, so a bill can show it.line 43
- Prices are per million tokens, input and output separately. A missing price would be a
KeyError, which is whyload_configrefuses it at startup.line 51 - About four characters per token for English. Good for a budget check; real counts come from the upstream.line 56
asdictturns the dataclass into a dict;|merges two dicts (Python 3.9+).line 81- Cache hits cost nothing (milestone 6), so they do not use the budget.line 90
- In SQLite a comparison is 1 or 0, so summing it counts the matching rows.line 99
from collections import defaultdict
from collections.abc import Callable
from datetime import datetime, timedelta, timezone
from config import Team
from usage import UsageStore, day_of
class BudgetExceeded(Exception):
def __init__(self, team: Team, used: int, retry_after_s: float):
super().__init__(f"team '{team.name}' used {used} of its {team.daily_token_budget} tokens today")
self.retry_after_s = retry_after_s
class Budgets:
"""Daily token budgets per team. Before a call, reserve the most it can use; after it, release the
reservation (the real tokens are in the usage table by then). Reservations are what stop ten
requests that arrive together from all passing a check that only one of them would pass."""
def __init__(self, usage: UsageStore, clock: Callable[[], float]):
self.usage, self.clock = usage, clock
self.pending: dict[str, int] = defaultdict(int) # tokens reserved by requests still running, per team
def reserve(self, team: Team, tokens: int) -> int:
now = self.clock()
used = self.usage.tokens_on(team.name, day_of(now)) + self.pending[team.name]
if used + tokens > team.daily_token_budget:
raise BudgetExceeded(team, used, seconds_to_midnight_utc(now))
self.pending[team.name] += tokens
return tokens
def release(self, team: Team, tokens: int) -> None:
self.pending[team.name] -= tokens
def seconds_to_midnight_utc(ts: float) -> float:
now = datetime.fromtimestamp(ts, timezone.utc)
midnight = datetime.combine(now.date() + timedelta(days=1), datetime.min.time(), timezone.utc)
return (midnight - now).total_seconds() - Reserve before, release after: the same reserve-and-refund idea as the system design, with SQLite and a dict instead of Redis.line 15
defaultdict(int)starts every missing team at 0, sopending[team] += nneeds no check.line 22- Refuses a request that **might** go over, even if its real answer would have fit: the budget is a promise, so the check is the worst case.line 27
- For
Retry-After: when a new day, and a new budget, starts.line 36
import asyncio
import hmac
import math
import re
import time
import uuid
from contextlib import asynccontextmanager
from typing import Any, Callable
import httpx2
from fastapi import Depends, FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from budget import BudgetExceeded, Budgets
from config import Target, Team, load_config, settings
from errors import GatewayError, error_body, error_response
from keys import ApiKey, KeyStore
from ratelimit import RateLimiter
from streaming import StreamStats, relay
from upstream import UpstreamError, Upstreams
from usage import UsageRecord, UsageStore, cost_usd, day_of, estimate_tokens, message_text
REQUEST_ID = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
class ChatRequest(BaseModel):
"""What the gateway checks. Every other field (temperature, max_tokens, tools...) is passed through."""
model_config = ConfigDict(extra="allow")
model: str = Field(min_length=1)
messages: list[dict[str, Any]] = Field(min_length=1)
stream: bool = False
def create_app(*, transport: httpx2.AsyncBaseTransport | None = None,
clock: Callable[[], float] = time.time) -> FastAPI:
"""Build the gateway. Tests pass a fake transport (the upstreams) and a fake clock (used from milestone 3)."""
s = settings()
cfg = load_config(s.config_file)
upstreams = Upstreams(cfg.upstreams, transport)
keys = KeyStore(s.db_path)
limiter = RateLimiter(clock)
usage = UsageStore(s.db_path)
budgets = Budgets(usage, clock)
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await upstreams.aclose() # close the pooled connections on shutdown
app = FastAPI(title="LLM gateway", lifespan=lifespan)
@app.exception_handler(GatewayError)
async def gateway_error(request: Request, err: GatewayError):
return error_response(err)
@app.exception_handler(RequestValidationError)
async def bad_request(request: Request, err: RequestValidationError):
first = err.errors()[0]
where = ".".join(str(p) for p in first["loc"] if p != "body")
return JSONResponse(error_body(f"{where}: {first['msg']}", "invalid_request_error"), status_code=400)
def caller(authorization: str | None = Header(default=None)) -> ApiKey:
"""The API key in "Authorization: Bearer gw-...". FastAPI runs this before every endpoint that asks for it."""
if not authorization or not authorization.startswith("Bearer "):
raise GatewayError(401, "missing API key: send Authorization: Bearer <your gateway key>",
"authentication_error", "missing_api_key")
key = keys.lookup(authorization.removeprefix("Bearer ").strip())
if key is None:
raise GatewayError(401, "invalid or revoked API key", "authentication_error", "invalid_api_key")
if key.team not in cfg.teams:
raise GatewayError(403, f"team '{key.team}' is not in gateway.toml", "permission_error", "unknown_team")
return key
def team_of(key: ApiKey) -> Team:
return cfg.teams[key.team]
def route(alias: str, team: Team) -> tuple[Target, ...]:
if alias not in cfg.routes:
raise GatewayError(404, f"model '{alias}' does not exist; use one of: {', '.join(team.models)}",
code="model_not_found")
if alias not in team.models:
raise GatewayError(403, f"team '{team.name}' may not use '{alias}'; allowed: {', '.join(team.models)}",
"permission_error", "model_not_allowed")
return cfg.routes[alias]
def rate_limit(key: ApiKey) -> dict[str, str]:
wait, left = limiter.take(key)
if wait > 0:
raise GatewayError(429, f"rate limit of {key.rpm} requests per minute reached; retry in {wait:.1f} s",
"rate_limit_error", "rate_limit_exceeded",
headers={"Retry-After": str(math.ceil(wait)), "x-ratelimit-remaining-requests": "0"})
return {"x-ratelimit-remaining-requests": str(left)}
def admin(authorization: str | None = Header(default=None)) -> None:
if not s.admin_key:
raise GatewayError(403, "admin endpoints are off: set ADMIN_KEY", "permission_error", "admin_disabled")
given = (authorization or "").removeprefix("Bearer ").strip()
if not hmac.compare_digest(given.encode(), s.admin_key.encode()): # constant time: no timing hints
raise GatewayError(401, "wrong admin key", "authentication_error", "invalid_admin_key")
@app.get("/admin/usage", dependencies=[Depends(admin)])
async def usage_report(day: str | None = None):
"""Usage and cost per team for one UTC day (default: today)."""
day = day or day_of(clock())
rows = usage.report(day)
teams = []
for name, team in cfg.teams.items():
row = rows.get(name, {"requests": 0, "ok": 0, "rejected": 0, "errors": 0, "cache_hits": 0,
"prompt_tokens": 0, "completion_tokens": 0, "cost_usd": 0.0, "avg_latency_ms": None})
used = row["prompt_tokens"] + row["completion_tokens"]
teams.append({"team": name, **{k: v for k, v in row.items() if k != "team"},
"daily_token_budget": team.daily_token_budget,
"budget_used_pct": round(100 * used / team.daily_token_budget, 1) if team.daily_token_budget else None})
return {"day": day, "teams": teams}
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/health/upstreams")
async def health_upstreams():
"""Ask every upstream for its models (GET /models) and say which routed models are missing."""
async def check(name: str) -> dict:
wanted = sorted({t.model for ts in cfg.routes.values() for t in ts if t.upstream == name})
try:
served = await upstreams.models(name)
except Exception as e:
return {"ok": False, "error": type(e).__name__}
return {"ok": True, "models": served, "missing": [m for m in wanted if m not in served]}
results = await asyncio.gather(*(check(n) for n in cfg.upstreams))
report = dict(zip(cfg.upstreams, results))
healthy = all(r["ok"] and not r["missing"] for r in report.values())
return {"status": "ok" if healthy else "degraded", "upstreams": report}
@app.get("/v1/models")
async def list_models(key: ApiKey = Depends(caller)):
return {"object": "list", "data": [{"id": alias, "object": "model", "created": 0, "owned_by": "llm-gateway"}
for alias in team_of(key).models]}
async def call(target: Target, body: dict, stream: bool) -> httpx2.Response:
try:
return await (upstreams.open_stream(target, body) if stream else upstreams.chat(target, body))
except UpstreamError as e:
status = 504 if e.kind == "timeout" else 502
raise GatewayError(status, str(e), "upstream_error", code=f"upstream_{e.kind}") from e
@app.post("/v1/chat/completions")
async def chat(req: ChatRequest, request: Request, key: ApiKey = Depends(caller)):
given_id = request.headers.get("x-request-id", "")
rec = UsageRecord(ts=clock(), request_id=given_id if REQUEST_ID.match(given_id) else uuid.uuid4().hex,
team=key.team, key_id=key.id, route=req.model)
started = time.perf_counter()
team = team_of(key)
reserved = 0
prompt_estimate = estimate_tokens(message_text(req.messages))
def finish(status: int, tokens: dict | None = None, answer_chars: int = 0) -> None:
"""Write the one usage row for this request and give back the budget reservation."""
rec.status = status
rec.latency_ms = round((time.perf_counter() - started) * 1000, 1)
if rec.upstream and (status == 200 or answer_chars): # a broken stream still generated tokens
if tokens:
rec.prompt_tokens, rec.completion_tokens = tokens["prompt_tokens"], tokens["completion_tokens"]
else: # no usage from the upstream (or the caller hung up first): estimate, and say so
rec.prompt_tokens, rec.completion_tokens = prompt_estimate, answer_chars // 4
rec.estimated = True
rec.cost_usd = cost_usd(cfg.prices, rec.upstream.split("/", 1)[1], rec.prompt_tokens, rec.completion_tokens)
usage.record(rec)
budgets.release(team, reserved)
try:
headers = {"x-request-id": rec.request_id, **rate_limit(key)}
target = route(req.model, team)[0]
body = req.model_dump(exclude_unset=True)
max_out = body.get("max_completion_tokens") or body.get("max_tokens") or cfg.default_max_tokens
try:
reserved = budgets.reserve(team, prompt_estimate + max_out)
except BudgetExceeded as e:
raise GatewayError(429, f"{e}; the budget resets at midnight UTC", "rate_limit_error",
"daily_budget_exceeded", headers={"Retry-After": str(math.ceil(e.retry_after_s))})
caller_wants_usage = bool((body.get("stream_options") or {}).get("include_usage"))
if req.stream: # always ask for usage: the gateway needs the token counts
body["stream_options"] = {**(body.get("stream_options") or {}), "include_usage": True}
resp = await call(target, body, req.stream)
rec.upstream = str(target)
headers["x-gateway-upstream"] = str(target)
except GatewayError as e:
finish(e.status)
raise
if resp.status_code != 200: # the upstream refused the request itself (a 4xx): pass it on unchanged
finish(resp.status_code)
return Response(resp.content, resp.status_code, headers=headers,
media_type=resp.headers.get("content-type", "application/json"))
if req.stream:
stats = StreamStats()
async def events():
try:
async for event in relay(resp, stats, caller_wants_usage):
yield event
finally: # runs when the stream ends, breaks, or the caller hangs up: bill what was generated
finish(502 if stats.error else 200, stats.usage, stats.chars)
return StreamingResponse(events(), media_type="text/event-stream",
headers={**headers, "Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
data = resp.json()
finish(200, data.get("usage"))
return JSONResponse(data, headers=headers)
return app - Accept the caller's id only when it is short and plain: it goes into logs and headers, so no newlines and no 10 KB strings.line 25
- A second dependency, for admin endpoints only.line 97
- Compares in constant time: a plain
==stops at the first wrong character, and the timing can leak the key.line 101 - Every configured team, even with no traffic: a report that hides zeros hides problems.line 110
- The one place that writes the usage row and gives the reservation back.line 161
- A stream that broke midway still generated tokens, and the provider bills them.line 165
- The worst case for this request: the prompt plus the most it may write.line 181
- Every refusal and failure still writes its row, then the error goes on to the exception handler.line 191
- Runs when the stream finishes, breaks, or the caller disconnects (the server then cancels the generator).line 206
"""Milestone 4: one usage row per request, cost per team, daily token budgets and the /admin/usage report."""
import sqlite3
import pytest
from budget import BudgetExceeded, Budgets
from config import Team
from fakes import FakeClock
from usage import UsageStore
ADMIN = {"Authorization": "Bearer admin-test-key"}
def rows(gw) -> list[dict]:
with sqlite3.connect(gw.db_path) as db:
db.row_factory = sqlite3.Row
return [dict(r) for r in db.execute("SELECT * FROM usage ORDER BY id")]
def test_every_request_with_a_valid_key_gets_one_usage_row(gateway):
gw = gateway()
gw.chat("fast")
gw.chat("smart")
gw.chat("nope") # 404, still recorded: it came with a valid key
r = rows(gw)
assert [(x["route"], x["upstream"], x["status"]) for x in r] == [
("fast", "ollama/llama3.2:3b", 200), ("smart", "hosted/hosted-large", 200), ("nope", None, 404)]
assert (r[0]["prompt_tokens"], r[0]["completion_tokens"], r[0]["cost_usd"]) == (20, 5, 0.0)
assert r[1]["cost_usd"] == pytest.approx((1000 * 3.00 + 200 * 15.00) / 1_000_000) # 0.006
assert r[0]["day"] == "2026-11-20" and r[0]["team"] == "search"
def test_requests_without_a_valid_key_are_not_recorded(gateway):
gw = gateway()
gw.client.headers["Authorization"] = "Bearer gw-wrong"
gw.chat()
assert rows(gw) == []
def test_the_request_id_is_returned_and_recorded(gateway):
gw = gateway()
r = gw.client.post("/v1/chat/completions", headers={"x-request-id": "job-42"},
json={"model": "fast", "messages": [{"role": "user", "content": "Hi"}]})
assert r.headers["x-request-id"] == "job-42"
assert len(gw.chat().headers["x-request-id"]) == 32 # none given: the gateway makes one
assert rows(gw)[0]["request_id"] == "job-42"
def test_streams_are_billed_from_the_usage_chunk(gateway):
gw = gateway()
gw.chat("smart", stream=True).read()
row = rows(gw)[0]
assert (row["prompt_tokens"], row["completion_tokens"], row["estimated"]) == (1000, 200, 0)
def test_a_broken_stream_is_still_billed_as_an_estimate(gateway):
gw = gateway()
gw.ollama.break_stream_after = 2 # "Hello from" was generated, then the upstream died
gw.chat("fast", stream=True).read()
row = rows(gw)[0]
assert row["status"] == 502 and row["estimated"] == 1 and row["completion_tokens"] == len("Hello from") // 4
def test_daily_budget_refuses_before_calling_the_upstream(gateway):
gw = gateway(team="support") # 1,000 tokens a day; default_max_tokens = 100 is reserved per request
gw.ollama.completion_tokens = 450 # each answer uses 20 + 450 = 470 tokens
assert gw.chat().status_code == 200 # used 470
assert gw.chat().status_code == 200 # used 940
r = gw.chat() # 940 + 101 reserved (1 for "Hi", 100 for the answer) > 1,000
assert r.status_code == 429
assert r.json()["error"]["code"] == "daily_budget_exceeded"
assert r.headers["Retry-After"] == str(12 * 3600) # the fake clock says 12:00 UTC
assert gw.ollama.calls == 2
gw.clock.advance(12 * 3600) # midnight: a new day, a new budget
assert gw.chat().status_code == 200
def test_reservations_count_until_released(tmp_path):
budgets = Budgets(UsageStore(tmp_path / "usage.db"), FakeClock())
team = Team("t", ("fast",), daily_token_budget=1000)
budgets.reserve(team, 600)
with pytest.raises(BudgetExceeded):
budgets.reserve(team, 600) # the first request is still running: its 600 are not free yet
budgets.release(team, 600)
budgets.reserve(team, 600)
def test_max_tokens_is_what_gets_reserved(gateway):
gw = gateway(team="support")
assert gw.chat(max_tokens=2000).status_code == 429 # could use more than the whole budget
assert gw.chat(max_tokens=50).status_code == 200
def test_admin_usage_report(gateway):
gw = gateway()
gw.chat("fast")
gw.chat("smart")
gw.hosted.fail = gw.ollama.fail = 500
gw.chat("smart")
assert gw.client.get("/admin/usage").status_code == 401 # a team key is not an admin key
report = gw.client.get("/admin/usage", headers=ADMIN).json()
assert report["day"] == "2026-11-20"
search = next(t for t in report["teams"] if t["team"] == "search")
assert (search["requests"], search["ok"], search["errors"]) == (3, 2, 1)
assert (search["prompt_tokens"], search["completion_tokens"]) == (1020, 205)
assert search["cost_usd"] == pytest.approx(0.006)
assert search["budget_used_pct"] == pytest.approx(12.2, abs=0.1) # 1,225 of 10,000
support = next(t for t in report["teams"] if t["team"] == "support")
assert support["requests"] == 0 # every team is listed, even without traffic
def test_admin_endpoints_are_off_without_an_admin_key(gateway, monkeypatch):
monkeypatch.setenv("ADMIN_KEY", "")
gw = gateway()
assert gw.client.get("/admin/usage", headers={"Authorization": "Bearer "}).status_code == 403 - The invariant the whole bill rests on.line 20
len("Hello from") // 4tokens, markedestimated.line 56- The fake upstream reports bigger answers, so the 1,000 token budget runs out after two requests.line 66
- Midnight UTC: a new day, and the same team may call again.line 74
- Two requests at the same time: the second sees the first one's reservation.line 78
uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py
uv run try_gateway.py
uv run try_gateway.py --stream
curl -s localhost:8080/admin/usage -H "Authorization: Bearer change-me-to-a-long-random-string" | uv run python -m json.tooluv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py
uv run try_gateway.py
uv run try_gateway.py --stream
curl -s localhost:8080/admin/usage -H "Authorization: Bearer change-me-to-a-long-random-string" | uv run python -m json.tooluv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py
uv run try_gateway.py
uv run try_gateway.py --stream
curl.exe -s localhost:8080/admin/usage -H "Authorization: Bearer change-me-to-a-long-random-string" | uv run python -m json.tool ........................................ [100%]
40 passed in 1.97s
models: ['fast', 'smart']
[ollama/llama3.2:3b] An API gateway is a single entry point that receives client requests and routes them to the right backend services.
usage: 38 in, 24 out
models: ['fast', 'smart']
An API gateway is a single entry point for clients that routes each request to the right backend service.
{
"day": "2026-11-29",
"teams": [
{
"team": "search",
"requests": 3,
"ok": 3,
"rejected": 0,
"errors": 0,
"cache_hits": 0,
"prompt_tokens": 114,
"completion_tokens": 71,
"cost_usd": 0.0,
"avg_latency_ms": 812.4,
"daily_token_budget": 200000,
"budget_used_pct": 0.1
},
{
"team": "support",
"requests": 0,
...
"daily_token_budget": 50000,
"budget_used_pct": 0.0
}
]
} Stuck on this milestone?
- The report shows more requests than you made
- Each
try_gateway.pyrun makes one chat request (themodelscall is not a chat request and is not recorded). The curl loop from milestone 3 also counted, refusals included. cost_usdis always 0- Correct for
llama3.2:3b: its price row is 0. Milestone 5 adds the hosted upstream, whose example prices are not 0. - A test fails with a usage row missing for a streamed request
- The row is written in the stream generator's
finally, so the response must be read to the end first. The tests call.read()or.textfor that. - The day in the report is "tomorrow" or "yesterday"
- Days are UTC on purpose, so every team's budget resets at the same moment. Pass
?day=YYYY-MM-DDto see another day.
Routing: fallback to the next upstream, and circuit breakers
A route tries its targets in order; a failure before the first byte falls back to the next target, and a target that keeps failing is skipped for a while.
Now the second upstream. fake_hosted.py stands in for a paid API, so you can watch fallback without an account or a bill. It is a small FastAPI app on port 9001 (start it with uv run fake_hosted.py) that serves hosted-small and hosted-large on /v1/models and /v1/chat/completions (normal and streaming, with include_usage), checks Authorization: Bearer <HOSTED_API_KEY> (401 otherwise), answers 404 for other models, and has two switches: --fail-rate 1 makes every request fail with 503 (an outage), --delay 40 answers after 40 seconds (longer than the gateway's 30 second timeout for it).
router.py: CircuitBreaker(failures, cooldown_s, clock) with state ("closed", "open" or "half_open"), allow() -> bool, success(), failure() and retry_after() -> float. Closed: every request is allowed; failures failures in a row open it (a success resets the count). Open: nothing is allowed until cooldown_s have passed since it opened; retry_after() says how long is left. Then half-open: allow() lets exactly one trial request through (and another only if that one has not reported back within cooldown_s); the trial's success() closes the breaker, its failure() opens it again at once. Router(cfg, clock) keeps one breaker per target ("ollama/llama3.2:3b"), shared by every route that uses that target, with breaker(target) and states() -> {"ollama/llama3.2:3b": "closed", ...}.
app.py: chat now tries the route's targets in order. Skip a target whose breaker does not allow it. Call it; an UpstreamError is the breaker's failure() and a reason to try the next target; any answer (even a 400) is its success() and the result. Fallback applies to streams too, because open_stream fails before anything reaches the caller; a stream that breaks later never switches model. When every target failed, answer as in milestone 1 with the last error's kind (502 or 504), and a message listing every problem. When every breaker was open and nothing was tried, answer 503 no_upstream_available with Retry-After (the shortest retry_after(), at least 1). New response header x-gateway-attempts: how many targets were actually tried. The usage row and x-gateway-upstream name the target that answered, so the cost is that model's price. /health/upstreams adds "breakers": router.states(), and an open breaker makes the status degraded.
Fallback only sees failures the gateway can measure: no connection, a timeout, an error status. A small model that answers 200 with a poor answer (a tool call written as text, a guess instead of a search, "could you give me the order id?" instead of acting) is a success here. Those are checked in the app, in code, as the support agent capstone does; the stretch goals show how a gateway could add one narrow quality check.
uv run pytest -qpasses for milestones 1 to 5 (52 tests): runuv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py tests/test_m5.py.- With
uv run fake_hosted.pyrunning,uv run try_gateway.py --model smartis answered by[hosted/hosted-large]. - Restart it with
--fail-rate 1: the first threesmartrequests sayx-gateway-attempts: 2(hosted failed, ollama answered), the fourth says1, and/health/upstreamsshows"hosted/hosted-large": "open".
Hints
- Write the loop in one function,
async def call(alias, body, stream), that returns(target, response, tried). It replaces milestone 2'scall: the endpoint no longer picks the target itself. - Keep the breaker free of I/O: it only reads the clock. Then the tests can open and close it with
clock.advance(), andtest_circuit_breaker_statesneeds no gateway at all. - Call
allow()only right before you really try that target: in half-open it hands out the one trial slot. - Distinguish "all tried and failed" from "nothing was tried" by remembering the last
UpstreamError: if it is stillNoneafter the loop, every breaker was open.
Show the reference solution for milestone 5
Try it yourself first. This is one good way to do it, not the only one.
"""A stand-in for a paid, hosted model API, so you can see fallback and breakers without paying anyone.
uv run fake_hosted.py # healthy, on port 9001
uv run fake_hosted.py --fail-rate 1 # every request fails with 503 (an outage)
uv run fake_hosted.py --delay 40 # answers after 40 seconds (slower than the gateway's timeout)"""
import argparse
import asyncio
import json
import os
import random
import time
import uvicorn
from dotenv import load_dotenv
from fastapi import FastAPI, Header, Request
from fastapi.responses import JSONResponse, StreamingResponse
load_dotenv()
MODELS = ["hosted-small", "hosted-large"]
opts = argparse.Namespace(fail_rate=0.0, delay=0.0)
app = FastAPI(title="Fake hosted model API")
def error(status: int, message: str) -> JSONResponse:
return JSONResponse({"error": {"message": message, "type": "server_error"}}, status_code=status)
@app.get("/v1/models")
async def models():
return {"object": "list", "data": [{"id": m, "object": "model", "created": 0, "owned_by": "fake-hosted"} for m in MODELS]}
@app.post("/v1/chat/completions")
async def chat(request: Request, authorization: str = Header(default="")):
if authorization != f"Bearer {os.environ.get('HOSTED_API_KEY', 'fake-hosted-key')}":
return error(401, "invalid API key")
body = await request.json()
if body.get("model") not in MODELS:
return error(404, f"model {body.get('model')!r} not found")
await asyncio.sleep(opts.delay)
if random.random() < opts.fail_rate:
return error(503, "the fake hosted API is having an outage")
question = str(body["messages"][-1].get("content", ""))
words = f"({body['model']}) A canned answer from the fake hosted API. You asked: {question[:60]}".split(" ")
usage = {"prompt_tokens": sum(len(str(m.get("content", ""))) for m in body["messages"]) // 4 + 1,
"completion_tokens": len(words)}
usage["total_tokens"] = usage["prompt_tokens"] + usage["completion_tokens"]
base = {"id": f"chatcmpl-{int(time.time() * 1000)}", "created": int(time.time()), "model": body["model"]}
if not body.get("stream"):
return {**base, "object": "chat.completion", "usage": usage,
"choices": [{"index": 0, "message": {"role": "assistant", "content": " ".join(words)}, "finish_reason": "stop"}]}
async def events():
for i, w in enumerate(words):
delta = {"role": "assistant", "content": w} if i == 0 else {"content": " " + w}
yield f"data: {json.dumps({**base, 'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': None}]})}\n\n"
await asyncio.sleep(0.02)
yield f"data: {json.dumps({**base, 'object': 'chat.completion.chunk', 'choices': [{'index': 0, 'delta': {}, 'finish_reason': 'stop'}]})}\n\n"
if (body.get("stream_options") or {}).get("include_usage"):
yield f"data: {json.dumps({**base, 'object': 'chat.completion.chunk', 'choices': [], 'usage': usage})}\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(events(), media_type="text/event-stream")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="A fake hosted model API.")
parser.add_argument("--port", type=int, default=9001)
parser.add_argument("--fail-rate", type=float, default=0.0, help="share of requests that fail with 503, 0 to 1")
parser.add_argument("--delay", type=float, default=0.0, help="seconds to wait before answering")
opts = parser.parse_args()
uvicorn.run(app, host="127.0.0.1", port=opts.port, log_level="warning") - Module-level options, replaced by the command line in
__main__: the endpoints read them on every request.line 19 - Like a real provider: a wrong key is 401. The gateway turns that into
upstream_authand falls back.line 34 asyncio.sleep, nottime.sleep: an async server must never block its event loop.line 39--fail-rate 0.3fails about 30% of requests: closer to a real bad day than a full outage.line 40- The usage chunk at the end, as OpenAI and Ollama send it.line 58
from collections.abc import Callable
from config import GatewayConfig, Target
class CircuitBreaker:
"""Stops sending requests to a target that keeps failing.
closed: requests flow. `failures` failures in a row open it.
open: requests skip this target for `cooldown_s` seconds.
half_open: after the cooldown, one trial request goes through. Success closes it; failure opens it again."""
def __init__(self, failures: int, cooldown_s: float, clock: Callable[[], float]):
self.threshold, self.cooldown_s, self.clock = failures, cooldown_s, clock
self.state = "closed"
self.failures = 0
self.opened_at = 0.0
self.trial_at: float | None = None # when the half-open trial request started
def allow(self) -> bool:
now = self.clock()
if self.state == "closed":
return True
if self.state == "open" and now - self.opened_at >= self.cooldown_s:
self.state, self.trial_at = "half_open", None
if self.state == "half_open" and (self.trial_at is None or now - self.trial_at >= self.cooldown_s):
self.trial_at = now # let exactly one request through (or another, if that one never reported back)
return True
return False
def success(self) -> None:
self.state, self.failures, self.trial_at = "closed", 0, None
def failure(self) -> None:
self.failures += 1
if self.state == "half_open" or self.failures >= self.threshold:
self.state, self.opened_at, self.trial_at = "open", self.clock(), None
def retry_after(self) -> float:
return max(0.0, self.opened_at + self.cooldown_s - self.clock()) if self.state == "open" else 0.0
class Router:
"""One breaker per target ("ollama/llama3.2:3b"), shared by every route that uses that target."""
def __init__(self, cfg: GatewayConfig, clock: Callable[[], float]):
self.routes = cfg.routes
self.breakers = {str(t): CircuitBreaker(cfg.breaker_failures, cfg.breaker_cooldown_s, clock)
for targets in cfg.routes.values() for t in targets}
def breaker(self, target: Target) -> CircuitBreaker:
return self.breakers[str(target)]
def states(self) -> dict[str, str]:
return {name: b.state for name, b in self.breakers.items()} - The same pattern as Resilience4j in Java: stop hammering a server that is down, so it can recover and your callers fail fast.line 6
- No timer thread: the state changes when someone asks and enough time has passed.line 23
- One trial at a time. If the trial never reports back (the caller left), another one is allowed after the cooldown, so the breaker cannot stick half-open.line 26
- A failed trial opens it again at once; in the closed state it takes
failuresfailures in a row.line 35 - A dict comprehension over every target of every route;
ollama/llama3.2:3bappears twice, so it gets one breaker that both routes share.line 48
import asyncio
import hmac
import math
import re
import time
import uuid
from contextlib import asynccontextmanager
from typing import Any, Callable
import httpx2
from fastapi import Depends, FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from budget import BudgetExceeded, Budgets
from config import Target, Team, load_config, settings
from errors import GatewayError, error_body, error_response
from keys import ApiKey, KeyStore
from ratelimit import RateLimiter
from router import Router
from streaming import StreamStats, relay
from upstream import UpstreamError, Upstreams
from usage import UsageRecord, UsageStore, cost_usd, day_of, estimate_tokens, message_text
REQUEST_ID = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
class ChatRequest(BaseModel):
"""What the gateway checks. Every other field (temperature, max_tokens, tools...) is passed through."""
model_config = ConfigDict(extra="allow")
model: str = Field(min_length=1)
messages: list[dict[str, Any]] = Field(min_length=1)
stream: bool = False
def create_app(*, transport: httpx2.AsyncBaseTransport | None = None,
clock: Callable[[], float] = time.time) -> FastAPI:
"""Build the gateway. Tests pass a fake transport (the upstreams) and a fake clock (used from milestone 3)."""
s = settings()
cfg = load_config(s.config_file)
upstreams = Upstreams(cfg.upstreams, transport)
keys = KeyStore(s.db_path)
limiter = RateLimiter(clock)
usage = UsageStore(s.db_path)
budgets = Budgets(usage, clock)
router = Router(cfg, clock)
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await upstreams.aclose() # close the pooled connections on shutdown
app = FastAPI(title="LLM gateway", lifespan=lifespan)
@app.exception_handler(GatewayError)
async def gateway_error(request: Request, err: GatewayError):
return error_response(err)
@app.exception_handler(RequestValidationError)
async def bad_request(request: Request, err: RequestValidationError):
first = err.errors()[0]
where = ".".join(str(p) for p in first["loc"] if p != "body")
return JSONResponse(error_body(f"{where}: {first['msg']}", "invalid_request_error"), status_code=400)
def caller(authorization: str | None = Header(default=None)) -> ApiKey:
"""The API key in "Authorization: Bearer gw-...". FastAPI runs this before every endpoint that asks for it."""
if not authorization or not authorization.startswith("Bearer "):
raise GatewayError(401, "missing API key: send Authorization: Bearer <your gateway key>",
"authentication_error", "missing_api_key")
key = keys.lookup(authorization.removeprefix("Bearer ").strip())
if key is None:
raise GatewayError(401, "invalid or revoked API key", "authentication_error", "invalid_api_key")
if key.team not in cfg.teams:
raise GatewayError(403, f"team '{key.team}' is not in gateway.toml", "permission_error", "unknown_team")
return key
def team_of(key: ApiKey) -> Team:
return cfg.teams[key.team]
def check_route(alias: str, team: Team) -> None:
if alias not in cfg.routes:
raise GatewayError(404, f"model '{alias}' does not exist; use one of: {', '.join(team.models)}",
code="model_not_found")
if alias not in team.models:
raise GatewayError(403, f"team '{team.name}' may not use '{alias}'; allowed: {', '.join(team.models)}",
"permission_error", "model_not_allowed")
def rate_limit(key: ApiKey) -> dict[str, str]:
wait, left = limiter.take(key)
if wait > 0:
raise GatewayError(429, f"rate limit of {key.rpm} requests per minute reached; retry in {wait:.1f} s",
"rate_limit_error", "rate_limit_exceeded",
headers={"Retry-After": str(math.ceil(wait)), "x-ratelimit-remaining-requests": "0"})
return {"x-ratelimit-remaining-requests": str(left)}
def admin(authorization: str | None = Header(default=None)) -> None:
if not s.admin_key:
raise GatewayError(403, "admin endpoints are off: set ADMIN_KEY", "permission_error", "admin_disabled")
given = (authorization or "").removeprefix("Bearer ").strip()
if not hmac.compare_digest(given.encode(), s.admin_key.encode()): # constant time: no timing hints
raise GatewayError(401, "wrong admin key", "authentication_error", "invalid_admin_key")
@app.get("/admin/usage", dependencies=[Depends(admin)])
async def usage_report(day: str | None = None):
"""Usage and cost per team for one UTC day (default: today)."""
day = day or day_of(clock())
rows = usage.report(day)
teams = []
for name, team in cfg.teams.items():
row = rows.get(name, {"requests": 0, "ok": 0, "rejected": 0, "errors": 0, "cache_hits": 0,
"prompt_tokens": 0, "completion_tokens": 0, "cost_usd": 0.0, "avg_latency_ms": None})
used = row["prompt_tokens"] + row["completion_tokens"]
teams.append({"team": name, **{k: v for k, v in row.items() if k != "team"},
"daily_token_budget": team.daily_token_budget,
"budget_used_pct": round(100 * used / team.daily_token_budget, 1) if team.daily_token_budget else None})
return {"day": day, "teams": teams}
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/health/upstreams")
async def health_upstreams():
"""Ask every upstream for its models (GET /models) and say which routed models are missing."""
async def check(name: str) -> dict:
wanted = sorted({t.model for ts in cfg.routes.values() for t in ts if t.upstream == name})
try:
served = await upstreams.models(name)
except Exception as e:
return {"ok": False, "error": type(e).__name__}
return {"ok": True, "models": served, "missing": [m for m in wanted if m not in served]}
results = await asyncio.gather(*(check(n) for n in cfg.upstreams))
report = dict(zip(cfg.upstreams, results))
breakers = router.states()
healthy = all(r["ok"] and not r["missing"] for r in report.values()) and "open" not in breakers.values()
return {"status": "ok" if healthy else "degraded", "upstreams": report, "breakers": breakers}
@app.get("/v1/models")
async def list_models(key: ApiKey = Depends(caller)):
return {"object": "list", "data": [{"id": alias, "object": "model", "created": 0, "owned_by": "llm-gateway"}
for alias in team_of(key).models]}
async def call(alias: str, body: dict, stream: bool) -> tuple[Target, httpx2.Response, int]:
"""Try the route's targets in order, skipping open breakers, until one answers.
Returns (the target that answered, its response, how many targets were tried)."""
problems, last, tried = [], None, 0
for target in cfg.routes[alias]:
breaker = router.breaker(target)
if not breaker.allow():
problems.append(f"{target}: circuit open")
continue
tried += 1
try:
resp = await (upstreams.open_stream(target, body) if stream else upstreams.chat(target, body))
except UpstreamError as e:
breaker.failure()
problems.append(str(e))
last = e
continue # fall back to the next target: nothing has been sent to the caller yet
breaker.success() # it answered; even a 400 proves the upstream is up
return target, resp, tried
if last is None: # every breaker was open: do not even try
wait = min(router.breaker(t).retry_after() for t in cfg.routes[alias])
raise GatewayError(503, f"no upstream available for '{alias}': {'; '.join(problems)}", "upstream_error",
"no_upstream_available", headers={"Retry-After": str(max(1, math.ceil(wait)))})
status = 504 if last.kind == "timeout" else 502
raise GatewayError(status, "; ".join(problems), "upstream_error", code=f"upstream_{last.kind}")
@app.post("/v1/chat/completions")
async def chat(req: ChatRequest, request: Request, key: ApiKey = Depends(caller)):
given_id = request.headers.get("x-request-id", "")
rec = UsageRecord(ts=clock(), request_id=given_id if REQUEST_ID.match(given_id) else uuid.uuid4().hex,
team=key.team, key_id=key.id, route=req.model)
started = time.perf_counter()
team = team_of(key)
reserved = 0
prompt_estimate = estimate_tokens(message_text(req.messages))
def finish(status: int, tokens: dict | None = None, answer_chars: int = 0) -> None:
"""Write the one usage row for this request and give back the budget reservation."""
rec.status = status
rec.latency_ms = round((time.perf_counter() - started) * 1000, 1)
if rec.upstream and (status == 200 or answer_chars): # a broken stream still generated tokens
if tokens:
rec.prompt_tokens, rec.completion_tokens = tokens["prompt_tokens"], tokens["completion_tokens"]
else: # no usage from the upstream (or the caller hung up first): estimate, and say so
rec.prompt_tokens, rec.completion_tokens = prompt_estimate, answer_chars // 4
rec.estimated = True
rec.cost_usd = cost_usd(cfg.prices, rec.upstream.split("/", 1)[1], rec.prompt_tokens, rec.completion_tokens)
usage.record(rec)
budgets.release(team, reserved)
try:
headers = {"x-request-id": rec.request_id, **rate_limit(key)}
check_route(req.model, team)
body = req.model_dump(exclude_unset=True)
max_out = body.get("max_completion_tokens") or body.get("max_tokens") or cfg.default_max_tokens
try:
reserved = budgets.reserve(team, prompt_estimate + max_out)
except BudgetExceeded as e:
raise GatewayError(429, f"{e}; the budget resets at midnight UTC", "rate_limit_error",
"daily_budget_exceeded", headers={"Retry-After": str(math.ceil(e.retry_after_s))})
caller_wants_usage = bool((body.get("stream_options") or {}).get("include_usage"))
if req.stream: # always ask for usage: the gateway needs the token counts
body["stream_options"] = {**(body.get("stream_options") or {}), "include_usage": True}
target, resp, tried = await call(req.model, body, req.stream)
rec.upstream = str(target)
headers |= {"x-gateway-upstream": str(target), "x-gateway-attempts": str(tried)}
except GatewayError as e:
finish(e.status)
raise
if resp.status_code != 200: # the upstream refused the request itself (a 4xx): pass it on unchanged
finish(resp.status_code)
return Response(resp.content, resp.status_code, headers=headers,
media_type=resp.headers.get("content-type", "application/json"))
if req.stream:
stats = StreamStats()
async def events():
try:
async for event in relay(resp, stats, caller_wants_usage):
yield event
finally: # runs when the stream ends, breaks, or the caller hangs up: bill what was generated
finish(502 if stats.error else 200, stats.usage, stats.chars)
return StreamingResponse(events(), media_type="text/event-stream",
headers={**headers, "Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
data = resp.json()
finish(200, data.get("usage"))
return JSONResponse(data, headers=headers)
return app - The router: in order, skipping open breakers, until one target answers.line 146
- An open breaker costs nothing: no connection attempt, no timeout to wait for.line 152
- Safe because nothing has been sent to the caller yet, even for a stream.line 162
- A 400 means the upstream is up and the request was bad. It must not count against the upstream.line 163
- Nothing was tried: 503 with a
Retry-After, so well-behaved clients wait instead of hammering.line 165 |=adds keys to a dict in place.line 211- Operations can see at a glance which targets are being skipped.line 139
"""Milestone 5: routes fall back to the next target on failures, and circuit breakers skip a target that keeps failing."""
import sqlite3
import pytest
from fakes import FakeClock, sse_events
from router import CircuitBreaker
@pytest.mark.parametrize("fail", [503, 429, "timeout", "connect"])
def test_fast_falls_back_to_hosted_small(gateway, fail):
gw = gateway()
gw.ollama.fail = fail
r = gw.chat("fast")
assert r.status_code == 200
assert r.json()["choices"][0]["message"]["content"] == "Hello from hosted."
assert (r.headers["x-gateway-upstream"], r.headers["x-gateway-attempts"]) == ("hosted/hosted-small", "2")
assert gw.hosted.requests[0]["model"] == "hosted-small"
def test_the_usage_row_names_the_target_that_answered(gateway):
gw = gateway()
gw.ollama.fail = 500
gw.chat("fast")
with sqlite3.connect(gw.db_path) as db:
upstream, cost = db.execute("SELECT upstream, cost_usd FROM usage").fetchone()
assert upstream == "hosted/hosted-small"
assert cost == pytest.approx((1000 * 0.15 + 200 * 0.60) / 1_000_000)
def test_a_bad_request_does_not_fall_back(gateway):
gw = gateway()
gw.ollama.fail = 400
assert gw.chat("fast").status_code == 400
assert gw.hosted.calls == 0
def test_the_breaker_opens_and_skips_the_failing_target(gateway):
gw = gateway() # test config: the breaker opens after 2 failures, for 30 seconds
gw.ollama.fail = 503
gw.chat("fast")
gw.chat("fast")
assert gw.ollama.calls == 2
r = gw.chat("fast")
assert r.status_code == 200 and r.headers["x-gateway-attempts"] == "1" # ollama skipped, not tried
assert gw.ollama.calls == 2
assert gw.client.get("/health/upstreams").json()["breakers"]["ollama/llama3.2:3b"] == "open"
gw.chat("smart") # smart's fallback is the same target: it shares the breaker
assert gw.ollama.calls == 2
def test_after_the_cooldown_one_trial_request_closes_it(gateway):
gw = gateway()
gw.ollama.fail = 503
gw.chat("fast")
gw.chat("fast")
gw.ollama.fail = None # ollama is back
gw.clock.advance(30)
r = gw.chat("fast")
assert r.headers["x-gateway-upstream"] == "ollama/llama3.2:3b"
assert gw.client.get("/health/upstreams").json()["breakers"]["ollama/llama3.2:3b"] == "closed"
def test_every_breaker_open_is_503_with_retry_after(gateway):
gw = gateway()
gw.ollama.fail = gw.hosted.fail = 503
gw.chat("fast")
r = gw.chat("fast") # both targets have now failed twice: both breakers open
assert r.status_code == 502
calls = gw.ollama.calls + gw.hosted.calls
gw.clock.advance(10)
r = gw.chat("fast")
assert r.status_code == 503
assert r.json()["error"]["code"] == "no_upstream_available"
assert r.headers["Retry-After"] == "20"
assert gw.ollama.calls + gw.hosted.calls == calls # nothing was sent upstream
def test_streams_fall_back_before_the_first_event(gateway):
gw = gateway()
gw.ollama.fail = "connect"
r = gw.chat("fast", stream=True)
assert r.headers["x-gateway-upstream"] == "hosted/hosted-small"
assert sse_events(r.text)[-1] == "[DONE]"
def test_a_stream_that_breaks_midway_does_not_switch_models(gateway):
gw = gateway()
gw.ollama.break_stream_after = 1
events = sse_events(gw.chat("fast", stream=True).text)
assert events[-1]["error"]["code"] == "upstream_stream_broken"
assert gw.hosted.calls == 0 # half an answer from one model plus half from another would be wrong
def test_circuit_breaker_states():
clock = FakeClock()
b = CircuitBreaker(failures=3, cooldown_s=30, clock=clock)
b.failure(); b.failure()
assert b.state == "closed" and b.allow()
b.success() # a success resets the count: only failures in a row open it
b.failure(); b.failure(); b.failure()
assert b.state == "open" and not b.allow()
assert b.retry_after() == 30
clock.advance(30)
assert b.allow() and b.state == "half_open"
assert not b.allow() # only one trial at a time
b.failure() # the trial failed: open again at once
assert b.state == "open" and not b.allow() - One test, four kinds of failure. Like JUnit's
@ParameterizedTest.line 10 - The breaker is open, so the third request did not even try ollama: one attempt, at hosted.line 45
- Breakers belong to targets, not routes.line 48
- Opened at t=0 with a 30 second cooldown, asked at t=10.line 75
- Fallback before the first byte only.line 87
uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py tests/test_m5.py
uv run fake_hosted.py &
sleep 2
uv run try_gateway.py --model smart "What is a circuit breaker?"
uv run try_gateway.py --model fast "What is a circuit breaker?"uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py tests/test_m5.py
uv run fake_hosted.py &
sleep 2
uv run try_gateway.py --model smart "What is a circuit breaker?"
uv run try_gateway.py --model fast "What is a circuit breaker?"uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py tests/test_m5.py
uv run try_gateway.py --model smart "What is a circuit breaker?"
uv run try_gateway.py --model fast "What is a circuit breaker?" .................................................... [100%] 52 passed in 2.55s models: ['fast', 'smart'] [hosted/hosted-large] (hosted-large) A canned answer from the fake hosted API. You asked: What is a circuit breaker? usage: 7 in, 16 out models: ['fast', 'smart'] [ollama/llama3.2:3b] A circuit breaker stops calls to a failing service for a while so it can recover and callers fail fast. usage: 36 in, 21 out
Stuck on this milestone?
smartanswers from ollama even thoughfake_hosted.pyruns- The hosted upstream refused the gateway's key (
upstream_auth, visible in the error message when you stop ollama). The gateway sendsHOSTED_API_KEYfrom its.env, and the fake checks the same variable from the same.env: start both from the project folder. - Port 9001 is already in use
- An old
fake_hosted.pyis still running in the background. Stop it (kill %1in the terminal that started it, or find its process withlsof -i :9001on macOS and Linux) and start it again. Or use--port 9002and setUPSTREAM_HOSTED_URL=http://localhost:9002/v1in.env. - How do I restart it with
--fail-rate 1? kill %1(macOS and Linux, in the terminal that started it), thenuv run fake_hosted.py --fail-rate 1 &. On Windows, Ctrl+C in its terminal and start it again with the flag.- Windows: where does
fake_hosted.pyrun? - In a third terminal, in the project folder:
uv run fake_hosted.py. The Windows tab of the command assumes it is already running. - After the hosted outage ends,
smartstill answers from ollama for a while - That is the breaker: open for
cooldown_s(30 seconds), then one trial request closes it.
An exact-match response cache with a TTL
The same deterministic request from the same team, within the TTL, is answered from memory: no upstream call, no cost, no budget used.
Many requests repeat: the same classification of the same ticket, an eval suite run again, a batch job retried. At temperature 0 the answer would be the same anyway (or nearly: some servers are not perfectly deterministic), so the gateway can return the stored one in a millisecond.
cache.py: cacheable(body) -> bool is true only when temperature is exactly 0 (a missing temperature means the server's default, usually 1), n is 1 or missing, and the request does not stream. cache_key(team, body) -> str is the SHA-256 of a JSON dump with sort_keys=True of the team and the body without stream, stream_options, user and metadata (fields that do not change the answer). Everything else is in the key: the route, the messages, max_tokens, tools... ResponseCache(ttl_s, max_entries, clock) with get(key) -> dict | None, put(key, value) and stats() -> {"entries", "hits", "misses", "hit_rate"} (hit_rate rounded to 3 places, None before any lookup). Entries expire ttl_s seconds after they were stored (an entry stored at t is gone at t + ttl), and when there are more than max_entries, the least recently used one goes.
app.py: after the route check and before the budget check, look the request up when it is cacheable and the caller did not send Cache-Control: no-cache. A hit returns the stored body with x-gateway-cache: hit and the x-gateway-upstream of the target that first answered it; its usage row has cached set, the original token counts, and cost 0, and it reserves no budget (so it counts in the report's cache_hits but not in its tokens). A miss calls the upstream as before and stores only a 200 answer. Every answer says x-gateway-cache: hit, miss (cacheable, not found) or bypass (not cacheable, or no-cache). GET /admin/cache (admin key) returns stats().
The cache is per team on purpose: teams send different data, and one team must never get an answer built from another team's prompt. It also does not change what the app sees at temperature 0, only how fast and cheap it is. There is one trap with small models: an app that sends the identical request again, hoping for a better answer after a bad one (a tool call written as text, a refusal), now gets the same bad answer instantly. Retry with a changed prompt (a nudge, like the support agent capstone does): that is a new key.
Why not a semantic cache? A semantic cache embeds the prompt and returns a stored answer when a previous prompt is similar enough. It finds more hits, and some of them are wrong: "refund order 1182" and "refund order 1183" embed almost identically. Real embedding scores are also bunched together (with nomic-embed-text, often 0.5 to 0.85 for unrelated and related texts alike), so a threshold like 0.65 lets weak matches through and even 0.95 needs testing on your own traffic. If you add one, make it opt-in per route, for FAQ-style prompts without user data, never across teams, with a short TTL, and measure the false-hit rate.
- The tests for milestones 1 to 6 pass (62 tests):
uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py tests/test_m5.py tests/test_m6.py. - Sending the same request at
"temperature": 0twice (the curl command below) showsx-gateway-cache: miss, thenx-gateway-cache: hit. /admin/cacheshows"hits": 1, "misses": 1.
Hints
collections.OrderedDictremembers insertion order and hasmove_to_end(key)andpopitem(last=False)(remove the oldest). That is a whole LRU cache in a dozen lines.- Store
(expires_at, value)per key. Onget, an expired entry counts as a miss and is deleted. json.dumps(..., sort_keys=True, separators=(",", ":"))gives the same text for the same data whatever the key order, so{"a": 1, "b": 2}and{"b": 2, "a": 1}hash the same.- Store
{"body": data, "upstream": str(target)}, not just the body: a hit must report which target produced it.
Show the reference solution for milestone 6
Try it yourself first. This is one good way to do it, not the only one.
import hashlib
import json
from collections import OrderedDict
from collections.abc import Callable
# Fields that do not change the answer, so they are left out of the key.
NOT_IN_KEY = {"stream", "stream_options", "user", "metadata"}
def cacheable(body: dict) -> bool:
"""Only answers that would come out the same anyway: temperature 0, one choice, not streamed."""
return body.get("temperature") == 0 and body.get("n", 1) == 1 and not body.get("stream")
def cache_key(team: str, body: dict) -> str:
"""Same team, same route, same messages, same parameters: same key. JSON key order does not matter."""
material = {k: v for k, v in body.items() if k not in NOT_IN_KEY}
raw = json.dumps({"team": team, "request": material}, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(raw.encode()).hexdigest()
class ResponseCache:
"""An exact-match cache in memory: entries expire after ttl_s, and the least recently used entry
is dropped when there are more than max_entries."""
def __init__(self, ttl_s: float, max_entries: int, clock: Callable[[], float]):
self.ttl_s, self.max_entries, self.clock = ttl_s, max_entries, clock
self.items: OrderedDict[str, tuple[float, dict]] = OrderedDict() # key -> (expires at, value)
self.hits = self.misses = 0
def get(self, key: str) -> dict | None:
item = self.items.get(key)
if item is not None and self.clock() < item[0]:
self.items.move_to_end(key) # now the most recently used
self.hits += 1
return item[1]
if item is not None:
del self.items[key] # expired
self.misses += 1
return None
def put(self, key: str, value: dict) -> None:
self.items[key] = (self.clock() + self.ttl_s, value)
self.items.move_to_end(key)
while len(self.items) > self.max_entries:
self.items.popitem(last=False) # the least recently used
def stats(self) -> dict:
looked_up = self.hits + self.misses
return {"entries": len(self.items), "hits": self.hits, "misses": self.misses,
"hit_rate": round(self.hits / looked_up, 3) if looked_up else None} - Fields that do not change the answer.
useris a per-user id: leaving it in would make every user's requests miss.line 7 - Only answers that would come out the same anyway. A cache in front of temperature 1 would remove the randomness the caller asked for.line 12
- The team is part of the key: entries are never shared between teams.line 18
- Oldest first.
move_to_endon every hit keeps the most recently used at the end.line 28 - Remove from the front: the least recently used entry.line 46
import asyncio
import hmac
import math
import re
import time
import uuid
from contextlib import asynccontextmanager
from typing import Any, Callable
import httpx2
from fastapi import Depends, FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from budget import BudgetExceeded, Budgets
from cache import ResponseCache, cache_key, cacheable
from config import Target, Team, load_config, settings
from errors import GatewayError, error_body, error_response
from keys import ApiKey, KeyStore
from ratelimit import RateLimiter
from router import Router
from streaming import StreamStats, relay
from upstream import UpstreamError, Upstreams
from usage import UsageRecord, UsageStore, cost_usd, day_of, estimate_tokens, message_text
REQUEST_ID = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
class ChatRequest(BaseModel):
"""What the gateway checks. Every other field (temperature, max_tokens, tools...) is passed through."""
model_config = ConfigDict(extra="allow")
model: str = Field(min_length=1)
messages: list[dict[str, Any]] = Field(min_length=1)
stream: bool = False
def create_app(*, transport: httpx2.AsyncBaseTransport | None = None,
clock: Callable[[], float] = time.time) -> FastAPI:
"""Build the gateway. Tests pass a fake transport (the upstreams) and a fake clock (used from milestone 3)."""
s = settings()
cfg = load_config(s.config_file)
upstreams = Upstreams(cfg.upstreams, transport)
keys = KeyStore(s.db_path)
limiter = RateLimiter(clock)
usage = UsageStore(s.db_path)
budgets = Budgets(usage, clock)
router = Router(cfg, clock)
cache = ResponseCache(cfg.cache_ttl_s, cfg.cache_max_entries, clock)
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await upstreams.aclose() # close the pooled connections on shutdown
app = FastAPI(title="LLM gateway", lifespan=lifespan)
@app.exception_handler(GatewayError)
async def gateway_error(request: Request, err: GatewayError):
return error_response(err)
@app.exception_handler(RequestValidationError)
async def bad_request(request: Request, err: RequestValidationError):
first = err.errors()[0]
where = ".".join(str(p) for p in first["loc"] if p != "body")
return JSONResponse(error_body(f"{where}: {first['msg']}", "invalid_request_error"), status_code=400)
def caller(authorization: str | None = Header(default=None)) -> ApiKey:
"""The API key in "Authorization: Bearer gw-...". FastAPI runs this before every endpoint that asks for it."""
if not authorization or not authorization.startswith("Bearer "):
raise GatewayError(401, "missing API key: send Authorization: Bearer <your gateway key>",
"authentication_error", "missing_api_key")
key = keys.lookup(authorization.removeprefix("Bearer ").strip())
if key is None:
raise GatewayError(401, "invalid or revoked API key", "authentication_error", "invalid_api_key")
if key.team not in cfg.teams:
raise GatewayError(403, f"team '{key.team}' is not in gateway.toml", "permission_error", "unknown_team")
return key
def team_of(key: ApiKey) -> Team:
return cfg.teams[key.team]
def check_route(alias: str, team: Team) -> None:
if alias not in cfg.routes:
raise GatewayError(404, f"model '{alias}' does not exist; use one of: {', '.join(team.models)}",
code="model_not_found")
if alias not in team.models:
raise GatewayError(403, f"team '{team.name}' may not use '{alias}'; allowed: {', '.join(team.models)}",
"permission_error", "model_not_allowed")
def rate_limit(key: ApiKey) -> dict[str, str]:
wait, left = limiter.take(key)
if wait > 0:
raise GatewayError(429, f"rate limit of {key.rpm} requests per minute reached; retry in {wait:.1f} s",
"rate_limit_error", "rate_limit_exceeded",
headers={"Retry-After": str(math.ceil(wait)), "x-ratelimit-remaining-requests": "0"})
return {"x-ratelimit-remaining-requests": str(left)}
def admin(authorization: str | None = Header(default=None)) -> None:
if not s.admin_key:
raise GatewayError(403, "admin endpoints are off: set ADMIN_KEY", "permission_error", "admin_disabled")
given = (authorization or "").removeprefix("Bearer ").strip()
if not hmac.compare_digest(given.encode(), s.admin_key.encode()): # constant time: no timing hints
raise GatewayError(401, "wrong admin key", "authentication_error", "invalid_admin_key")
@app.get("/admin/usage", dependencies=[Depends(admin)])
async def usage_report(day: str | None = None):
"""Usage and cost per team for one UTC day (default: today)."""
day = day or day_of(clock())
rows = usage.report(day)
teams = []
for name, team in cfg.teams.items():
row = rows.get(name, {"requests": 0, "ok": 0, "rejected": 0, "errors": 0, "cache_hits": 0,
"prompt_tokens": 0, "completion_tokens": 0, "cost_usd": 0.0, "avg_latency_ms": None})
used = row["prompt_tokens"] + row["completion_tokens"]
teams.append({"team": name, **{k: v for k, v in row.items() if k != "team"},
"daily_token_budget": team.daily_token_budget,
"budget_used_pct": round(100 * used / team.daily_token_budget, 1) if team.daily_token_budget else None})
return {"day": day, "teams": teams}
@app.get("/admin/cache", dependencies=[Depends(admin)])
async def cache_stats():
return cache.stats()
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/health/upstreams")
async def health_upstreams():
"""Ask every upstream for its models (GET /models) and say which routed models are missing."""
async def check(name: str) -> dict:
wanted = sorted({t.model for ts in cfg.routes.values() for t in ts if t.upstream == name})
try:
served = await upstreams.models(name)
except Exception as e:
return {"ok": False, "error": type(e).__name__}
return {"ok": True, "models": served, "missing": [m for m in wanted if m not in served]}
results = await asyncio.gather(*(check(n) for n in cfg.upstreams))
report = dict(zip(cfg.upstreams, results))
breakers = router.states()
healthy = all(r["ok"] and not r["missing"] for r in report.values()) and "open" not in breakers.values()
return {"status": "ok" if healthy else "degraded", "upstreams": report, "breakers": breakers}
@app.get("/v1/models")
async def list_models(key: ApiKey = Depends(caller)):
return {"object": "list", "data": [{"id": alias, "object": "model", "created": 0, "owned_by": "llm-gateway"}
for alias in team_of(key).models]}
async def call(alias: str, body: dict, stream: bool) -> tuple[Target, httpx2.Response, int]:
"""Try the route's targets in order, skipping open breakers, until one answers.
Returns (the target that answered, its response, how many targets were tried)."""
problems, last, tried = [], None, 0
for target in cfg.routes[alias]:
breaker = router.breaker(target)
if not breaker.allow():
problems.append(f"{target}: circuit open")
continue
tried += 1
try:
resp = await (upstreams.open_stream(target, body) if stream else upstreams.chat(target, body))
except UpstreamError as e:
breaker.failure()
problems.append(str(e))
last = e
continue # fall back to the next target: nothing has been sent to the caller yet
breaker.success() # it answered; even a 400 proves the upstream is up
return target, resp, tried
if last is None: # every breaker was open: do not even try
wait = min(router.breaker(t).retry_after() for t in cfg.routes[alias])
raise GatewayError(503, f"no upstream available for '{alias}': {'; '.join(problems)}", "upstream_error",
"no_upstream_available", headers={"Retry-After": str(max(1, math.ceil(wait)))})
status = 504 if last.kind == "timeout" else 502
raise GatewayError(status, "; ".join(problems), "upstream_error", code=f"upstream_{last.kind}")
@app.post("/v1/chat/completions")
async def chat(req: ChatRequest, request: Request, key: ApiKey = Depends(caller)):
given_id = request.headers.get("x-request-id", "")
rec = UsageRecord(ts=clock(), request_id=given_id if REQUEST_ID.match(given_id) else uuid.uuid4().hex,
team=key.team, key_id=key.id, route=req.model)
started = time.perf_counter()
team = team_of(key)
reserved = 0
prompt_estimate = estimate_tokens(message_text(req.messages))
def finish(status: int, tokens: dict | None = None, answer_chars: int = 0) -> None:
"""Write the one usage row for this request and give back the budget reservation."""
rec.status = status
rec.latency_ms = round((time.perf_counter() - started) * 1000, 1)
if rec.upstream and (status == 200 or answer_chars): # a broken stream still generated tokens
if tokens:
rec.prompt_tokens, rec.completion_tokens = tokens["prompt_tokens"], tokens["completion_tokens"]
else: # no usage from the upstream (or the caller hung up first): estimate, and say so
rec.prompt_tokens, rec.completion_tokens = prompt_estimate, answer_chars // 4
rec.estimated = True
if not rec.cached: # a cache hit costs nothing (and does not count against the budget)
rec.cost_usd = cost_usd(cfg.prices, rec.upstream.split("/", 1)[1], rec.prompt_tokens, rec.completion_tokens)
usage.record(rec)
budgets.release(team, reserved)
try:
headers = {"x-request-id": rec.request_id, **rate_limit(key)}
check_route(req.model, team)
body = req.model_dump(exclude_unset=True)
key_for_cache = None
if cacheable(body) and "no-cache" not in request.headers.get("cache-control", ""):
key_for_cache = cache_key(team.name, body)
hit = cache.get(key_for_cache)
if hit is not None: # same question, same settings, same team, within the TTL: no upstream call
rec.cached, rec.upstream = True, hit["upstream"]
finish(200, hit["body"].get("usage"))
return JSONResponse(hit["body"], headers={**headers, "x-gateway-cache": "hit",
"x-gateway-upstream": hit["upstream"]})
headers["x-gateway-cache"] = "miss" if key_for_cache else "bypass"
max_out = body.get("max_completion_tokens") or body.get("max_tokens") or cfg.default_max_tokens
try:
reserved = budgets.reserve(team, prompt_estimate + max_out)
except BudgetExceeded as e:
raise GatewayError(429, f"{e}; the budget resets at midnight UTC", "rate_limit_error",
"daily_budget_exceeded", headers={"Retry-After": str(math.ceil(e.retry_after_s))})
caller_wants_usage = bool((body.get("stream_options") or {}).get("include_usage"))
if req.stream: # always ask for usage: the gateway needs the token counts
body["stream_options"] = {**(body.get("stream_options") or {}), "include_usage": True}
target, resp, tried = await call(req.model, body, req.stream)
rec.upstream = str(target)
headers |= {"x-gateway-upstream": str(target), "x-gateway-attempts": str(tried)}
except GatewayError as e:
finish(e.status)
raise
if resp.status_code != 200: # the upstream refused the request itself (a 4xx): pass it on unchanged
finish(resp.status_code)
return Response(resp.content, resp.status_code, headers=headers,
media_type=resp.headers.get("content-type", "application/json"))
if req.stream:
stats = StreamStats()
async def events():
try:
async for event in relay(resp, stats, caller_wants_usage):
yield event
finally: # runs when the stream ends, breaks, or the caller hangs up: bill what was generated
finish(502 if stats.error else 200, stats.usage, stats.chars)
return StreamingResponse(events(), media_type="text/event-stream",
headers={**headers, "Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
data = resp.json()
if key_for_cache:
cache.put(key_for_cache, {"body": data, "upstream": str(target)})
finish(200, data.get("usage"))
return JSONResponse(data, headers=headers)
return app - In this process's memory, like the rate limiter. Production uses Redis so every instance shares it.line 50
- The caller can always ask for a fresh answer.line 208
- No budget reserved, no upstream called: a hit is the cheapest request the gateway serves.line 211
- A hit costs nothing; its token counts are kept so you can see what was saved.line 198
- Only after a 200: errors and refusals are never cached.line 251
"""Milestone 6: an exact-match response cache with a TTL, per team, only for answers that are deterministic anyway."""
import sqlite3
from cache import cache_key
ADMIN = {"Authorization": "Bearer admin-test-key"}
def test_the_same_request_at_temperature_0_is_answered_from_the_cache(gateway):
gw = gateway()
first = gw.chat("fast", "What is TTL?", temperature=0)
second = gw.chat("fast", "What is TTL?", temperature=0)
assert (first.headers["x-gateway-cache"], second.headers["x-gateway-cache"]) == ("miss", "hit")
assert second.json() == first.json()
assert second.headers["x-gateway-upstream"] == "ollama/llama3.2:3b"
assert gw.ollama.calls == 1
def test_anything_that_changes_the_answer_changes_the_key(gateway):
gw = gateway()
gw.chat("fast", "Q1", temperature=0)
gw.chat("fast", "Q2", temperature=0) # other messages
gw.chat("fast", "Q1", temperature=0, max_tokens=5) # other parameters
gw.chat("smart", "Q1", temperature=0) # other route
assert gw.ollama.calls + gw.hosted.calls == 4
def test_teams_never_share_entries(gateway):
gw = gateway()
gw.chat("fast", "Q", temperature=0)
gw.client.headers["Authorization"] = f"Bearer {gw.new_key('support')}"
assert gw.chat("fast", "Q", temperature=0).headers["x-gateway-cache"] == "miss"
def test_only_deterministic_requests_are_cached(gateway):
gw = gateway()
for extra in ({}, {"temperature": 0.7}, {"temperature": 0, "n": 2}):
assert gw.chat("fast", "Q", **extra).headers["x-gateway-cache"] == "bypass"
gw.chat("fast", "Q", **extra)
gw.chat("fast", "Q", temperature=0, stream=True).read()
gw.chat("fast", "Q", temperature=0, stream=True).read()
assert gw.ollama.calls == 8
def test_cache_control_no_cache_skips_it(gateway):
gw = gateway()
gw.chat("fast", "Q", temperature=0)
r = gw.client.post("/v1/chat/completions", headers={"Cache-Control": "no-cache"},
json={"model": "fast", "messages": [{"role": "user", "content": "Q"}], "temperature": 0})
assert r.headers["x-gateway-cache"] == "bypass" and gw.ollama.calls == 2
def test_entries_expire_after_the_ttl(gateway):
gw = gateway() # test config: ttl_s = 60
gw.chat("fast", "Q", temperature=0)
gw.clock.advance(59)
assert gw.chat("fast", "Q", temperature=0).headers["x-gateway-cache"] == "hit"
gw.clock.advance(1)
assert gw.chat("fast", "Q", temperature=0).headers["x-gateway-cache"] == "miss"
def test_the_least_recently_used_entry_goes_first(gateway):
gw = gateway() # test config: max_entries = 3
for q in ("A", "B", "C"):
gw.chat("fast", q, temperature=0)
gw.chat("fast", "A", temperature=0) # A is now the most recently used
gw.chat("fast", "D", temperature=0) # pushes out B
assert gw.chat("fast", "A", temperature=0).headers["x-gateway-cache"] == "hit"
assert gw.chat("fast", "B", temperature=0).headers["x-gateway-cache"] == "miss"
def test_errors_are_not_cached(gateway):
gw = gateway()
gw.ollama.fail = 400
gw.chat("fast", "Q", temperature=0)
gw.ollama.fail = None
assert gw.chat("fast", "Q", temperature=0).headers["x-gateway-cache"] == "miss"
def test_hits_are_recorded_free_and_counted(gateway):
gw = gateway()
gw.chat("smart", "Q", temperature=0)
gw.chat("smart", "Q", temperature=0)
with sqlite3.connect(gw.db_path) as db:
assert db.execute("SELECT cached, cost_usd FROM usage ORDER BY id").fetchall() == [(0, 0.006), (1, 0.0)]
search = next(t for t in gw.client.get("/admin/usage", headers=ADMIN).json()["teams"] if t["team"] == "search")
assert (search["requests"], search["cache_hits"], search["prompt_tokens"]) == (2, 1, 1000)
assert gw.client.get("/admin/cache", headers=ADMIN).json() == {"entries": 1, "hits": 1, "misses": 1, "hit_rate": 0.5}
def test_cache_key_ignores_json_order_and_fields_that_do_not_change_the_answer():
a = {"model": "fast", "temperature": 0, "messages": [{"role": "user", "content": "Q"}]}
b = {"messages": [{"content": "Q", "role": "user"}], "temperature": 0, "model": "fast", "user": "u-1"}
assert cache_key("search", a) == cache_key("search", b)
assert cache_key("search", a) != cache_key("support", a) - Other messages, other parameters, another route: four upstream calls.line 19
- The same question from another team is a miss.line 28
- TTL 60 in the test config: still there at 59 seconds, gone at 60.line 56
- Reading A makes it recent, so adding D pushes out B instead.line 62
uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py tests/test_m5.py tests/test_m6.py
for i in 1 2; do curl -s -o /dev/null -D - localhost:8080/v1/chat/completions -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" -d '{"model": "fast", "temperature": 0, "messages": [{"role": "user", "content": "What is a TTL?"}]}' | grep -i "x-gateway-"; done
curl -s localhost:8080/admin/cache -H "Authorization: Bearer change-me-to-a-long-random-string"uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py tests/test_m5.py tests/test_m6.py
for i in 1 2; do curl -s -o /dev/null -D - localhost:8080/v1/chat/completions -H "Authorization: Bearer $GATEWAY_KEY" -H "Content-Type: application/json" -d '{"model": "fast", "temperature": 0, "messages": [{"role": "user", "content": "What is a TTL?"}]}' | grep -i "x-gateway-"; done
curl -s localhost:8080/admin/cache -H "Authorization: Bearer change-me-to-a-long-random-string"uv run pytest -q tests/test_m1.py tests/test_m2.py tests/test_m3.py tests/test_m4.py tests/test_m5.py tests/test_m6.py
1..2 | ForEach-Object { curl.exe -s -o NUL -D - localhost:8080/v1/chat/completions -H "Authorization: Bearer $env:GATEWAY_KEY" -H "Content-Type: application/json" -d '{\"model\": \"fast\", \"temperature\": 0, \"messages\": [{\"role\": \"user\", \"content\": \"What is a TTL?\"}]}' | Select-String "x-gateway-" }
curl.exe -s localhost:8080/admin/cache -H "Authorization: Bearer change-me-to-a-long-random-string" .............................................................. [100%]
62 passed in 2.94s
x-gateway-cache: miss
x-gateway-upstream: ollama/llama3.2:3b
x-gateway-attempts: 1
x-gateway-cache: hit
x-gateway-upstream: ollama/llama3.2:3b
{"entries":1,"hits":1,"misses":1,"hit_rate":0.5} Stuck on this milestone?
- The second request is a
misstoo - Check
temperatureis the number0(not missing, not"0"), and that the gateway did not restart between the two requests (--reloadrestarts it on every save, and the cache lives in memory). - Every request says
bypass cacheable()is false: a missingtemperature,nabove 1,stream: true, or aCache-Control: no-cacheheader (some HTTP tools send one).- A test sees
hitsthat it did not expect - Each test gets a new gateway with an empty cache. If you made the cache a module-level global, two tests share it: create it inside
create_app.
Logs with personal data masked, and OpenTelemetry spans
One JSON log line per request that never contains a key or raw personal data, and a trace per request with one span per upstream try, joined to the caller's trace and the upstream's.
redact.py: redact(text) -> str masks, in this order: API keys (sk-, gw-, pk- or rk- followed by 8 or more letters, digits, _ or -) as [KEY]; email addresses as [EMAIL]; and runs of digits (single spaces, dashes, dots or brackets allowed between them, an optional leading + or (): 13 to 19 digits that pass the Luhn checksum are [CARD], 9 to 15 digits are [PHONE], more than 15 that fail Luhn are [NUMBER], and shorter runs stay, so dates (2026-11-20), prices and order ids remain readable. Keys go first because they contain digits.
logs.py: JsonFormatter writes each record as one JSON object with ts (UTC, milliseconds), level, msg and the fields passed in extra={"fields": {...}}. setup_logging(log_file) -> logging.Logger configures the "gateway" logger with one file handler (remove old handlers first: the tests build many apps in one process), level INFO, and propagate = False.
tracing.py: setup_tracing(exporter) -> TracerProvider for TRACE_EXPORTER: none (spans are created but go nowhere), short (one line per span on the console, like lab 13) or console (the full JSON). Do not call trace.set_tracer_provider(): the app gets its tracer from the provider it is given, so each test can pass its own.
upstream.py: chat() and open_stream() take an optional headers dict, sent with the request.
app.py: create_app(..., tracer_provider=None) uses the given provider or setup_tracing(settings.trace_exporter), and shuts its own provider down on exit. Per chat request:
- a root span
POST /v1/chat/completions, kind SERVER, whose parent comes from the caller'straceparentheader (propagate.extract(request.headers)), withgateway.team,gateway.routeandgateway.request_id, and at the endhttp.response.status_code,gateway.cache,gateway.upstreamandgateway.cost_usd; status ERROR for 5xx; - one child span per upstream try,
chat <model>, kind CLIENT, withgen_ai.operation.name(chat),gen_ai.provider.name(the upstream),gen_ai.request.modelandgateway.stream. A failed try getserror.type(the status code like"503", ortimeout,connect) and status ERROR, and ends at once. The try that answered stays open until the request ends (after the stream, for a stream) and getsgen_ai.usage.input_tokensandgen_ai.usage.output_tokens; - each upstream request carries
x-request-idand atraceparentfor its span (propagate.inject), so an upstream that traces can join the same trace; - one log line, message
chat, withrequest_id,trace_id(32 hex characters, the root span's),team,key(the prefix only),route,upstream,attempts,stream,status,cache,latency_ms,prompt_tokens,completion_tokens,estimatedandcost_usd;error(redacted) when there was one; and only whenLOG_PROMPTS=true,prompt: the redacted text of the last message, cut to 200 characters.
Also settle up when the request is cancelled (shutdown, or the caller left): catch asyncio.CancelledError, write the row with status 499 (the code nginx uses for "client closed request"), and re-raise.
Run it. The settings are read when the app is built, so restart the gateway with them: in its terminal press Ctrl+C, then TRACE_EXPORTER=short LOG_PROMPTS=true uv run uvicorn --factory app:create_app --port 8080 --reload (Windows: $env:TRACE_EXPORTER="short"; $env:LOG_PROMPTS="true" first). Restart fake_hosted.py with --fail-rate 1, so smart has to fall back. After the command below, the gateway's terminal shows three spans with the same trace id (the times are from a real run):
chat hosted-large 6.1 ms ERROR trace=7d53b48d gen_ai.operation.name=chat gen_ai.provider.name=hosted gen_ai.request.model=hosted-large gateway.stream=False error.type=503
chat llama3.2:3b 1843.0 ms UNSET trace=7d53b48d gen_ai.operation.name=chat gen_ai.provider.name=ollama gen_ai.request.model=llama3.2:3b gateway.stream=False http.response.status_code=200 gen_ai.usage.input_tokens=45 gen_ai.usage.output_tokens=38
POST /v1/chat/completions 1858.2 ms UNSET trace=7d53b48d gateway.team=search gateway.route=smart gateway.request_id=04631849edf845a487949c64b69d280c http.response.status_code=200 gateway.cache=miss gateway.upstream=ollama/llama3.2:3b gateway.cost_usd=0.0
- The tests for milestones 1 to 7 pass (74 tests).
- Restart the gateway with
TRACE_EXPORTER=short LOG_PROMPTS=truein front of the uvicorn command: asmartrequest whilefake_hosted.py --fail-rate 1runs prints twochatspans (the first ERROR,error.type=503) and the root span, all with the sametrace=. tail -n 1 gateway.logshows the JSON line with the sametrace_id,"attempts": 2, and[EMAIL]instead of the address you typed.
Hints
- Start spans with
tracer.start_span(name, kind=..., context=..., attributes={...})and end them yourself withspan.end(): the request outlives anywithblock when it streams. For a child, passcontext=trace.set_span_in_context(root). propagate.inject(headers, context=trace.set_span_in_context(span))addstraceparentto a dict you then send;propagate.extract(request.headers)reads the caller's.- Write the log line in
finish(), so every outcome logs exactly once.format(span.get_span_context().trace_id, "032x")gives the trace id as 32 hex characters, the form Jaeger and every other tool shows. - The Luhn check: from the right, double every second digit, subtract 9 from results above 9, sum everything; a valid card number sums to a multiple of 10.
Show the reference solution for milestone 7
Try it yourself first. This is one good way to do it, not the only one.
import re
KEY = re.compile(r"\b(?:sk|gw|pk|rk)-[A-Za-z0-9_-]{8,}")
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
# A run of digits with single spaces, dashes, dots or brackets between them: phone numbers, card numbers.
NUMBER = re.compile(r"\+?\(?\d(?:[ ().-]{0,2}\d){6,22}")
def luhn_ok(digits: str) -> bool:
"""The checksum every payment card number passes, so a card is told apart from other long numbers."""
total = 0
for i, ch in enumerate(reversed(digits)):
d = int(ch)
if i % 2 == 1:
d = d * 2 - 9 if d > 4 else d * 2
total += d
return total % 10 == 0
def _number(m: re.Match) -> str:
digits = re.sub(r"\D", "", m.group())
if 13 <= len(digits) <= 19 and luhn_ok(digits):
return "[CARD]"
if 9 <= len(digits) <= 15:
return "[PHONE]"
if len(digits) > 15:
return "[NUMBER]"
return m.group() # short numbers (dates, prices, order ids) stay: logs need them
def redact(text: str) -> str:
"""Mask secrets and personal data before text goes into a log. Keys first: they contain digits."""
text = KEY.sub("[KEY]", text)
text = EMAIL.sub("[EMAIL]", text)
return NUMBER.sub(_number, text) - Keys first: a key like
sk-live-4111...must become[KEY], notsk-live-[CARD].line 3 - One pattern for every long number;
_numberdecides what it is from the digits.line 6 - Every payment card number passes this checksum, and most random numbers do not.line 9
- Phone numbers. A 16-digit order number would be masked as
[NUMBER]: masking too much is the safe mistake.line 24 - Logs are for debugging: dates, prices and order ids must stay readable.line 28
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
class JsonFormatter(logging.Formatter):
"""One JSON object per line: easy to search, and every log tool can read it."""
def format(self, record: logging.LogRecord) -> str:
entry = {"ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds"),
"level": record.levelname.lower(), "msg": record.getMessage(), **getattr(record, "fields", {})}
return json.dumps(entry)
def setup_logging(log_file: Path) -> logging.Logger:
log = logging.getLogger("gateway")
for handler in list(log.handlers): # building the app twice (tests do) must not log every line twice
log.removeHandler(handler)
handler.close()
handler = logging.FileHandler(log_file, encoding="utf-8")
handler.setFormatter(JsonFormatter())
log.addHandler(handler)
log.setLevel(logging.INFO)
log.propagate = False # not also to the root logger (uvicorn's console)
return log - One JSON object per line ("JSON lines"): every log tool can read and filter it,
grepandjqincluded.line 7 extra={"fields": {...}}putsfieldson the record; this copies them into the line.line 12- Loggers are global in Python. Each
create_appcall (every test) would add another handler and write every line twice.line 18 - Keep these lines out of the console, where uvicorn already prints its own access lines.line 25
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
def one_line(span: ReadableSpan) -> str:
"""A short console format: name, duration, status, the start of the trace id, attributes."""
ms = (span.end_time - span.start_time) / 1_000_000
trace_id = format(span.context.trace_id, "032x")[:8]
attrs = " ".join(f"{k}={v}" for k, v in span.attributes.items())
return f"{span.name:<27} {ms:7.1f} ms {span.status.status_code.name:<5} trace={trace_id} {attrs}\n"
def setup_tracing(exporter: str) -> TracerProvider:
"""TRACE_EXPORTER: none (spans are made but go nowhere), short (one line each) or console (full JSON)."""
provider = TracerProvider(resource=Resource.create({"service.name": "llm-gateway"}))
if exporter == "short":
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter(formatter=one_line)))
elif exporter == "console":
provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
elif exporter != "none":
raise ValueError(f"unknown TRACE_EXPORTER {exporter!r}: use none, short or console")
return provider - The same short console format as lab 13: name, duration, status, the start of the trace id, the attributes.line 6
- No
trace.set_tracer_provider(): Python allows the global provider to be set only once per process, and each test wants its own.line 23
import httpx2
from config import Target, Upstream
class UpstreamError(Exception):
"""A failure another upstream might not have: no connection, a timeout, 401/403 (our key), 429 or 5xx."""
def __init__(self, target: Target, kind: str, message: str, status: int | None = None):
super().__init__(f"{target}: {message}")
self.target, self.kind, self.status = target, kind, status
class Upstreams:
"""One pooled HTTP client per upstream. Every call to a model server goes through here."""
def __init__(self, upstreams: dict[str, Upstream], transport: httpx2.AsyncBaseTransport | None = None):
self.clients = {
name: httpx2.AsyncClient(
base_url=u.base_url,
headers={"Authorization": f"Bearer {u.api_key}"},
timeout=httpx2.Timeout(u.timeout_s, connect=5.0),
transport=transport,
)
for name, u in upstreams.items()
}
async def chat(self, target: Target, body: dict, headers: dict[str, str] | None = None) -> httpx2.Response:
"""POST /chat/completions with the upstream's own model name. Raises UpstreamError for failures that are
not the caller's fault; other answers (200, or a 4xx such as 400 for a bad request) are returned as they are."""
try:
resp = await self.clients[target.upstream].post("/chat/completions", json={**body, "model": target.model},
headers=headers)
except httpx2.TimeoutException as e: # before TransportError: it is a subclass
raise UpstreamError(target, "timeout", f"no answer in time ({type(e).__name__})") from e
except httpx2.TransportError as e:
raise UpstreamError(target, "connect", f"cannot reach the upstream ({type(e).__name__})") from e
if resp.status_code in (401, 403): # the gateway's own key for this upstream is wrong, not the caller's
raise UpstreamError(target, "auth", f"refused the gateway's key ({resp.status_code})", resp.status_code)
if resp.status_code == 429 or resp.status_code >= 500:
raise UpstreamError(target, "status", f"answered {resp.status_code}", resp.status_code)
return resp
async def open_stream(self, target: Target, body: dict, headers: dict[str, str] | None = None) -> httpx2.Response:
"""Start a streaming POST /chat/completions and return as soon as the status and headers arrive.
A 200 response is still open: the caller reads it line by line and must close it (aclose)."""
client = self.clients[target.upstream]
request = client.build_request("POST", "/chat/completions", json={**body, "model": target.model}, headers=headers)
try:
resp = await client.send(request, stream=True)
except httpx2.TimeoutException as e:
raise UpstreamError(target, "timeout", f"no answer in time ({type(e).__name__})") from e
except httpx2.TransportError as e:
raise UpstreamError(target, "connect", f"cannot reach the upstream ({type(e).__name__})") from e
if resp.status_code != 200:
await resp.aread() # an error body is small: read it, then close the connection
await resp.aclose()
if resp.status_code in (401, 403):
raise UpstreamError(target, "auth", f"refused the gateway's key ({resp.status_code})", resp.status_code)
if resp.status_code == 429 or resp.status_code >= 500:
raise UpstreamError(target, "status", f"answered {resp.status_code}", resp.status_code)
return resp
async def models(self, name: str) -> list[str]:
"""The model ids an upstream serves (its own GET /models)."""
resp = await self.clients[name].get("/models")
resp.raise_for_status()
return [m["id"] for m in resp.json()["data"]]
async def aclose(self) -> None:
for client in self.clients.values():
await client.aclose() - Extra headers for one request (
traceparent,x-request-id), on top of the client's ownAuthorization.line 28
import asyncio
import hmac
import math
import re
import time
import uuid
from contextlib import asynccontextmanager
from typing import Any, Callable
import httpx2
from fastapi import Depends, FastAPI, Header, Request, Response
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from opentelemetry import propagate, trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.trace import Span, SpanKind, StatusCode
from pydantic import BaseModel, ConfigDict, Field
from budget import BudgetExceeded, Budgets
from cache import ResponseCache, cache_key, cacheable
from config import Target, Team, load_config, settings
from errors import GatewayError, error_body, error_response
from keys import ApiKey, KeyStore
from logs import setup_logging
from ratelimit import RateLimiter
from redact import redact
from router import Router
from streaming import StreamStats, relay
from tracing import setup_tracing
from upstream import UpstreamError, Upstreams
from usage import UsageRecord, UsageStore, cost_usd, day_of, estimate_tokens, message_text
REQUEST_ID = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
class ChatRequest(BaseModel):
"""What the gateway checks. Every other field (temperature, max_tokens, tools...) is passed through."""
model_config = ConfigDict(extra="allow")
model: str = Field(min_length=1)
messages: list[dict[str, Any]] = Field(min_length=1)
stream: bool = False
def create_app(*, transport: httpx2.AsyncBaseTransport | None = None, clock: Callable[[], float] = time.time,
tracer_provider: TracerProvider | None = None) -> FastAPI:
"""Build the gateway. Tests pass a fake transport (the upstreams), a fake clock and their own tracer provider."""
s = settings()
cfg = load_config(s.config_file)
upstreams = Upstreams(cfg.upstreams, transport)
keys = KeyStore(s.db_path)
limiter = RateLimiter(clock)
usage = UsageStore(s.db_path)
budgets = Budgets(usage, clock)
router = Router(cfg, clock)
cache = ResponseCache(cfg.cache_ttl_s, cfg.cache_max_entries, clock)
log = setup_logging(s.log_file)
provider = tracer_provider or setup_tracing(s.trace_exporter)
tracer = provider.get_tracer("llm-gateway")
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
await upstreams.aclose() # close the pooled connections on shutdown
if tracer_provider is None:
provider.shutdown() # send any spans still waiting
app = FastAPI(title="LLM gateway", lifespan=lifespan)
@app.exception_handler(GatewayError)
async def gateway_error(request: Request, err: GatewayError):
return error_response(err)
@app.exception_handler(RequestValidationError)
async def bad_request(request: Request, err: RequestValidationError):
first = err.errors()[0]
where = ".".join(str(p) for p in first["loc"] if p != "body")
return JSONResponse(error_body(f"{where}: {first['msg']}", "invalid_request_error"), status_code=400)
def caller(authorization: str | None = Header(default=None)) -> ApiKey:
"""The API key in "Authorization: Bearer gw-...". FastAPI runs this before every endpoint that asks for it."""
if not authorization or not authorization.startswith("Bearer "):
raise GatewayError(401, "missing API key: send Authorization: Bearer <your gateway key>",
"authentication_error", "missing_api_key")
key = keys.lookup(authorization.removeprefix("Bearer ").strip())
if key is None:
raise GatewayError(401, "invalid or revoked API key", "authentication_error", "invalid_api_key")
if key.team not in cfg.teams:
raise GatewayError(403, f"team '{key.team}' is not in gateway.toml", "permission_error", "unknown_team")
return key
def team_of(key: ApiKey) -> Team:
return cfg.teams[key.team]
def check_route(alias: str, team: Team) -> None:
if alias not in cfg.routes:
raise GatewayError(404, f"model '{alias}' does not exist; use one of: {', '.join(team.models)}",
code="model_not_found")
if alias not in team.models:
raise GatewayError(403, f"team '{team.name}' may not use '{alias}'; allowed: {', '.join(team.models)}",
"permission_error", "model_not_allowed")
def rate_limit(key: ApiKey) -> dict[str, str]:
wait, left = limiter.take(key)
if wait > 0:
raise GatewayError(429, f"rate limit of {key.rpm} requests per minute reached; retry in {wait:.1f} s",
"rate_limit_error", "rate_limit_exceeded",
headers={"Retry-After": str(math.ceil(wait)), "x-ratelimit-remaining-requests": "0"})
return {"x-ratelimit-remaining-requests": str(left)}
def admin(authorization: str | None = Header(default=None)) -> None:
if not s.admin_key:
raise GatewayError(403, "admin endpoints are off: set ADMIN_KEY", "permission_error", "admin_disabled")
given = (authorization or "").removeprefix("Bearer ").strip()
if not hmac.compare_digest(given.encode(), s.admin_key.encode()): # constant time: no timing hints
raise GatewayError(401, "wrong admin key", "authentication_error", "invalid_admin_key")
@app.get("/admin/usage", dependencies=[Depends(admin)])
async def usage_report(day: str | None = None):
"""Usage and cost per team for one UTC day (default: today)."""
day = day or day_of(clock())
rows = usage.report(day)
teams = []
for name, team in cfg.teams.items():
row = rows.get(name, {"requests": 0, "ok": 0, "rejected": 0, "errors": 0, "cache_hits": 0,
"prompt_tokens": 0, "completion_tokens": 0, "cost_usd": 0.0, "avg_latency_ms": None})
used = row["prompt_tokens"] + row["completion_tokens"]
teams.append({"team": name, **{k: v for k, v in row.items() if k != "team"},
"daily_token_budget": team.daily_token_budget,
"budget_used_pct": round(100 * used / team.daily_token_budget, 1) if team.daily_token_budget else None})
return {"day": day, "teams": teams}
@app.get("/admin/cache", dependencies=[Depends(admin)])
async def cache_stats():
return cache.stats()
@app.get("/health")
async def health():
return {"status": "ok"}
@app.get("/health/upstreams")
async def health_upstreams():
"""Ask every upstream for its models (GET /models) and say which routed models are missing."""
async def check(name: str) -> dict:
wanted = sorted({t.model for ts in cfg.routes.values() for t in ts if t.upstream == name})
try:
served = await upstreams.models(name)
except Exception as e:
return {"ok": False, "error": type(e).__name__}
return {"ok": True, "models": served, "missing": [m for m in wanted if m not in served]}
results = await asyncio.gather(*(check(n) for n in cfg.upstreams))
report = dict(zip(cfg.upstreams, results))
breakers = router.states()
healthy = all(r["ok"] and not r["missing"] for r in report.values()) and "open" not in breakers.values()
return {"status": "ok" if healthy else "degraded", "upstreams": report, "breakers": breakers}
@app.get("/v1/models")
async def list_models(key: ApiKey = Depends(caller)):
return {"object": "list", "data": [{"id": alias, "object": "model", "created": 0, "owned_by": "llm-gateway"}
for alias in team_of(key).models]}
async def call(alias: str, body: dict, stream: bool, root: Span,
request_id: str) -> tuple[Target, httpx2.Response, int, Span]:
"""Try the route's targets in order, skipping open breakers, until one answers. Each try is a span.
Returns (the target that answered, its response, how many targets were tried, its span, still open)."""
problems, last, tried = [], None, 0
for target in cfg.routes[alias]:
breaker = router.breaker(target)
if not breaker.allow():
problems.append(f"{target}: circuit open")
continue
tried += 1
span = tracer.start_span(f"chat {target.model}", kind=SpanKind.CLIENT,
context=trace.set_span_in_context(root),
attributes={"gen_ai.operation.name": "chat", "gen_ai.provider.name": target.upstream,
"gen_ai.request.model": target.model, "gateway.stream": stream})
headers = {"x-request-id": request_id}
propagate.inject(headers, context=trace.set_span_in_context(span)) # adds traceparent
try:
resp = await (upstreams.open_stream(target, body, headers) if stream
else upstreams.chat(target, body, headers))
except UpstreamError as e:
breaker.failure()
span.set_attribute("error.type", str(e.status or e.kind))
span.set_status(StatusCode.ERROR, str(e))
span.end()
problems.append(str(e))
last = e
continue # fall back to the next target: nothing has been sent to the caller yet
breaker.success() # it answered; even a 400 proves the upstream is up
span.set_attribute("http.response.status_code", resp.status_code)
return target, resp, tried, span # finish() ends the span, after the stream if there is one
if last is None: # every breaker was open: do not even try
wait = min(router.breaker(t).retry_after() for t in cfg.routes[alias])
raise GatewayError(503, f"no upstream available for '{alias}': {'; '.join(problems)}", "upstream_error",
"no_upstream_available", headers={"Retry-After": str(max(1, math.ceil(wait)))})
status = 504 if last.kind == "timeout" else 502
raise GatewayError(status, "; ".join(problems), "upstream_error", code=f"upstream_{last.kind}")
@app.post("/v1/chat/completions")
async def chat(req: ChatRequest, request: Request, key: ApiKey = Depends(caller)):
given_id = request.headers.get("x-request-id", "")
rec = UsageRecord(ts=clock(), request_id=given_id if REQUEST_ID.match(given_id) else uuid.uuid4().hex,
team=key.team, key_id=key.id, route=req.model)
started = time.perf_counter()
team = team_of(key)
reserved = 0
prompt_estimate = estimate_tokens(message_text(req.messages))
root = tracer.start_span("POST /v1/chat/completions", kind=SpanKind.SERVER,
context=propagate.extract(request.headers), # continue the caller's trace
attributes={"gateway.team": key.team, "gateway.route": req.model,
"gateway.request_id": rec.request_id})
chat_span: Span | None = None # the try that answered; set below, read by finish()
cache_state, attempts = "bypass", 0
def finish(status: int, tokens: dict | None = None, answer_chars: int = 0, error: str | None = None) -> None:
"""Write the usage row and the log line, end the spans, and give back the budget reservation."""
rec.status = status
rec.latency_ms = round((time.perf_counter() - started) * 1000, 1)
if rec.upstream and (status == 200 or answer_chars): # a broken stream still generated tokens
if tokens:
rec.prompt_tokens, rec.completion_tokens = tokens["prompt_tokens"], tokens["completion_tokens"]
else: # no usage from the upstream (or the caller hung up first): estimate, and say so
rec.prompt_tokens, rec.completion_tokens = prompt_estimate, answer_chars // 4
rec.estimated = True
if not rec.cached: # a cache hit costs nothing (and does not count against the budget)
rec.cost_usd = cost_usd(cfg.prices, rec.upstream.split("/", 1)[1], rec.prompt_tokens, rec.completion_tokens)
usage.record(rec)
budgets.release(team, reserved)
if chat_span is not None:
chat_span.set_attributes({"gen_ai.usage.input_tokens": rec.prompt_tokens,
"gen_ai.usage.output_tokens": rec.completion_tokens})
if error:
chat_span.set_status(StatusCode.ERROR, error)
chat_span.end()
root.set_attributes({"http.response.status_code": status, "gateway.cache": cache_state,
"gateway.upstream": rec.upstream or "", "gateway.cost_usd": rec.cost_usd})
if status >= 500:
root.set_status(StatusCode.ERROR, error or "")
root.end()
fields = {"request_id": rec.request_id, "trace_id": format(root.get_span_context().trace_id, "032x"),
"team": key.team, "key": key.prefix, "route": req.model, "upstream": rec.upstream,
"attempts": attempts, "stream": req.stream, "status": status, "cache": cache_state,
"latency_ms": rec.latency_ms, "prompt_tokens": rec.prompt_tokens,
"completion_tokens": rec.completion_tokens, "estimated": rec.estimated, "cost_usd": rec.cost_usd}
if error:
fields["error"] = redact(error)
if s.log_prompts:
fields["prompt"] = redact(message_text(req.messages[-1:]))[:200]
log.info("chat", extra={"fields": fields})
try:
headers = {"x-request-id": rec.request_id, **rate_limit(key)}
check_route(req.model, team)
body = req.model_dump(exclude_unset=True)
key_for_cache = None
if cacheable(body) and "no-cache" not in request.headers.get("cache-control", ""):
key_for_cache = cache_key(team.name, body)
hit = cache.get(key_for_cache)
if hit is not None: # same question, same settings, same team, within the TTL: no upstream call
rec.cached, rec.upstream, cache_state = True, hit["upstream"], "hit"
finish(200, hit["body"].get("usage"))
return JSONResponse(hit["body"], headers={**headers, "x-gateway-cache": "hit",
"x-gateway-upstream": hit["upstream"]})
cache_state = headers["x-gateway-cache"] = "miss" if key_for_cache else "bypass"
max_out = body.get("max_completion_tokens") or body.get("max_tokens") or cfg.default_max_tokens
try:
reserved = budgets.reserve(team, prompt_estimate + max_out)
except BudgetExceeded as e:
raise GatewayError(429, f"{e}; the budget resets at midnight UTC", "rate_limit_error",
"daily_budget_exceeded", headers={"Retry-After": str(math.ceil(e.retry_after_s))})
caller_wants_usage = bool((body.get("stream_options") or {}).get("include_usage"))
if req.stream: # always ask for usage: the gateway needs the token counts
body["stream_options"] = {**(body.get("stream_options") or {}), "include_usage": True}
target, resp, attempts, chat_span = await call(req.model, body, req.stream, root, rec.request_id)
rec.upstream = str(target)
headers |= {"x-gateway-upstream": str(target), "x-gateway-attempts": str(attempts)}
except GatewayError as e:
finish(e.status, error=e.message)
raise
except asyncio.CancelledError: # the server is cancelling this request (shutdown, or the caller left)
finish(499, error="cancelled before the upstream answered")
raise
if resp.status_code != 200: # the upstream refused the request itself (a 4xx): pass it on unchanged
finish(resp.status_code)
return Response(resp.content, resp.status_code, headers=headers,
media_type=resp.headers.get("content-type", "application/json"))
if req.stream:
stats = StreamStats()
async def events():
try:
async for event in relay(resp, stats, caller_wants_usage):
yield event
finally: # runs when the stream ends, breaks, or the caller hangs up: bill what was generated
finish(502 if stats.error else 200, stats.usage, stats.chars, stats.error)
return StreamingResponse(events(), media_type="text/event-stream",
headers={**headers, "Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
data = resp.json()
if key_for_cache:
cache.put(key_for_cache, {"body": data, "upstream": str(target)})
finish(200, data.get("usage"))
return JSONResponse(data, headers=headers)
return app propagatereads and writes the W3Ctraceparentheader;tracelinks spans to their parents.line 14- Tests pass a provider with an in-memory exporter; the real app builds one from
TRACE_EXPORTER.line 58 - One span per **try**, so a fallback shows as a failed span and a good one under the same request.line 174
- The upstream receives a
traceparentnaming this span as the parent.line 179 error.typeis the OpenTelemetry convention for what kind of failure it was.line 185- The answering span is still open: for a stream, the model is still writing.line 193
- If the app sent a
traceparent, the gateway's spans join the app's trace instead of starting a new one.line 211 - Never the key itself. The prefix is enough to find which key it was in
admin.py list-keys.line 243 - Off by default: prompts are customer data. When on, only the last message, redacted and cut to 200 characters.line 249
CancelledErroris not anExceptionsubclass, soexcept Exceptionwould miss it. Settle up, then always re-raise.line 282
"""Milestone 7: one JSON log line per request with personal data masked, and OpenTelemetry spans for every try."""
import json
import pytest
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind, StatusCode
from redact import redact
@pytest.fixture
def traced(gateway):
"""A gateway whose spans land in a list the test can read."""
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
gw = gateway(tracer_provider=provider)
return gw, exporter
def log_lines(gw) -> list[dict]:
return [json.loads(line) for line in gw.log_file.read_text().splitlines()]
@pytest.mark.parametrize("text, masked", [
("mail me at sam.lee@example.com please", "mail me at [EMAIL] please"),
("card 4111 1111 1111 1111, exp 12/29", "card [CARD], exp 12/29"),
("call +1 (555) 123-4567 today", "call [PHONE] today"),
("my key is sk-live-abc123DEF456ghi", "my key is [KEY]"),
("order A1001 on 2026-11-20 cost 79.00", "order A1001 on 2026-11-20 cost 79.00"),
])
def test_redact(text, masked):
assert redact(text) == masked
def test_one_json_line_per_request_without_the_key_or_the_prompt(gateway):
gw = gateway()
gw.chat("fast", "My email is sam.lee@example.com")
gw.chat("nope")
lines = log_lines(gw)
assert [(x["route"], x["status"]) for x in lines] == [("fast", 200), ("nope", 404)]
first = lines[0]
assert first["upstream"] == "ollama/llama3.2:3b" and first["prompt_tokens"] == 20 and first["key"] == gw.key[:7]
assert "prompt" not in first # prompts are not logged unless LOG_PROMPTS=true
text = gw.log_file.read_text()
assert gw.key not in text and "sam.lee" not in text
assert "does not exist" in lines[1]["error"]
def test_log_prompts_logs_a_redacted_preview(gateway, monkeypatch):
monkeypatch.setenv("LOG_PROMPTS", "true")
gw = gateway()
gw.chat("fast", "My email is sam.lee@example.com, card 4111-1111-1111-1111")
assert log_lines(gw)[0]["prompt"] == "My email is [EMAIL], card [CARD]"
def test_a_root_span_and_a_chat_span_with_genai_attributes(traced):
gw, exporter = traced
gw.chat("fast")
spans = {s.name: s for s in exporter.get_finished_spans()}
root, chat = spans["POST /v1/chat/completions"], spans["chat llama3.2:3b"]
assert root.kind == SpanKind.SERVER and chat.kind == SpanKind.CLIENT
assert chat.parent.span_id == root.context.span_id
assert chat.attributes["gen_ai.provider.name"] == "ollama"
assert (chat.attributes["gen_ai.usage.input_tokens"], chat.attributes["gen_ai.usage.output_tokens"]) == (20, 5)
assert root.attributes["gateway.team"] == "search" and root.attributes["gateway.upstream"] == "ollama/llama3.2:3b"
assert log_lines(gw)[0]["trace_id"] == format(root.context.trace_id, "032x") # logs and traces join up
def test_a_fallback_shows_as_two_chat_spans(traced):
gw, exporter = traced
gw.ollama.fail = 503
gw.chat("fast")
chats = [s for s in exporter.get_finished_spans() if s.name.startswith("chat ")]
assert [s.name for s in chats] == ["chat llama3.2:3b", "chat hosted-small"]
assert chats[0].status.status_code == StatusCode.ERROR and chats[0].attributes["error.type"] == "503"
assert chats[1].status.status_code == StatusCode.UNSET
def test_the_trace_continues_upstream_and_from_the_caller(traced):
gw, exporter = traced
caller_trace = "4bf92f3577b34da6a3ce929d0e0e4736"
gw.client.post("/v1/chat/completions", headers={"traceparent": f"00-{caller_trace}-00f067aa0ba902b7-01"},
json={"model": "fast", "messages": [{"role": "user", "content": "Hi"}]})
root = next(s for s in exporter.get_finished_spans() if s.kind == SpanKind.SERVER)
assert format(root.context.trace_id, "032x") == caller_trace
sent = gw.ollama.headers[0]
assert caller_trace in sent["traceparent"] and sent["x-request-id"] == log_lines(gw)[0]["request_id"]
def test_a_stream_span_ends_when_the_stream_ends(traced):
gw, exporter = traced
gw.chat("smart", stream=True).read()
chat = next(s for s in exporter.get_finished_spans() if s.name == "chat hosted-large")
assert chat.attributes["gen_ai.usage.output_tokens"] == 200 and chat.attributes["gateway.stream"] is True
def test_a_cache_hit_has_no_chat_span(traced):
gw, exporter = traced
gw.chat("fast", "Q", temperature=0)
gw.chat("fast", "Q", temperature=0)
roots = [s for s in exporter.get_finished_spans() if s.kind == SpanKind.SERVER]
assert [r.attributes["gateway.cache"] for r in roots] == ["miss", "hit"]
assert len([s for s in exporter.get_finished_spans() if s.kind == SpanKind.CLIENT]) == 1 - A gateway whose spans go to an
InMemorySpanExporter, a list the test can read.line 14 - The other half of redaction: what must **not** be masked.line 32
- Reads the whole log file: neither the key nor the email may be anywhere in it.line 48
- Logs and traces share the trace id, so you can jump from a log line to its trace.line 69
- A
traceparentas an app would send it: version, trace id, parent span id, flags.line 84
uv run pytest -q
uv run try_gateway.py --model smart "My email is sam.lee@example.com, what is an SLA?"
tail -n 1 gateway.loguv run pytest -q
uv run try_gateway.py --model smart "My email is sam.lee@example.com, what is an SLA?"
tail -n 1 gateway.loguv run pytest -q
uv run try_gateway.py --model smart "My email is sam.lee@example.com, what is an SLA?"
Get-Content gateway.log -Tail 1 ..........................................................................
74 passed in 3.43s
models: ['fast', 'smart']
[ollama/llama3.2:3b] An SLA (service level agreement) is a commitment between a provider and a customer that defines the expected level of service, such as uptime.
usage: 45 in, 38 out
{"ts": "2026-11-29T08:51:19.602+00:00", "level": "info", "msg": "chat", "request_id": "04631849edf845a487949c64b69d280c", "trace_id": "7d53b48d4f9f53eb614ade95d033a977", "team": "search", "key": "gw-xY3f", "route": "smart", "upstream": "ollama/llama3.2:3b", "attempts": 2, "stream": false, "status": 200, "cache": "miss", "latency_ms": 1851.4, "prompt_tokens": 45, "completion_tokens": 38, "estimated": false, "cost_usd": 0.0, "prompt": "My email is [EMAIL], what is an SLA?"} Stuck on this milestone?
- No span lines appear in the gateway's terminal
- Environment variables are read when the app is built, so restart uvicorn with
TRACE_EXPORTER=shortin front of the command (--reloaddoes not pick up a changed variable)..envworks too: setTRACE_EXPORTER=shortthere and restart. - Every log line appears twice
setup_loggingadded a second handler to the same global logger. Remove the existing handlers before adding yours.ValueError: unknown TRACE_EXPORTER- Only
none,shortandconsoleare known. A typo stops the gateway at startup on purpose. - Overriding the tracer provider is not allowed
- That warning means something called
trace.set_tracer_provider()twice. The gateway must not call it at all: it uses the provider it was given.
A load test with p50, p95 and cache hit rate, and a Docker image
Measure the gateway under concurrent load (latency percentiles, time to first token, status codes, cache hit rate) and package it as a small, non-root Docker image.
stats.py: percentile(values, p) (nearest rank: the smallest value with at least p% of the values at or below it; ValueError for an empty list) and summarize(results, wall_s) -> dict. Each result is {"status", "latency_ms", "ttft_ms" (streams only, else None), "cache", "upstream"}. The summary has requests, ok (status 200), statuses (count per status, sorted), per_second, cache_hit_rate (hits among the ok results, 3 places), upstreams (count per upstream of the ok results that were not cache hits: who really answered), and, when there are ok results, p50_ms, p95_ms and max_ms of their latencies, plus ttft_p50_ms and ttft_p95_ms when there are times to first token. Latencies of errors are left out: a fast 429 would make the gateway look quick.
load.py: async def run_load(client, requests, concurrency, model="fast", distinct=5, stream=False) -> list[dict] sends requests chat requests with at most concurrency in flight (an asyncio.Semaphore). Request i asks PROMPTS[i % distinct] at temperature 0 with max_tokens 100, so prompts repeat and can hit the cache. A streamed request records the time to the first data: line as ttft_ms. A request that gets no answer at all (httpx2.TransportError) is status 0. main() reads --requests, --concurrency, --model, --distinct and --stream, uses GATEWAY_URL and GATEWAY_KEY, and prints the summary, one key value line each. The test drives run_load against the app in memory with httpx2.ASGITransport, so the real code is tested without a server.
Create a key with a high limit for the load test (the default 60 requests per minute would turn most of it into 429s, which is a fine thing to see once). Look at three numbers: with fast and 5 distinct prompts the hit rate is 0.9 (only the first five go upstream); with --stream the time to first token is far below the full latency; and the gateway's own overhead is the difference between its latency and the upstream's.
Dockerfile: the two-stage image from lab 14. Stage 1 copies uv in and runs uv sync --locked --no-install-project --no-dev with uv.lock and pyproject.toml mounted, then copies the code; stage 2 starts from the same slim Python image, creates a non-root app user and a /data folder it owns, copies /app, sets GATEWAY_DB=/data/gateway.db and LOG_FILE=/data/gateway.log (mount a volume on /data and keys and usage survive a new container), USER app, exposes 8080, has a HEALTHCHECK on /health, and runs uvicorn --factory app:create_app --host 0.0.0.0 --port 8080. One worker: the rate limits, breakers and cache live in the process's memory, and four workers would mean four of each. .dockerignore keeps out .venv/, .env (secrets go in with -e at run time, never into an image), *.db, *.log and tests/.
uv run pytest -qpasses: all 80 tests.uv run load.py --requests 50 --concurrency 5with a high-limit key printsok 50,cache_hit_rate 0.9and p50 and p95 latencies.uv run load.py --requests 50 --concurrency 5 --stream --model smartprintsttft_p50_msandttft_p95_mswell belowp50_ms.- Optional, with Docker: the image builds, the container answers
/health, and a key created withdocker exec llm-gateway python admin.py create-key ...works againstlocalhost:8080.
Hints
asyncio.gather(*(limited(i) for i in range(n)))starts every request at once;async with gate:insidelimited(aSemaphore(concurrency)) makes all butconcurrencyof them wait their turn.time.perf_counter()is the clock for measuring durations: it never jumps when the system clock changes.httpx2.AsyncClient(transport=httpx2.ASGITransport(app=app), base_url="http://gw/v1")sends requests straight into a FastAPI app. The gateway creates its upstream clients increate_app, not in the lifespan, which is why this works without starting the app.- In a container,
localhostis the container itself. Point the upstreams at your computer withUPSTREAM_OLLAMA_URL=http://host.docker.internal:11434/v1(Docker Desktop on macOS and Windows), or use--network hoston Linux.
Show the reference solution for milestone 8
Try it yourself first. This is one good way to do it, not the only one.
import math
from collections import Counter
def percentile(values: list[float], p: float) -> float:
"""Nearest-rank percentile: the smallest value with at least p% of all values at or below it."""
if not values:
raise ValueError("no values")
ordered = sorted(values)
rank = math.ceil(p / 100 * len(ordered))
return ordered[max(rank, 1) - 1]
def summarize(results: list[dict], wall_s: float) -> dict:
"""results: one dict per request with status, latency_ms, ttft_ms (streams only), cache and upstream."""
ok = [r for r in results if r["status"] == 200]
latencies = [r["latency_ms"] for r in ok]
ttfts = [r["ttft_ms"] for r in ok if r.get("ttft_ms") is not None]
out = {
"requests": len(results),
"ok": len(ok),
"statuses": dict(sorted(Counter(r["status"] for r in results).items())),
"per_second": round(len(results) / wall_s, 1) if wall_s > 0 else None,
"cache_hit_rate": round(sum(r["cache"] == "hit" for r in ok) / len(ok), 3) if ok else None,
"upstreams": dict(Counter(r["upstream"] for r in ok if r["cache"] != "hit")),
}
if latencies:
out |= {"p50_ms": percentile(latencies, 50), "p95_ms": percentile(latencies, 95), "max_ms": max(latencies)}
if ttfts:
out |= {"ttft_p50_ms": percentile(ttfts, 50), "ttft_p95_ms": percentile(ttfts, 95)}
return out - Nearest rank, the simple definition: p95 of 100 values is the 95th smallest. Libraries interpolate between values; for latency reports either is fine if you are consistent.line 5
- Latency of successful requests only. Report the errors separately, in
statuses.line 16 - Who really answered: a sudden share of
hosted/...onfastmeans the local model is failing over.line 25
"""Load-test a running gateway: uv run load.py --requests 50 --concurrency 5"""
import argparse
import asyncio
import json
import os
import time
import httpx2
from stats import summarize
PROMPTS = [
"In one sentence, what is a load balancer?",
"In one sentence, what is a cache?",
"In one sentence, what is a circuit breaker?",
"In one sentence, what is rate limiting?",
"In one sentence, what is an API key?",
"In one sentence, what is a message queue?",
"In one sentence, what is a database index?",
"In one sentence, what is a CDN?",
]
async def one(client: httpx2.AsyncClient, i: int, model: str, distinct: int, stream: bool) -> dict:
"""One request. Prompts repeat every `distinct` requests, at temperature 0, so repeats can hit the cache."""
body = {"model": model, "messages": [{"role": "user", "content": PROMPTS[i % distinct]}],
"temperature": 0, "max_tokens": 100, "stream": stream}
start = time.perf_counter()
ttft = None
try:
if stream:
async with client.stream("POST", "/chat/completions", json=body) as r:
async for line in r.aiter_lines():
if ttft is None and line.startswith("data:"):
ttft = (time.perf_counter() - start) * 1000 # time to the first event
else:
r = await client.post("/chat/completions", json=body)
status, headers = r.status_code, r.headers
except httpx2.TransportError: # includes timeouts: the gateway did not answer at all
status, headers = 0, {}
return {"status": status, "latency_ms": round((time.perf_counter() - start) * 1000, 1),
"ttft_ms": None if ttft is None else round(ttft, 1),
"cache": headers.get("x-gateway-cache", ""), "upstream": headers.get("x-gateway-upstream", "")}
async def run_load(client: httpx2.AsyncClient, requests: int, concurrency: int, model: str = "fast",
distinct: int = 5, stream: bool = False) -> list[dict]:
"""Send `requests` requests, at most `concurrency` at a time."""
gate = asyncio.Semaphore(concurrency)
async def limited(i: int) -> dict:
async with gate:
return await one(client, i, model, distinct, stream)
return await asyncio.gather(*(limited(i) for i in range(requests)))
async def main() -> None:
parser = argparse.ArgumentParser(description="Load-test the gateway and report p50/p95 and the cache hit rate.")
parser.add_argument("--requests", type=int, default=50)
parser.add_argument("--concurrency", type=int, default=5)
parser.add_argument("--model", default="fast")
parser.add_argument("--distinct", type=int, default=5, help="how many different prompts (1 to 8)")
parser.add_argument("--stream", action="store_true", help="stream, and also measure time to first token")
args = parser.parse_args()
headers = {"Authorization": f"Bearer {os.environ.get('GATEWAY_KEY', '')}"}
async with httpx2.AsyncClient(base_url=os.environ.get("GATEWAY_URL", "http://localhost:8080/v1"),
headers=headers, timeout=120) as client:
start = time.perf_counter()
results = await run_load(client, args.requests, args.concurrency, args.model,
min(max(args.distinct, 1), len(PROMPTS)), args.stream)
wall = time.perf_counter() - start
for k, v in summarize(results, wall).items():
print(f"{k:<15} {json.dumps(v)}")
if __name__ == "__main__":
asyncio.run(main()) - Eight short questions.
--distinctpicks how many are used, so you control how often prompts repeat.line 12 - Cacheable on purpose, and short answers so the test is about the gateway, not the model.line 27
- Read the stream line by line to time the first event.line 32
- A timeout or a refused connection is a result too (status 0), not a crash of the load test.line 39
- At most
concurrencyrequests in flight, like a fixed pool of virtual users.line 49
# syntax=docker/dockerfile:1
# ---------- stage 1: build. Has uv; installs the dependencies into /app/.venv ----------
FROM python:3.12-slim-bookworm AS builder
COPY --from=ghcr.io/astral-sh/uv:0.11.32 /uv /uvx /bin/
ENV UV_COMPILE_BYTECODE=1 \
UV_LINK_MODE=copy \
UV_PYTHON_DOWNLOADS=0
WORKDIR /app
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
uv sync --locked --no-install-project --no-dev
COPY . /app
# ---------- stage 2: run. Only Python, the .venv and the code; no uv, no build cache ----------
FROM python:3.12-slim-bookworm
RUN groupadd --system --gid 999 app \
&& useradd --system --gid 999 --uid 999 --no-create-home app \
&& mkdir /data && chown app:app /data
COPY --from=builder --chown=app:app /app /app
# The database and the log go to /data: mount a volume there so keys and usage survive a new container.
ENV PATH="/app/.venv/bin:$PATH" \
PYTHONUNBUFFERED=1 \
GATEWAY_DB=/data/gateway.db \
LOG_FILE=/data/gateway.log
WORKDIR /app
USER app
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8080/health', timeout=2)"]
# One worker: rate limits, breakers and the cache live in this process's memory.
CMD ["uvicorn", "--factory", "app:create_app", "--host", "0.0.0.0", "--port", "8080", "--timeout-graceful-shutdown", "30"] - uv pinned to an exact version, copied out of its official image.line 5
--locked: exactly the versions inuv.lock, or fail.--no-dev: no pytest and no openai SDK in the image.line 15- The one folder the app may write to. A named volume mounted there keeps the same owner.line 24
- The same settings as
.env, but with paths in the volume.-eatdocker runoverrides them.line 31 - Not root: a bug in the app cannot take over the container.line 35
- Docker (and most orchestrators) restart a container whose health check keeps failing.line 38
- One process, one worker: the in-memory rate limits, breakers and cache stay correct.line 42
.venv/
__pycache__/
.pytest_cache/
.env
*.db
*.log
tests/ - Anything copied into an image can be read by anyone who has the image. Keys go in at run time.line 4
- Tests run before the build (in CI), not in the production image.line 7
"""Milestone 8: the load test's numbers, the load test against the gateway, and a Dockerfile that is safe to ship."""
import asyncio
from pathlib import Path
import httpx2
import pytest
from load import run_load
from stats import percentile, summarize
ROOT = Path(__file__).resolve().parent.parent
def test_percentile_nearest_rank():
values = [float(v) for v in range(1, 101)] # 1.0 .. 100.0
assert (percentile(values, 50), percentile(values, 95), percentile(values, 100)) == (50.0, 95.0, 100.0)
assert percentile([30.0, 10.0, 20.0], 50) == 20.0
with pytest.raises(ValueError):
percentile([], 50)
def test_summarize_counts_statuses_hits_and_only_ok_latencies():
results = [{"status": 200, "latency_ms": 100.0, "cache": "miss", "upstream": "ollama/llama3.2:3b"},
{"status": 200, "latency_ms": 2.0, "cache": "hit", "upstream": "ollama/llama3.2:3b"},
{"status": 200, "latency_ms": 300.0, "cache": "miss", "upstream": "hosted/hosted-small"},
{"status": 429, "latency_ms": 1.0, "cache": "", "upstream": ""}]
s = summarize(results, wall_s=2.0)
assert (s["requests"], s["ok"], s["statuses"], s["per_second"]) == (4, 3, {200: 3, 429: 1}, 2.0)
assert (s["p50_ms"], s["max_ms"], s["cache_hit_rate"]) == (100.0, 300.0, 0.333)
assert s["upstreams"] == {"ollama/llama3.2:3b": 1, "hosted/hosted-small": 1} # hits did not reach an upstream
def load(gw, **kwargs) -> list[dict]:
async def go():
# ASGITransport calls the app directly, no server or network: the same code as the real load test.
async with httpx2.AsyncClient(transport=httpx2.ASGITransport(app=gw.app), base_url="http://gw/v1",
headers={"Authorization": f"Bearer {gw.key}"}) as client:
return await run_load(client, **kwargs)
return asyncio.run(go())
def test_repeated_prompts_hit_the_cache(gateway):
gw = gateway() # test config: the cache holds 3 entries
s = summarize(load(gw, requests=30, concurrency=1, distinct=3), 1.0)
assert s["ok"] == 30 and s["cache_hit_rate"] == 0.9 # only the first 3 miss
assert gw.ollama.calls == 3
def test_a_cache_smaller_than_the_working_set_never_hits(gateway):
gw = gateway()
s = summarize(load(gw, requests=30, concurrency=1, distinct=5), 1.0)
assert s["cache_hit_rate"] == 0.0 # A B C D E A B...: each prompt was pushed out just before it came back
def test_concurrent_streams_all_succeed_with_a_time_to_first_token(gateway):
gw = gateway()
results = load(gw, requests=20, concurrency=5, stream=True)
assert all(r["status"] == 200 and r["ttft_ms"] is not None for r in results)
assert "ttft_p95_ms" in summarize(results, 1.0)
def test_the_dockerfile_is_safe_to_ship():
dockerfile = (ROOT / "Dockerfile").read_text()
assert "uv sync --locked" in dockerfile # exactly the versions in uv.lock
assert "--no-dev" in dockerfile # no pytest in the image
assert "\nUSER " in dockerfile # not root
assert "app:create_app" in dockerfile
ignored = (ROOT / ".dockerignore").read_text().split()
assert ".env" in ignored and ".venv/" in ignored and "*.db" in ignored # no secrets, no local data - The real load test code, sending its requests straight into the app in memory.line 36
- Five prompts in rotation through a 3-entry LRU: each one is pushed out just before it comes back. Size the cache from your traffic, not from a guess.line 49
- Checks the rules that matter on your own Dockerfile: locked versions, no dev packages, not root, no secrets.line 62
uv run pytest -q
uv run admin.py create-key --team search --name load-test --rpm 6000 --burst 100
export GATEWAY_KEY=gw-paste-the-load-test-key-here
uv run load.py --requests 50 --concurrency 5
uv run load.py --requests 50 --concurrency 5 --stream --model smart
uv lock
docker build -t llm-gateway:0.1.0 .
docker run -d --name llm-gateway -p 8080:8080 -v gateway-data:/data -e ADMIN_KEY=change-me-to-a-long-random-string -e HOSTED_API_KEY=fake-hosted-key -e UPSTREAM_OLLAMA_URL=http://host.docker.internal:11434/v1 -e UPSTREAM_HOSTED_URL=http://host.docker.internal:9001/v1 llm-gateway:0.1.0
docker exec llm-gateway python admin.py create-key --team search --name docker-appuv run pytest -q
uv run admin.py create-key --team search --name load-test --rpm 6000 --burst 100
export GATEWAY_KEY=gw-paste-the-load-test-key-here
uv run load.py --requests 50 --concurrency 5
uv run load.py --requests 50 --concurrency 5 --stream --model smart
uv lock
docker build -t llm-gateway:0.1.0 .
docker run -d --name llm-gateway --network host -v gateway-data:/data -e ADMIN_KEY=change-me-to-a-long-random-string -e HOSTED_API_KEY=fake-hosted-key llm-gateway:0.1.0
docker exec llm-gateway python admin.py create-key --team search --name docker-appuv run pytest -q
uv run admin.py create-key --team search --name load-test --rpm 6000 --burst 100
$env:GATEWAY_KEY="gw-paste-the-load-test-key-here"
uv run load.py --requests 50 --concurrency 5
uv run load.py --requests 50 --concurrency 5 --stream --model smart
uv lock
docker build -t llm-gateway:0.1.0 .
docker run -d --name llm-gateway -p 8080:8080 -v gateway-data:/data -e ADMIN_KEY=change-me-to-a-long-random-string -e HOSTED_API_KEY=fake-hosted-key -e UPSTREAM_OLLAMA_URL=http://host.docker.internal:11434/v1 -e UPSTREAM_HOSTED_URL=http://host.docker.internal:9001/v1 llm-gateway:0.1.0
docker exec llm-gateway python admin.py create-key --team search --name docker-app ........................................................................ [ 90%]
........ [100%]
80 passed in 4.11s
Created a key for team search (6000 requests/minute, burst 100).
It is shown only once. Store it like a password:
gw-TtTclM8vh83bDtCveQyGEZe55kbyWZaq
requests 50
ok 50
statuses {"200": 50}
per_second 3.1
cache_hit_rate 0.9
upstreams {"ollama/llama3.2:3b": 5}
p50_ms 15.3
p95_ms 3841.6
max_ms 4410.7
requests 50
ok 50
statuses {"200": 50}
per_second 11.9
cache_hit_rate 0.0
upstreams {"hosted/hosted-large": 50}
p50_ms 411.7
p95_ms 442.7
max_ms 466.3
ttft_p50_ms 11.3
ttft_p95_ms 40.2
Resolved 40 packages in 5ms
[+] Building 21.6s (17/17) FINISHED
=> [builder 4/5] RUN --mount=type=cache,target=/root/.cache/uv ...
=> [stage-1 3/4] COPY --from=builder --chown=app:app /app /app
=> naming to docker.io/library/llm-gateway:0.1.0
6f2c1e0b9a7d...
Created a key for team search (60 requests/minute, burst 10).
It is shown only once. Store it like a password:
gw-Qe8rT1yU5iO9pA3sD7fG2hJ6kL0zXcVb Stuck on this milestone?
- The load test shows mostly 429
- The key has the default 60 requests per minute and burst 10. Create one with
--rpm 6000 --burst 100for load tests, as above: that the limit works under load is a result in itself. cache_hit_rate 0.0without--stream- The cache holds fewer entries than you have distinct prompts (see the milestone 8 test), or the gateway restarted (the cache is in memory). With
max_entries = 1000and--distinct 5it is 0.9. failed to compute cache key: "/uv.lock": not found- There is no
uv.lockyet (for example, you downloaded the project). Runuv lockonce, and commit the file. - The container starts, but every chat is 502
upstream_connect - The upstream URLs point at
localhost, which inside a container is the container. Use thehost.docker.internalURLs on macOS and Windows,--network hoston Linux, and check Ollama runs.docker logs llm-gatewayshows uvicorn's output; the JSON log is in the volume:docker exec llm-gateway tail -n 3 /data/gateway.log. docker: Error response from daemon: Conflict. The container name "/llm-gateway" is already in use- An earlier run is still there:
docker rm -f llm-gateway, then run it again.
Check it works
Three checks. The tests pass with no model (80 of them). One real request goes through every layer: your key, the smart route, a fallback when the hosted upstream is down, a stream, a usage row and a log line. And the usage report adds it all up per team.
Start fake_hosted.py --fail-rate 1 and the gateway (both from the project folder), with GATEWAY_KEY set to a key of team search. Your model's words and the numbers in the report will differ. What must hold: the log line says "upstream": "ollama/llama3.2:3b" and "attempts": 2 (the hosted upstream failed and the gateway fell back before the first byte), it has the key's prefix but never the key, no prompt unless LOG_PROMPTS=true (and then masked), and the report counts the request under search.
uv run pytest -q
uv run try_gateway.py --model smart --stream "In one sentence, what does an LLM gateway do?"
tail -n 1 gateway.log
curl -s localhost:8080/admin/usage -H "Authorization: Bearer change-me-to-a-long-random-string" ........................................................................ [ 90%]
........ [100%]
80 passed in 4.11s
models: ['fast', 'smart']
An LLM gateway sits between applications and model providers, handling routing, keys, limits, caching and cost tracking in one place.
{"ts": "2026-11-29T09:12:40.118+00:00", "level": "info", "msg": "chat", "request_id": "9b1f0c2e7d4a4f7e8c3b5a6d1e2f3a4b", "trace_id": "c41e5a7f9b2d4e6f8a1c3e5b7d9f0a2c", "team": "search", "key": "gw-xY3f", "route": "smart", "upstream": "ollama/llama3.2:3b", "attempts": 2, "stream": true, "status": 200, "cache": "bypass", "latency_ms": 2210.6, "prompt_tokens": 39, "completion_tokens": 27, "estimated": false, "cost_usd": 0.0}
{"day":"2026-11-29","teams":[{"team":"search","requests":71,"ok":66,"rejected":3,"errors":2,"cache_hits":46,"prompt_tokens":1630,"completion_tokens":1240,"cost_usd":0.012935,"avg_latency_ms":212.7,"daily_token_budget":200000,"budget_used_pct":1.4},{"team":"support","requests":0,...}]} Review rubric
Review your project the way a senior engineer or an interviewer would. Aim for the right column on every row.
| Area | Works | Production-ready |
|---|---|---|
| API compatibility | The openai SDK works against the gateway for normal requests. | Streaming, tools and unknown fields pass through untouched; errors use the OpenAI shape and status codes, so SDK exception classes and automatic retries behave as they do against a provider; the usage chunk is only sent to callers that asked for it. |
| Keys and limits | Requests need a key, and there is a requests-per-minute limit. | Keys are random, shown once and stored hashed; revocation works at once; the bucket is per key with a burst and a rate; 429s carry Retry-After; refused requests never reach an upstream; you can explain why production keeps the buckets in Redis. |
| Tokens, cost and budgets | Token counts are saved per request. | Exactly one usage row per request with a valid key; streams billed from the usage chunk, also when they break or the caller leaves, estimates marked as such; budgets reserve the worst case and release after; a routed model without a price stops the gateway at startup. |
| Routing and resilience | A second upstream is tried when the first fails. | Only failures that are not the caller's fall back (timeouts, connection errors, 401/403 of the gateway's key, 429, 5xx); fallback only before the first byte; one breaker per target shared across routes; all-open answers 503 with Retry-After without calling anyone; the usage row and headers name the target that answered. |
| Caching | Repeated requests are served from a cache. | Only deterministic requests (temperature 0, one choice, no stream), keyed on everything that changes the answer and scoped per team; TTL and LRU bounds; errors never cached; hit rate measured under load; a clear, reasoned position on semantic caching. |
| Privacy and observability | Requests are logged. | One JSON line per request with the trace id, never a key or a raw prompt; prompts only by opt-in and redacted; a server span per request and a client span per upstream try with GenAI attributes, joined to the caller's and the upstream's traces via traceparent. |
| Testing and delivery | Some tests call the endpoints. | 80 tests with fake upstreams behind MockTransport and a fake clock, no sleeps and no model; the load test runs in CI against the app in memory; the image is locked, non-root, without dev packages or secrets, one worker, data in a volume. |
Stretch goals
- Share state between instances. Move the token buckets, budget reservations, cache and breaker states to Redis (
redis.asyncio), with the bucket refill and take in one Lua script so it is atomic. Then run two gateway processes behind a load balancer and show with the load test that the limit holds across both. - Idempotency keys. Accept an
Idempotency-Keyheader: store the request's state in SQLite or Redis for 24 hours; a duplicate of a running request waits for it (or gets 409), a duplicate of a finished one replays the stored answer instead of calling the model again. - A narrow quality fallback. When the caller asks for JSON (
response_format: {"type": "json_object"}) and the answer does not parse, retry once on the next target, and count how often that happens per target. That is the one kind of small-model failure a gateway can see without understanding the task. - Embeddings and a semantic cache, opt-in. Proxy
/v1/embeddingswith the same keys and usage rows, then add a semantic cache for routes that opt in. Before choosing a threshold, print the similarity of pairs that should and should not match (withnomic-embed-textboth kinds land between about 0.5 and 0.85), and measure false hits on a set of near-duplicate prompts like "refund order 1182" and "refund order 1183". - Prices that change. Give each price a
valid_fromdate and price each usage row with the price valid at its timestamp, so a price change does not rewrite last month's bill. Add a monthly report per team.
Troubleshooting
Warnings or outputs that differ from this page, and uv sync printed Using CPython 3.15
The project uses a newer Python than 3.12. Run uv python pin 3.12, then uv sync. Creating the project with uv init --python 3.12 avoids it.
Address already in use when starting the gateway
Another gateway (or something else) is on port 8080, often an old --reload server in another terminal. Stop it, or start this one with --port 8081 and set GATEWAY_URL=http://localhost:8081/v1 for the scripts.
Real streams from Ollama are billed as estimated
Your Ollama version does not send the usage chunk for stream_options.include_usage. Update Ollama; until then the gateway estimates from the text length, which is what the estimated column is for.
An app using the gateway now gets model not found
Apps must ask for a route name (fast, smart), not a vendor model. GET /v1/models with the app's key lists the routes its team may use.
sqlite3.OperationalError: database is locked under heavy load
Many writes at once to one SQLite file. Fine for this project; for more traffic set PRAGMA journal_mode=WAL, write usage rows in batches from a queue, or move usage to Postgres or a log pipeline.
Tests pass one by one but fail together
Something is global: a module-level cache, rate limiter or logger handler. Everything with state belongs inside create_app, so each test's gateway starts empty.
What changes in production
- Shared state in Redis: buckets, reservations, the cache and (optionally) breaker states, so several stateless gateway instances enforce one limit per key and one budget per team. Each instance keeps its config in memory.
- Usage events off the hot path: write each usage row to a queue (Kafka, or a local buffer) and aggregate in a warehouse for the monthly chargeback, instead of an
INSERTper request. Keep prices with validity dates. - Keys and config from a control plane: a small admin service creates keys, teams, routes and prices, and pushes them to the gateways; a key can also be limited to certain routes or apps, and is scanned for in code repositories (that is what the
gw-prefix is for). - Policy before data leaves: an allow-list of models per team, data residency (an EU team only reaches EU endpoints), PII blocking or masking on the request itself, not just in logs.
- Watch the gateway itself: its own added latency (p99), first-token time per upstream, 429 and fallback rates, breaker openings, cache hit rate and dollars per team, with alerts at 80% of a budget.
Interview angle
“Tell me about something you built that sits in front of LLM providers.”
An OpenAI-compatible LLM gateway in Python with FastAPI. Apps keep the normal SDK and only change the base URL and the key; they ask for aliases like fast and smart, and a TOML config maps each alias to an ordered list of upstream targets, here Ollama and a hosted API. Keys are per team, random, stored as SHA-256 hashes in SQLite; each key has a token-bucket rate limit, and each team a daily token budget that reserves the worst case (prompt plus max tokens) before the call and releases it after, so concurrent requests cannot overshoot. Every request with a valid key writes exactly one usage row with tokens, cost from a price table and latency, also for streams that break or callers that hang up, and /admin/usage reports it per team. Failures that are not the caller's (timeouts, connection errors, 429 and 5xx) fall back to the next target, but only before the first byte, and a circuit breaker per target skips one that keeps failing. Deterministic requests at temperature 0 hit an exact-match cache scoped per team; I chose not to do semantic caching by default because near-duplicate prompts like two order numbers embed almost identically. Logs are JSON with keys never written and PII masked, and every upstream try is an OpenTelemetry span joined to the caller's trace. 80 tests run with fake upstreams behind httpx MockTransport and a fake clock. In a load test with repeated prompts the hit rate was 90%: p50 dropped to about 15 milliseconds while p95 was the model's seconds, which is why I report percentiles and not an average. To scale it out I would move the buckets, budgets and cache to Redis and the usage rows to a queue.
Clean up
Everything the project writes is in its folder: gateway.db (keys and usage) and gateway.log. Delete them to start fresh (you will need new keys). Stop the background fake_hosted.py and the gateway, and remove the Docker container and volume if you made them.
rm -f gateway.db gateway.log
kill %1
docker rm -f llm-gateway
docker volume rm gateway-datarm -f gateway.db gateway.log
kill %1
docker rm -f llm-gateway
docker volume rm gateway-dataRemove-Item gateway.db, gateway.log -ErrorAction SilentlyContinue
docker rm -f llm-gateway
docker volume rm gateway-data Practice
No model needed: these run in your browser and check your answer.
A token bucket, request by request
Write allowed(times, capacity, rate). times are the arrival times of requests in seconds, in order. The bucket starts full with capacity tokens, refills rate tokens per second (never above capacity), and each allowed request takes one token. Return a list with True for each allowed request and False for each refused one (a refused request takes nothing). The starter never refills.
def allowed(times, capacity, rate):
tokens = capacity
out = []
for t in times:
if tokens >= 1:
tokens -= 1
out.append(True)
else:
out.append(False)
return out
print(allowed([0, 0, 0, 1, 1.5, 2], capacity=2, rate=1))
Hint
Keep `tokens` and the time of the last request. For each request, first add `(t - last) * rate`, cap it with `min(capacity, ...)`, set `last = t`, then decide.
A cache with a TTL and least-recently-used eviction
Write a class TTLCache(ttl, max_entries) with put(key, value, now) and get(key, now). get returns the value, or None when the key is missing or the entry is expired (an entry stored at time t expires at t + ttl). get of a live entry makes it the most recently used. When put would make more than max_entries entries, remove the least recently used one. The starter is a plain dict.
class TTLCache:
def __init__(self, ttl, max_entries):
self.items = {}
def put(self, key, value, now):
self.items[key] = value
def get(self, key, now):
return self.items.get(key)
c = TTLCache(ttl=10, max_entries=2)
c.put("a", 1, now=0)
print(c.get("a", now=5), c.get("a", now=10))
Hint
`from collections import OrderedDict`. Store `(expires_at, value)`. In `get`, call `move_to_end(key)` on a hit; in `put`, `move_to_end` too, and `popitem(last=False)` while there are too many.
The full project
The full reference solution, as it is after the last milestone. Build your own first, then compare.