Cookbook 20 · Operate
Metered LLM Gateway
Route every agent LLM call through one gateway, price the model per 1K tokens, and read exact cost next to usage -- with the gateway's own ledger agreeing.
OperateCore15–30 min
What you build. An OpenAI-compatible stand-in gateway (
assets/server/llm_gateway.py) that serves the MLflow AI Gateway discovery listing and /v1/chat/completions behind a bearer key, billing a flat 1000+1000 tokens per call so the arithmetic is checkable by eye. The stack boots with a deliberately wrong provider key; the first run fails with the gateway's own 401 (in the gateway's ledger), an admin rotates the key live through the audited Settings surface, and the next run adds exactly 2000 tokens and $3.00 to the model's usage row. A rate change re-prices only subsequent calls. The key's durable home -- the encrypted secrets store -- and a deterministic guardrail definition close the loop.
Surfaces: LLM Gateway Workflows Settings Administration Audit Log
What you learn
- Read Integrations > LLM Gateway > Endpoints: configured, reachable, Through gateway (CALIBER's own LLM base URL points at it), and the gateway's endpoint rows -- and watch the page degrade to Unreachable with the error while the gateway is down, instead of breaking
- Diagnose a credential failure by its evidence: a run that errors with the gateway's
401plus a refused line in the gateway's own ledger means the key reached the gateway and was wrong there -- then rotate it at runtime (PATCH /settings/llm, admin-only, audited, fingerprint-masked) - Price a model on the Pricing tab in USD per 1K tokens: duplicates 409, viewer creation 403, edits admin-only
- Read the Usage tab after a run: calls, tokens and exact cost per model, aggregated from trace spans -- and see that raising a rate never rewrites what past calls cost
- Store and rotate the key in Administration > Secrets (version bump,
secret://reference, no readback), and define a deterministicregexguardrail on the Guardrails tab, knowing exactly where it is and is not enforced
Implementation flow
flowchart LR GW["Stand-in gateway :8791"] --> DISC["Endpoints tab: reachable, routed through"] GW --> P["Paused: page degrades, never breaks"] WRONG["Run on the wrong key"] --> L401["Gateway 401 + ledger line ok:false"] L401 --> ROT["Admin rotates the key: PATCH /settings/llm"] PRICE["Pricing: lab-chat-mini $1/$2 per 1K"] --> RUN["Metered run"] ROT --> RUN RUN --> USE["Usage: +2000 tokens, +$3.00 exactly"] USE --> RAISE["Raise the rate to $10/1K"] RAISE --> NEXT["Next call bills $12.00; the past is unchanged"] SEC["Secrets: put / rotate / revoke, no readback"] --> AUD["Audit Log"] GRD["Guardrail defined (regex), honestly scoped"] --> AUD
Step-by-step UI only
Each step shows the exact navigation path, the fields to fill, the button to click, and a snapshot of the CALIBER screen you'll be on.
- Before you start: start the stand-in gateway (
assets/server/llm_gateway.py) and a stack as the README describes (--real-llm,CALIBER_GATEWAY_URIandCALIBER_LLM_BASE_URLpointing at it, the deliberately wrong boot key). Open LLM Gateway and read the Endpoints tab.You'll see: Reachable, Through gateway, and two endpoint rows:chat-labandembeddings-lab.Screen snapshotcaliber · Integrations › LLM GatewayRead / inspect this surface — no form to fill. Integrations › LLM GatewayPause the stand-in (curl -X POST http://127.0.0.1:8791/admin/pause) and refresh the page; then resume it and refresh again.You'll see: Unreachable with the discovery error while paused -- a degraded card, never a broken page -- then Reachable again.Screen snapshotcaliber · Integrations › LLM GatewayRead / inspect this surface — no form to fill.- Import
assets/workflow/metered-reply.workflow.yaml, publish it, and run it once while the provider key is still the wrong boot key.Click RunYou'll see: The run ends error with the gateway's own401in the message, and the gateway's ledger records one refused call.Screen snapshotcaliber · Agent resources › WorkflowsRun Admin › SettingsAs an admin, write the right provider key at runtime (PATCH /settings/llm {"openai_api_key": ...}; the Settings page's LLM section is the same surface). An operator gets 403.You'll see: The masked fingerprint (••••+ the key's last 4) confirms which key is live; the value itself is never readable back.Screen snapshotcaliber · Admin › SettingsRead / inspect this surface — no form to fill.Integrations › LLM Gateway › PricingClick Add rate and price the gateway's model: providerlab, modellab-chat-mini,$1/1K prompt,$2/1K completion.Click CreateYou'll see: The rate row appears. A duplicate (provider, model) is refused with 409, and editing a rate is admin-only.Screen snapshotcaliber · Integrations › LLM Gateway › PricingCreateAgent resources › WorkflowsRun the metered workflow again, now on the right key.Click RunYou'll see: The run completes with the gateway model's reply, and the gateway's ledger records one real call billing a flat 1000+1000 tokens.Screen snapshotcaliber · Agent resources › WorkflowsRunIntegrations › LLM Gateway › UsageOpen the Usage tab and findlab-chat-miniin the by-model table.You'll see: One more call, 2000 more tokens, and exactly $3.00 more cost: (1000/1000)×$1 + (1000/1000)×$2.Screen snapshotcaliber · Integrations › LLM Gateway › UsageRead / inspect this surface — no form to fill.Integrations › LLM Gateway › PricingRaise the prompt rate to$10/1K (admin), re-read Usage, then run the workflow once more.You'll see: Past cost is unchanged -- the meter is written at call time -- and the new call bills $12.00.Screen snapshotcaliber · Integrations › LLM Gateway › PricingRead / inspect this surface — no form to fill.Admin › Administration › SecretsStore the gateway key under a name (Store / rotate), then store it again with a new value.Click Store / rotateYou'll see: The listing shows the name, a bumped version and asecret://reference -- never a value. Asecret://source forCALIBER_LLM_API_KEY_ENVresolves from this store at boot.Screen snapshotcaliber · Admin › Administration › SecretsStore / rotateIntegrations › LLM Gateway › GuardrailsClick New guardrail, pick the deterministicregexkind, name it, set a pattern, create it -- then delete it.Click Create guardrailYou'll see: The definition is listed (stored in the MLflow tracking store). Enforcement happens in MLflow's own AI Gateway, not in the standalone gateway the Endpoints tab lists -- the lab is explicit about that boundary.Screen snapshotcaliber · Integrations › LLM Gateway › GuardrailsCreate guardrail
Assets (copy-paste)
The exact files this cookbook uses — copy each into the matching field. Source: docs-site/cookbooks/20-llm-gateway-cost-guardrails-lab/assets/.
#!/usr/bin/env python3
"""A stand-in LLM gateway for the Metered LLM Gateway lab. It is NOT a real model.
CALIBER's gateway surface is about CALIBER's *view* of an OpenAI-compatible gateway: discovery,
routing, usage, and cost. This server plays the gateway-plus-provider role the way the lab's other
stand-ins play a ticketing SaaS or an account service: it exposes the same two surfaces the real
MLflow AI Gateway exposes -- the discovery listing CALIBER's Endpoints tab reads, and the
OpenAI-compatible chat-completions route CALIBER's workflow executor posts to -- and it bills a
flat, fixed token count per call so every cost number downstream is checkable by eye.
python3 llm_gateway.py [PORT] # default 8791, listens on 127.0.0.1 only
Environment:
LAB20_GATEWAY_KEY the bearer key chat completions require (default "lab20-gateway-key").
CALIBER holds this key as the secret ``secret://lab20-gateway-key``.
LLM_GATEWAY_LEDGER path to a JSONL file this server appends one line to per call
Routes:
GET /health 200, no auth
GET /api/2.0/endpoints/ 200 -- the MLflow AI Gateway discovery shape CALIBER's /gateway
route fetches; 503 while paused
POST /v1/chat/completions 200 -- an OpenAI chat-completions response with a canned reply and
fixed usage (1000 prompt + 1000 completion tokens, every call);
401 without ``Authorization: Bearer <LAB20_GATEWAY_KEY>``;
503 while paused
POST /admin/pause 200 -- discovery and completions answer 503 until /admin/resume.
Lab-only: it stands in for a gateway outage.
POST /admin/resume 200
POST /admin/reset 200 -- unpause; a fresh start for a re-run on the same process
Usage is fixed at 1000/1000 so the arithmetic stays visible: at the lab's pricing row of $1 per 1K
prompt tokens and $2 per 1K completion tokens, every call costs exactly $3.00. The ledger line
``{"path", "model", "ok", "prompt_tokens", "completion_tokens"}`` is written before the response is
sent: a client must never observe "success" before the gateway's own record of it exists -- that
record is this lab's proof, the same pattern the MCP and OpenAPI labs use.
"""
from __future__ import annotations
import json
import os
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PROMPT_TOKENS = 1000
COMPLETION_TOKENS = 1000
REPLY = "Filed through the metered gateway."
ENDPOINTS = {
"endpoints": [
{
"name": "chat-lab",
"endpoint_type": "llm/v1/chat",
"model": {"name": "lab-chat-mini", "provider": "lab"},
"endpoint_url": "/v1/chat/completions",
"limit": None,
},
{
"name": "embeddings-lab",
"endpoint_type": "llm/v1/embeddings",
"model": {"name": "lab-embed-mini", "provider": "lab"},
"endpoint_url": "/v1/embeddings",
"limit": None,
},
]
}
KEY = os.environ.get("LAB20_GATEWAY_KEY", "lab20-gateway-key")
_paused = False
def _ledger(
path: str, model: str, ok: bool, prompt: int = 0, completion: int = 0
) -> None:
ledger = os.environ.get("LLM_GATEWAY_LEDGER")
if not ledger:
return
with open(ledger, "a", encoding="utf-8") as handle:
handle.write(
json.dumps(
{
"path": path,
"model": model,
"ok": ok,
"prompt_tokens": prompt,
"completion_tokens": completion,
}
)
+ "\n"
)
class Handler(BaseHTTPRequestHandler):
def _send(self, status: int, body: dict) -> None:
payload = json.dumps(body).encode()
self.send_response(status)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def _body(self) -> dict:
length = int(self.headers.get("Content-Length", "0"))
raw = self.rfile.read(length) if length else b""
return json.loads(raw) if raw else {}
def do_GET(self) -> None:
if self.path == "/health":
self._send(200, {"ok": True})
return
if self.path.rstrip("/") == "/api/2.0/endpoints":
if _paused:
self._send(503, {"error": "gateway paused"})
return
self._send(200, ENDPOINTS)
return
self._send(404, {"error": "not found"})
def do_POST(self) -> None:
global _paused
if self.path == "/admin/pause":
_paused = True
self._send(200, {"paused": True})
return
if self.path == "/admin/resume":
_paused = False
self._send(200, {"paused": False})
return
if self.path == "/admin/reset":
_paused = False
self._send(200, {"paused": False})
return
if self.path == "/v1/chat/completions":
body = self._body()
model = str(body.get("model", ""))
if _paused:
_ledger("/v1/chat/completions", model, False)
self._send(503, {"error": "gateway paused"})
return
if self.headers.get("Authorization") != f"Bearer {KEY}":
_ledger("/v1/chat/completions", model, False)
self._send(
401,
{
"error": {
"message": "missing or wrong gateway key",
"type": "auth_error",
}
},
)
return
# Logged before the response is sent: a caller must never observe "success"
# before the gateway's own record of the call exists.
_ledger(
"/v1/chat/completions", model, True, PROMPT_TOKENS, COMPLETION_TOKENS
)
self._send(
200,
{
"id": "chatcmpl-lab20",
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": REPLY},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": PROMPT_TOKENS,
"completion_tokens": COMPLETION_TOKENS,
"total_tokens": PROMPT_TOKENS + COMPLETION_TOKENS,
},
},
)
return
self._send(404, {"error": "not found"})
def log_message(self, format: str, *args: object) -> None:
pass
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8791
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
# One agent, one model, one metered call per run. The agent's `model` names the gateway
# endpoint's model id (`lab-chat-mini`), which is also the pricing row's `model_id` -- that
# is the whole join: span model -> pricing model_id -> cost.
schema_version: 1
workflow_id: metered-reply
name: metered-reply
description: Cookbook 20. A single agent whose every call goes through the metered gateway.
nodes:
start:
id: start
type: start
outputs:
user_message:
type: string
reply_agent:
id: reply_agent
type: agent
name: reply-agent
model: lab-chat-mini
instructions:
type: inline
text: >-
Answer the user's message in one short sentence. You are a stand-in agent in a cost
accounting lab; the content of your reply does not matter, the metering of it does.
inputs:
input:
type: string
outputs:
final_output:
type: string
final:
id: final
type: output
inputs:
response:
type: string
edges:
- id: e_start_agent
from: start
to: reply_agent
map:
user_message: input
- id: e_agent_final
from: reply_agent
to: final
map:
final_output: response
Evaluation & quality gates
| Quality gate | Target |
|---|---|
| Discovery | GET /gateway reports configured, reachable and routing_through_gateway true, with the stand-in's 2 endpoints; a paused gateway flips reachable to false with the error, HTTP 200 either way |
| Two ledgers agree | usage's call count for lab-chat-mini equals the gateway ledger's ok count; a refused call is in the ledger (ok false) and never in usage |
| Exact cost | one run adds exactly 2000 tokens and $3.00 at $1/$2 per 1K (the same arithmetic test_routes_llm_pricing.py pins); after the rate rises to $10, the next call bills $12.00 and past cost is unchanged |
| Role floors | pricing create needs the operator scope (viewer 403); pricing edits and key rotation are admin-only (operator 403); secrets are admin-only end to end |
| No credential readback | GET /settings/llm returns presence and a masked fingerprint; secret responses carry metadata and a secret:// reference, never a value |
| Audit | settings.update_llm, create/update_llm_pricing, put/revoke_secret and create/delete_gateway_guardrail each appear in the audit log |
Developer notes & gotchas
- Flags. The gateway surface needs no feature flag; only the gallery step needs
cookbooks. The stack itself must be started with--real-llmand routed through the stand-in:CALIBER_GATEWAY_URI=http://127.0.0.1:8791,CALIBER_LLM_BASE_URL=http://127.0.0.1:8791/v1, plus a generatedLAB20_SECRET_KEYfor the secrets stage andCALIBER_OPERATOR_USERS=admin,lab20-operator; the lab README's Prerequisites has every export, in order. - The base URL ends in /v1. The OpenAI client appends
/chat/completionsto it. A value ending in/gateway404s against the standalone MLflow gateway -- this lab fixed that example in.env.exampleand the gateway deployment README. - Boot with the wrong key on purpose.
OPENAI_API_KEY=lab20-boot-key-wrongboth stages the lab's credential-failure beat and keeps your real key out of a disposable stack (--real-llmwould otherwise read it from.env). - Cost is written at call time. The agent-turn span carries tokens, model and cost computed from the pricing table at that moment;
/gateway/usageonly aggregates spans. Editing a rate re-prices the future, never history -- an audit property and a bookkeeping caveat in one. - The trust boundary, honestly. Guardrail definitions live in the MLflow tracking store and are enforced by MLflow's own AI Gateway, not by the standalone gateway the Endpoints tab lists. Pricing matches on
model_idalone and an unknown model costs $0. The refinement/diagnosis LLM client does not route throughCALIBER_LLM_BASE_URL. - Run it. Start the stand-in first:
python3 docs-site/cookbooks/20-llm-gateway-cost-guardrails-lab/assets/server/llm_gateway.py 8791 &, thencd sdk/caliber-sdk && ../../caliber/.venv/bin/python examples/cookbooks/cookbook_20_llm_gateway_cost_guardrails.py(under a minute;--cleanuparchives what it created).