CALIBER
Quickstart

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 401 plus 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 deterministic regex guardrail 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.

  1. Integrations › LLM Gateway creates · the stand-in gateway llm_gateway.py ↓
    Before you start: start the stand-in gateway (assets/server/llm_gateway.py) and a stack as the README describes (--real-llm, CALIBER_GATEWAY_URI and CALIBER_LLM_BASE_URL pointing 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-lab and embeddings-lab.
    Screen snapshot
    caliber · Integrations › LLM Gateway
    LLM Gateway
    Read / inspect this surface — no form to fill.
  2. Integrations › LLM Gateway
    Pause 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 snapshot
    caliber · Integrations › LLM Gateway
    LLM Gateway
    Read / inspect this surface — no form to fill.
  3. Agent resources › Workflows creates · the metered workflow metered-reply.workflow.yaml ↓
    Import assets/workflow/metered-reply.workflow.yaml, publish it, and run it once while the provider key is still the wrong boot key.
    Click Run
    You'll see: The run ends error with the gateway's own 401 in the message, and the gateway's ledger records one refused call.
    Screen snapshot
    caliber · Agent resources › Workflows
    WorkflowsWorkflows
    Run
  4. Admin › Settings
    As 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 snapshot
    caliber · Admin › Settings
    SettingsSettings
    Read / inspect this surface — no form to fill.
  5. Integrations › LLM Gateway › Pricing
    Click Add rate and price the gateway's model: provider lab, model lab-chat-mini, $1/1K prompt, $2/1K completion.
    Click Create
    You'll see: The rate row appears. A duplicate (provider, model) is refused with 409, and editing a rate is admin-only.
    Screen snapshot
    caliber · Integrations › LLM Gateway › Pricing
    Pricing
    Create
  6. Agent resources › Workflows
    Run the metered workflow again, now on the right key.
    Click Run
    You'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 snapshot
    caliber · Agent resources › Workflows
    WorkflowsWorkflows
    Run
  7. Integrations › LLM Gateway › Usage
    Open the Usage tab and find lab-chat-mini in 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 snapshot
    caliber · Integrations › LLM Gateway › Usage
    Usage
    Read / inspect this surface — no form to fill.
  8. Integrations › LLM Gateway › Pricing
    Raise 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 snapshot
    caliber · Integrations › LLM Gateway › Pricing
    Pricing
    Read / inspect this surface — no form to fill.
  9. Admin › Administration › Secrets
    Store the gateway key under a name (Store / rotate), then store it again with a new value.
    Click Store / rotate
    You'll see: The listing shows the name, a bumped version and a secret:// reference -- never a value. A secret:// source for CALIBER_LLM_API_KEY_ENV resolves from this store at boot.
    Screen snapshot
    caliber · Admin › Administration › Secrets
    Secrets
    Store / rotate
  10. Integrations › LLM Gateway › Guardrails
    Click New guardrail, pick the deterministic regex kind, name it, set a pattern, create it -- then delete it.
    Click Create guardrail
    You'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 snapshot
    caliber · Integrations › LLM Gateway › Guardrails
    Guardrails
    Create 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/.

assets/server/llm_gateway.py
#!/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()
assets/workflow/metered-reply.workflow.yaml
# 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 gateTarget
DiscoveryGET /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 agreeusage'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 costone 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 floorspricing 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 readbackGET /settings/llm returns presence and a masked fingerprint; secret responses carry metadata and a secret:// reference, never a value
Auditsettings.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-llm and 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 generated LAB20_SECRET_KEY for the secrets stage and CALIBER_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/completions to it. A value ending in /gateway 404s against the standalone MLflow gateway -- this lab fixed that example in .env.example and the gateway deployment README.
  • Boot with the wrong key on purpose. OPENAI_API_KEY=lab20-boot-key-wrong both stages the lab's credential-failure beat and keeps your real key out of a disposable stack (--real-llm would 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/usage only 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_id alone and an unknown model costs $0. The refinement/diagnosis LLM client does not route through CALIBER_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 &, then cd sdk/caliber-sdk && ../../caliber/.venv/bin/python examples/cookbooks/cookbook_20_llm_gateway_cost_guardrails.py (under a minute; --cleanup archives what it created).

CALIBER : Contextual Adaptive Lifecycle for Intelligent Build, Evaluation, and Refinement — Cookbooks — every recipe is UI-implementable on the shipped platform. Source + assets under docs-site/cookbooks/<nn>-…/. Regenerate with python3 docs-site/cookbooks/training/build.py.