Lesson 3 of 5 · 2 min
The service
# run locally: uvicorn gateway:app --port 8100
import hashlib, json, os, time
import httpx
from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import PlainTextResponse
from prometheus_client import Counter, Histogram, generate_latest
from pydantic import BaseModel
PROVIDERS = [
{"name": "local", "url": "http://127.0.0.1:11434/v1", "key": "ollama", "model": "gpt-oss:20b", "price": 0.0},
{"name": "cloud", "url": os.getenv("CLOUD_URL", ""), "key": os.getenv("CLOUD_KEY", ""), "model": os.getenv("CLOUD_MODEL", ""), "price": float(os.getenv("CLOUD_PRICE", "0.5"))},
]
KEYS = {k: float(v) for k, v in (p.split(":") for p in os.getenv("CLIENT_KEYS", "demo-key:1.0").split(","))} # key:daily budget
CALLS = Counter("gateway_calls_total", "Calls", ["provider", "result"])
TIME = Histogram("gateway_seconds", "Provider latency", ["provider"])
spent, cache, fails = {}, {}, {}
app = FastAPI()
class Chat(BaseModel):
messages: list[dict]
max_tokens: int = 500
@app.post("/v1/chat")
async def chat(body: Chat, authorization: str = Header("")):
key = authorization.removeprefix("Bearer ")
if key not in KEYS:
raise HTTPException(401, "unknown key")
day = (key, time.strftime("%Y-%m-%d"))
if spent.get(day, 0) >= KEYS[key]:
raise HTTPException(429, "daily budget used up")
ident = hashlib.sha256((key + json.dumps(body.model_dump(), sort_keys=True)).encode()).hexdigest()
if ident in cache:
return cache[ident] | {"cached": True}
errors = []
async with httpx.AsyncClient(timeout=60) as client:
for p in PROVIDERS:
count, until = fails.get(p["name"], (0, 0))
if not p["url"] or (count >= 3 and time.time() < until):
continue
try:
with TIME.labels(p["name"]).time():
r = await client.post(p["url"] + "/chat/completions", headers={"Authorization": "Bearer " + p["key"]},
json={"model": p["model"], "messages": body.messages, "max_tokens": body.max_tokens})
r.raise_for_status()
data = r.json()
tokens = data.get("usage", {}).get("total_tokens", 0)
spent[day] = spent.get(day, 0) + tokens / 1e6 * p["price"]
fails[p["name"]] = (0, 0)
CALLS.labels(p["name"], "ok").inc()
out = {"provider": p["name"], "tokens": tokens, "answer": data["choices"][0]["message"]["content"]}
cache[ident] = out
return out | {"cached": False}
except (httpx.HTTPError, KeyError, ValueError) as e:
fails[p["name"]] = (count + 1, time.time() + 30)
CALLS.labels(p["name"], "error").inc()
errors.append(p["name"] + ": " + type(e).__name__)
raise HTTPException(502, {"failed": errors})
@app.get("/metrics", response_class=PlainTextResponse)
def metrics():
return generate_latest()The cache key includes the client, so one customer never receives another's answer.
