{"slug": "llm-observability-in-python-12-steps-80-min", "title": "LLM Observability in Python: 12 Steps, 80 Min", "summary": "A tutorial published on Shattered.io walks Python developers through building `llmscope`, a standard-library LLM observability tool that records tokens in and out, cached share, latency, status and dollar cost for every model call, then writes spans to SQLite for reports and alerts. The 12-step project takes about 80 minutes and runs without API keys via a simulated provider, with optional adapters for the OpenAI Responses API, Anthropic Messages API and Gemini API. The piece ties the need to three price changes between November 9 and December 1, 2026: Anthropic's Claude Fable 5.2 at $8 per million input and $40 per million output tokens (down from $10 and $50 for Fable 5.1), OpenAI's GPT-6.2 Astra at the same $8 and $40, and Google's Gemini 4 Carbon at an introductory $2 and $10 through November 30 before rising to $4 and $20.", "body_md": "Don't miss new tech stories on Google\n\nAdd Shattered once in the Google app and our stories show up in your news suggestions.\n\n[Add now](https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F)\n\n## LLM Observability: What to Record for Every Model Call\n\nThree price lists changed between November 9 and December 1, 2026. Anthropic released Claude Fable 5.2 on November 9, 2026 at $8 per million input tokens and $40 per million output tokens, down from $10 and $50 for Fable 5.1. OpenAI shipped [GPT-6.2 Astra](https://developers.openai.com/api/docs/guides/latest-model/gpt-6.2-astra.md) on November 17 at the same $8 and $40. Google’s Gemini 4 Carbon sells at an introductory $2 and $10 through November 30, then jumps to $4 and $20. A team that watches only its monthly invoice sees the damage weeks late.\n\nLLM observability closes that gap. It means recording the tokens in and out, the cached share, the latency, the status and the dollar cost for every model call, then rolling those records into numbers you can alert on. The practical payoff is spotting the call path that doubled its spend, the model whose 95th-percentile latency slipped, and the cache that quietly stopped hitting. Readers still choosing a model can start with [how GPT-6.2 Astra and Fable 5.2 compare on cost per task](https://shattered.io/gpt-6-2-astra-vs-claude-fable-5-2-62-vs-65-index-4-vs-26-54-task-cost/). Any ranking goes stale the day a vendor edits a price, though, and your own measurements do not.\n\nThe project below, `llmscope`, runs its core on the Python standard library. It wraps a provider call, prices the usage from a dated price book, writes a span into SQLite, and serves reports and alerts from that table. A built-in simulated provider lets every step run without API keys. Optional adapters talk to the OpenAI Responses API, the Anthropic Messages API and the Gemini API.\n\n| Signal | Why it matters | Where it comes from | \n|---|---|---|\n| Fresh input tokens | Billed at the full input rate | Provider usage block | \n| Cached input tokens | Billed at a steep discount, so a drop signals a broken cache | Provider usage block | \n| Output and thinking tokens | Usually the largest line on the bill | Provider usage block | \n| Duration and time to first token | Drives user experience and timeouts | Your own timer | \n| Status and error class | Separates rate limits from outages | Exception type or HTTP status | \n| Cost in micro-dollars | The number finance asks about | Token counts times a dated price | \n| Tags (feature, route, tenant) | Assigns spend to an owner | Your call sites | \n\n### Why Vendor Dashboards Are Not Enough\n\nEach vendor console reports its own usage, which works fine for a single provider. A product that sends traffic to three APIs needs one schema, one clock and one definition of cost. Console totals also cannot answer per-feature questions, because the vendor has never heard of your feature names. And no console warns you about next week’s price change on a different vendor’s model. The [price gap between ChatGPT, Claude and Gemini](https://shattered.io/claude-vs-chatgpt-vs-gemini-price-gap-2026/) is wide enough that routing decisions deserve real data from your own traffic.\n\n## Prerequisites: Versions, Keys and Time\n\nPlan for about 80 minutes. Steps 1 to 11 need no network access and no keys, because the demo uses the simulated provider. Only live calls and the optional OpenTelemetry export in Step 12 need extra setup.\n\n| Requirement | Version or tier | Notes | \n|---|---|---|\n| Python | 3.12 or newer | Tested on 3.12.3 | \n| SQLite | Bundled with Python | Tested on 3.45.1 | \n| OpenAI API access | A key that can call gpt-6.2-astra | OpenAI says the model works with both the Responses API and Chat Completions | \n| Anthropic API access | A key for Claude Fable 5.2 | Anthropic lists Fable 5.2 as available to all customers on the Claude API | \n| Google API access | A paid Gemini API key | Gemini 4 Carbon is not available on the Free tier | \n| opentelemetry-sdk | Latest release | Optional, Step 12 only. Tested in a throwaway virtual environment | \n\n### API Keys and Environment\n\nCreate one virtual environment and keep keys in environment variables, never in source files. The adapters read `OPENAI_API_KEY`, `ANTHROPIC_API_KEY` and `GEMINI_API_KEY`. Anthropic’s model ID for Fable 5.2 reportedly reads `claude-fable-5-2`, which is what the config uses, so confirm it in your console. If you still need a Google key, the [Gemini API tutorial for Carbon](https://shattered.io/gemini-api-tutorial-gemini-4-carbon-12-steps-2026/) covers creating one and picking a paid tier.\n\n```\nmkdir llmscope && cd llmscope\npython3 --version                  # expect 3.12 or newer\npython3 -m venv .venv && source .venv/bin/activate\nmkdir -p llmscope config scripts tests\ntouch tests/__init__.py\n\n# only needed for live calls, skip for the offline demo\nexport OPENAI_API_KEY=\"sk-your-key\"\nexport ANTHROPIC_API_KEY=\"your-key\"\nexport GEMINI_API_KEY=\"your-key\"\n```\n\nA handful of short test prompts costs a few cents at the rates above, so a live smoke test will not dent any budget. Still, create keys scoped to a single project, set a spend cap wherever the vendor offers one, and rotate the keys when the experiment ends. An observability tool that holds production keys deserves the same care as the application it watches.\n\n## Steps 1 and 2: Project Layout and a Dated Price Book\n\n**Step 1: lay out the project.** The layout keeps config, library code, scripts and tests apart, so a price edit never touches Python. Create the files as you reach them. When you finish Step 12, the tree should match this.\n\n```\nllmscope/\n  config/\n    alerts.json\n    prices.json\n  llmscope/\n    __init__.py\n    alerts.py\n    otel_export.py\n    pricing.py\n    providers.py\n    report.py\n    store.py\n    tracer.py\n  scripts/\n    demo.py\n  tests/\n    __init__.py\n    test_pricing.py\n```\n\n**Step 2: write the price book.** Every row carries an `effective_from` date, and the lookup picks the newest row that starts on or before the call date. That one design choice handles Carbon’s introductory pricing. The model keeps a single ID, but its price doubles on December 1, so it needs two rows. Google’s [Carbon availability post](https://blog.google/innovation-and-ai/models-and-research/gemini-models/gemini-4-carbon-now-available/) gives the introductory rate, and Google’s own pricing notes put the new rate at $4 per million input tokens and $20 per million output tokens after November 30.\n\nThe file also encodes the billing quirks that bite later. For GPT-6.2 Astra, OpenAI’s pricing page says batch runs cost 50% of standard rates and fast mode costs twice the standard rate. Requests above 272K input tokens double the input and cache rates and raise output to 1.5 times the short-context rate for the whole request. Anthropic lists a 50% Batch API discount for Fable 5.2, and its [Fable 5.2 documentation](https://platform.claude.com/docs/en/models/fable-5-2/whats-new-fable-5-2) prices fast mode at $16 and $80 per million tokens, which is exactly twice standard.\n\n`config/prices.json`\n\n```\n{\n  \"currency\": \"USD\",\n  \"per_tokens\": 1000000,\n  \"prices\": [\n    {\n      \"model\": \"gpt-6.2-astra\",\n      \"effective_from\": \"2026-11-17\",\n      \"input\": 8.00,\n      \"cached_input\": 0.40,\n      \"output\": 40.00,\n      \"tiers\": {\"standard\": 1, \"batch\": 0.5, \"fast\": 2},\n      \"long_context\": {\"over_input_tokens\": 272000, \"input_x\": 2, \"cached_x\": 2, \"output_x\": 1.5},\n      \"source\": \"OpenAI GPT-6.2 Astra model page, checked 2026-11-25\"\n    },\n    {\n      \"model\": \"claude-fable-5-2\",\n      \"effective_from\": \"2026-11-09\",\n      \"input\": 8.00,\n      \"cached_input\": 0.20,\n      \"output\": 40.00,\n      \"tiers\": {\"standard\": 1, \"batch\": 0.5, \"fast\": 2},\n      \"source\": \"Claude Platform Docs, Fable 5.2 overview, checked 2026-11-25\"\n    },\n    {\n      \"model\": \"gemini-4-carbon\",\n      \"effective_from\": \"2026-11-10\",\n      \"input\": 2.00,\n      \"cached_input\": 0.10,\n      \"output\": 10.00,\n      \"tiers\": {\"standard\": 1},\n      \"source\": \"Google introductory price, valid through 2026-11-30\"\n    },\n    {\n      \"model\": \"gemini-4-carbon\",\n      \"effective_from\": \"2026-12-01\",\n      \"input\": 4.00,\n      \"cached_input\": 0.20,\n      \"output\": 20.00,\n      \"tiers\": {\"standard\": 1},\n      \"source\": \"Google post-introduction price\",\n      \"note\": \"Cached rate assumes the 95% discount carries over. Confirm on Google's pricing page.\"\n    }\n  ]\n}\n```\n\n| Model | Input per 1M | Cached input per 1M | Output per 1M | Valid from | \n|---|---|---|---|---|\n| GPT-6.2 Astra | $8.00 | $0.40 | $40.00 | November 17, 2026 | \n| Claude Fable 5.2 | $8.00 | $0.20 (cache reads) | $40.00 | November 9, 2026 | \n| Gemini 4 Carbon (introductory) | $2.00 | 95% below input rate | $10.00 | November 10 to 30, 2026 | \n| Gemini 4 Carbon (after the introduction) | $4.00 | Assumed 95% below input rate | $20.00 | December 1, 2026 | \n\nThe Carbon cached rate after November 30 is an assumption in the file. Google’s text describes the 95% cache discount during the introductory period, so the config carries a `note` field flagging that row for a manual check. Notes like that cost nothing and save an audit later. Cache write prices are missing on purpose. OpenAI lists writes at $10 per million tokens for 30 minutes of retention, which is more than the $8 input rate, so a missing write price must fail loudly instead of defaulting to zero. Step 3 enforces that.\n\n## Steps 3 and 4: Normalize Usage and Price Every Call\n\n**Step 3: define one usage shape.** The three APIs report tokens differently, and mixing the conventions is the most common source of wrong LLM cost tracking. The table shows the shapes the adapters assume. They follow each vendor’s public API reference as of my last check. I could not re-verify Carbon’s exact usage field names against Google’s documentation today, so the code includes a guard that rejects impossible numbers.\n\n| Provider | Input field | Cached tokens | Output and thinking | \n|---|---|---|---|\n| OpenAI Responses API | `input_tokens` (includes cached) | `input_tokens_details.cached_tokens` | `output_tokens` (includes reasoning) | \n| Anthropic Messages API | `input_tokens` (excludes cache reads and writes) | `cache_read_input_tokens` and`cache_creation_input_tokens` | `output_tokens` | \n| Gemini API | `promptTokenCount` (includes cached) | `cachedContentTokenCount` | `candidatesTokenCount` plus`thoughtsTokenCount` | \n\nThe `Usage` dataclass below stores fresh input, cached input, output and cache-write tokens as separate fields. Its `__post_init__` check raises on a negative count. If an adapter subtracts cached tokens from an input figure that never included them, the result goes negative and the error appears at the first call instead of on next month’s invoice.\n\n**Step 4: write the pricing engine.** The `PriceBook` class uses `Decimal` for every multiplication, applies tier multipliers after the base math, and raises `KeyError` on anything it cannot price. Unknown models, unknown tiers and dates before a model’s launch all stop the call path. Silent zeros are the failure mode you are trying to remove.\n\n`llmscope/pricing.py`\n\n``` python\nfrom __future__ import annotations\n\nimport json\nfrom dataclasses import dataclass\nfrom datetime import date, timedelta\nfrom decimal import Decimal\nfrom pathlib import Path\n\n@dataclass(frozen=True)\nclass Usage:\n    input_tokens: int = 0          # fresh input tokens, NOT served from cache\n    cached_input_tokens: int = 0   # input tokens read from a cache\n    output_tokens: int = 0         # visible output plus reasoning tokens\n    cache_write_tokens: int = 0    # tokens written to an explicit cache\n\n    def __post_init__(self):\n        if min(self.input_tokens, self.cached_input_tokens,\n               self.output_tokens, self.cache_write_tokens) < 0:\n            raise ValueError(\"negative token count: the provider's usage fields are not what the adapter assumes\")\n\n    @property\n    def total_input(self) -> int:\n        return self.input_tokens + self.cached_input_tokens\n\nclass PriceBook:\n    def __init__(self, rows: list[dict], per_tokens: int = 1_000_000):\n        self.rows = rows\n        self.per = Decimal(per_tokens)\n\n    @classmethod\n    def load(cls, path: str | Path) -> \"PriceBook\":\n        raw = json.loads(Path(path).read_text(encoding=\"utf-8\"))\n        return cls(raw[\"prices\"], raw.get(\"per_tokens\", 1_000_000))\n\n    def lookup(self, model: str, when: date) -> dict:\n        rows = [r for r in self.rows\n                if r[\"model\"] == model and date.fromisoformat(r[\"effective_from\"]) <= when]\n        if not rows:\n            raise KeyError(f\"no price row for {model!r} on {when}\")\n        return max(rows, key=lambda r: r[\"effective_from\"])\n\n    def cost(self, model: str, usage: Usage, when: date, tier: str = \"standard\") -> Decimal:\n        row = self.lookup(model, when)\n        tiers = row.get(\"tiers\", {\"standard\": 1})\n        if tier not in tiers:\n            raise KeyError(f\"{model!r} has no {tier!r} tier in the price book\")\n        if usage.cache_write_tokens and \"cache_write\" not in row:\n            raise KeyError(f\"{model!r} has cache writes but no cache_write price\")\n\n        d = lambda v: Decimal(str(v))\n        inp, cached, out = d(row[\"input\"]), d(row[\"cached_input\"]), d(row[\"output\"])\n        lc = row.get(\"long_context\")\n        if lc and usage.total_input > lc[\"over_input_tokens\"]:\n            inp *= d(lc[\"input_x\"])\n            cached *= d(lc[\"cached_x\"])\n            out *= d(lc[\"output_x\"])\n        total = (usage.input_tokens * inp\n                 + usage.cached_input_tokens * cached\n                 + usage.output_tokens * out\n                 + usage.cache_write_tokens * d(row.get(\"cache_write\", 0))) / self.per\n        return total * d(tiers[tier])\n\n    def upcoming_changes(self, today: date, days: int) -> list[dict]:\n        horizon = today + timedelta(days=days)\n        found = []\n        for r in self.rows:\n            start = date.fromisoformat(r[\"effective_from\"])\n            if today < start <= horizon:\n                before = self.lookup(r[\"model\"], today)\n                found.append({\n                    \"model\": r[\"model\"],\n                    \"effective_from\": r[\"effective_from\"],\n                    \"input_before\": before[\"input\"], \"input_after\": r[\"input\"],\n                    \"output_before\": before[\"output\"], \"output_after\": r[\"output\"],\n                })\n        return found\n```\n\nThe `upcoming_changes` method looks ahead from a given day and reports any row that starts inside the window. Step 9 uses it to warn about the Carbon switch before it lands.\n\nRounding deserves one sentence of attention. The tracer converts each cost to integer micro-dollars with `to_integral_value`, and `Decimal` rounds half to even by default. That choice keeps rounding bias out of long sums, so a million calls do not drift in one direction. At current prices a single call costs thousands of micro-dollars, so the rounding error per row is far below anything an invoice would show.\n\n## Step 5: Store Spans in SQLite Without Storing Prompts\n\nSQLite fits this job. It needs no server, it ships with Python, and write-ahead logging lets one process write while another runs reports. The schema stores one row per span with money in integer micro-dollars. Floats drift when you sum thousands of tiny values, while integers do not.\n\nThe schema deliberately has no prompt column. It keeps a [SHA-256](https://shattered.io/category/cryptography/) hash and a character count, which is enough to spot duplicate prompts and size anomalies. Prompts often hold customer data, and Anthropic’s docs say Claude Fable 5.2 requires 30-day data retention and is not available under legacy zero data retention unless Anthropic authorizes it. If your provider already keeps prompts for a month, your own telemetry database should not become a second, less protected copy. The tracer can capture prompt text, but only when you pass `capture_prompts=True`.\n\n`llmscope/store.py`\n\n``` python\nfrom __future__ import annotations\n\nimport sqlite3\nimport threading\nfrom pathlib import Path\n\nSCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS spans (\n  span_id TEXT PRIMARY KEY,\n  trace_id TEXT NOT NULL,\n  parent_id TEXT,\n  name TEXT NOT NULL,\n  provider TEXT,\n  model TEXT,\n  started_at TEXT NOT NULL,\n  duration_ms REAL NOT NULL,\n  ttft_ms REAL,\n  input_tokens INTEGER NOT NULL DEFAULT 0,\n  cached_input_tokens INTEGER NOT NULL DEFAULT 0,\n  output_tokens INTEGER NOT NULL DEFAULT 0,\n  cost_micro_usd INTEGER NOT NULL DEFAULT 0,\n  tier TEXT NOT NULL DEFAULT 'standard',\n  status TEXT NOT NULL,\n  error TEXT,\n  prompt_sha256 TEXT,\n  prompt_chars INTEGER,\n  tags TEXT NOT NULL DEFAULT '{}'\n);\nCREATE INDEX IF NOT EXISTS idx_spans_started ON spans(started_at);\nCREATE INDEX IF NOT EXISTS idx_spans_model ON spans(model, started_at);\n\"\"\"\n\nCOLUMNS = [\"span_id\", \"trace_id\", \"parent_id\", \"name\", \"provider\", \"model\", \"started_at\",\n           \"duration_ms\", \"ttft_ms\", \"input_tokens\", \"cached_input_tokens\", \"output_tokens\",\n           \"cost_micro_usd\", \"tier\", \"status\", \"error\", \"prompt_sha256\", \"prompt_chars\", \"tags\"]\n\nclass Store:\n    def __init__(self, path: str | Path = \"llmscope.db\"):\n        self.conn = sqlite3.connect(str(path), check_same_thread=False)\n        self.conn.row_factory = sqlite3.Row\n        self.conn.execute(\"PRAGMA journal_mode=WAL\")\n        self.conn.executescript(SCHEMA)\n        self._lock = threading.Lock()\n\n    def insert(self, span: dict) -> None:\n        unknown = set(span) - set(COLUMNS)\n        if unknown:\n            raise ValueError(f\"unknown span fields: {sorted(unknown)}\")\n        cols = [c for c in COLUMNS if span.get(c) is not None]\n        placeholders = \",\".join(\"?\" for _ in cols)\n        with self._lock, self.conn:\n            self.conn.execute(\n                f\"INSERT INTO spans ({','.join(cols)}) VALUES ({placeholders})\",\n                [span[c] for c in cols],\n            )\n\n    def query(self, sql: str, params: tuple = ()) -> list[sqlite3.Row]:\n        with self._lock:\n            return self.conn.execute(sql, params).fetchall()\n```\n\nThe `insert` method skips columns that are `None` so the schema defaults apply, and it rejects unknown fields. That strictness catches typos in span dictionaries on the first write.\n\nAdd a retention job on day one. Spans carry no prompt text by default, but they still describe your traffic, and old rows rarely earn their disk space. This statement deletes anything older than 90 days, which you can run weekly from cron. Pick a window that matches your invoice reconciliation cycle, then back up the database file before the first purge.\n\n```\nDELETE FROM spans WHERE started_at < date('now', '-90 days');\n```\n\n## Steps 6 and 7: Provider Adapters and a Tracer That Nests Spans\n\n**Step 6: write the adapters.** Each adapter turns one vendor response into a `Response` with a normalized `Usage`. Errors become a `ProviderError` carrying only a short code such as `http_429`, never the response body. Bodies can echo prompt fragments, and you do not want those in your logs. The `FakeProvider` at the bottom is a deterministic stand-in. It returns plausible token counts and a simulated duration, which makes the demo repeatable. Its latencies are invented for illustration and are not benchmark results.\n\n`llmscope/providers.py`\n\n``` python\nfrom __future__ import annotations\n\nimport json\nimport os\nimport random\nimport urllib.error\nimport urllib.request\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\nfrom .pricing import Usage\n\nclass ProviderError(RuntimeError):\n    pass\n\n@dataclass\nclass Response:\n    text: str\n    usage: Usage\n    ttft_ms: float | None = None\n    simulated_ms: float | None = None  # only the fake provider sets this\n\nclass Provider(Protocol):\n    name: str\n    model: str\n\n    def complete(self, prompt: str, **kw) -> Response: ...\n\ndef _post_json(url: str, headers: dict, body: dict, timeout: float = 60.0) -> dict:\n    req = urllib.request.Request(\n        url, data=json.dumps(body).encode(), headers={\"content-type\": \"application/json\", **headers},\n    )\n    try:\n        with urllib.request.urlopen(req, timeout=timeout) as resp:\n            return json.loads(resp.read())\n    except urllib.error.HTTPError as exc:\n        raise ProviderError(f\"http_{exc.code}\") from None\n    except (urllib.error.URLError, TimeoutError):\n        raise ProviderError(\"network\") from None\n\nclass OpenAIProvider:\n    name = \"openai\"\n\n    def __init__(self, model: str = \"gpt-6.2-astra\", api_key: str | None = None):\n        self.model = model\n        self.key = api_key or os.environ[\"OPENAI_API_KEY\"]\n\n    def complete(self, prompt: str, **kw) -> Response:\n        data = _post_json(\n            \"https://api.openai.com/v1/responses\",\n            {\"authorization\": f\"Bearer {self.key}\"},\n            {\"model\": self.model, \"input\": prompt, **kw},\n        )\n        text = \"\".join(\n            part.get(\"text\", \"\")\n            for item in data.get(\"output\", []) if item.get(\"type\") == \"message\"\n            for part in item.get(\"content\", []) if part.get(\"type\") == \"output_text\"\n        )\n        u = data[\"usage\"]\n        cached = (u.get(\"input_tokens_details\") or {}).get(\"cached_tokens\", 0)\n        # input_tokens INCLUDES cached tokens here; output_tokens includes reasoning\n        return Response(text, Usage(u[\"input_tokens\"] - cached, cached, u[\"output_tokens\"]))\n\nclass AnthropicProvider:\n    name = \"anthropic\"\n\n    def __init__(self, model: str = \"claude-fable-5-2\", api_key: str | None = None):\n        self.model = model\n        self.key = api_key or os.environ[\"ANTHROPIC_API_KEY\"]\n\n    def complete(self, prompt: str, **kw) -> Response:\n        body = {\"model\": self.model, \"max_tokens\": kw.pop(\"max_tokens\", 1024),\n                \"messages\": [{\"role\": \"user\", \"content\": prompt}], **kw}\n        data = _post_json(\n            \"https://api.anthropic.com/v1/messages\",\n            {\"x-api-key\": self.key, \"anthropic-version\": \"2023-06-01\"}, body,\n        )\n        text = \"\".join(b.get(\"text\", \"\") for b in data.get(\"content\", []) if b.get(\"type\") == \"text\")\n        u = data[\"usage\"]\n        # input_tokens EXCLUDES cache reads and cache writes on this API\n        return Response(text, Usage(\n            u[\"input_tokens\"], u.get(\"cache_read_input_tokens\", 0), u[\"output_tokens\"],\n            u.get(\"cache_creation_input_tokens\", 0),\n        ))\n\nclass GeminiProvider:\n    name = \"google\"\n\n    def __init__(self, model: str = \"gemini-4-carbon\", api_key: str | None = None):\n        self.model = model\n        self.key = api_key or os.environ[\"GEMINI_API_KEY\"]\n\n    def complete(self, prompt: str, **kw) -> Response:\n        data = _post_json(\n            f\"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent\",\n            {\"x-goog-api-key\": self.key},\n            {\"contents\": [{\"role\": \"user\", \"parts\": [{\"text\": prompt}]}], **kw},\n        )\n        parts = data[\"candidates\"][0][\"content\"].get(\"parts\", [])\n        text = \"\".join(p.get(\"text\", \"\") for p in parts)\n        m = data[\"usageMetadata\"]\n        cached = m.get(\"cachedContentTokenCount\", 0)\n        # promptTokenCount INCLUDES cached tokens; thinking tokens are reported\n        # separately from candidatesTokenCount and bill as output\n        return Response(text, Usage(\n            m[\"promptTokenCount\"] - cached, cached,\n            m.get(\"candidatesTokenCount\", 0) + m.get(\"thoughtsTokenCount\", 0),\n        ))\n\nclass FakeProvider:\n    \"\"\"Offline stand-in with plausible shapes. Latencies are simulated, not measured.\"\"\"\n\n    def __init__(self, model: str, seed: int = 7, ms_per_token: float = 12.0,\n                 base_ms: float = 600.0, cache_rate: float = 0.5, error_rate: float = 0.01,\n                 context_tokens: int = 3000, name: str = \"fake\"):\n        self.name, self.model = name, model\n        self.rng = random.Random(f\"{seed}:{model}\")\n        self.ms_per_token, self.base_ms = ms_per_token, base_ms\n        self.cache_rate, self.error_rate, self.context = cache_rate, error_rate, context_tokens\n\n    def complete(self, prompt: str, **kw) -> Response:\n        if self.rng.random() < self.error_rate:\n            raise ProviderError(\"http_529\")\n        total_in = self.context + len(prompt) // 4\n        cached = int(total_in * 0.9) if self.rng.random() < self.cache_rate else 0\n        out = int(self.rng.lognormvariate(5.8, 0.6))\n        ms = self.base_ms + out * self.ms_per_token + self.rng.expovariate(1 / 250)\n        return Response(\"ok\", Usage(total_in - cached, cached, out),\n                        ttft_ms=self.base_ms * 0.6, simulated_ms=ms)\n```\n\nIf you want the same prompts to hit all three real APIs, the [ChatGPT vs Claude vs Gemini API test harness](https://shattered.io/chatgpt-vs-claude-vs-gemini-api-test-harness-12-steps-2026/) shows how to build a fair prompt set. Feed that set through `llm_call` and your database fills with comparable rows.\n\n**Step 7: write the tracer.** The `Tracer` exposes two entry points. `span()` is a context manager for your own units of work, such as a support answer or a retrieval step. `llm_call()` wraps a provider call, times it, prices it and writes the row. A `contextvars` variable tracks the current span, so an LLM call made inside a `span()` block automatically records its parent and shares the trace ID. Failed calls still write a row with `status=\"error\"` and an error class, then re-raise so your own retry logic keeps working.\n\n`llmscope/tracer.py`\n\n``` python\nfrom __future__ import annotations\n\nimport contextvars\nimport hashlib\nimport json\nimport time\nimport uuid\nfrom contextlib import contextmanager\nfrom datetime import datetime, timezone\nfrom typing import Callable\n\nfrom .pricing import PriceBook\nfrom .providers import Provider, Response\nfrom .store import Store\n\n_current: contextvars.ContextVar[dict | None] = contextvars.ContextVar(\"llmscope_span\", default=None)\n\ndef _utc_now() -> datetime:\n    return datetime.now(timezone.utc)\n\nclass Tracer:\n    def __init__(self, store: Store, prices: PriceBook,\n                 clock: Callable[[], datetime] = _utc_now, capture_prompts: bool = False):\n        self.store, self.prices, self.clock = store, prices, clock\n        self.capture_prompts = capture_prompts\n\n    @contextmanager\n    def span(self, name: str, **tags):\n        parent = _current.get()\n        me = {\"span_id\": uuid.uuid4().hex[:16],\n              \"trace_id\": parent[\"trace_id\"] if parent else uuid.uuid4().hex,\n              \"parent_id\": parent[\"span_id\"] if parent else None}\n        token = _current.set(me)\n        started, t0, status, err = self.clock(), time.perf_counter(), \"ok\", None\n        try:\n            yield me\n        except Exception as exc:\n            status, err = \"error\", type(exc).__name__\n            raise\n        finally:\n            _current.reset(token)\n            self.store.insert({**me, \"name\": name, \"started_at\": started.isoformat(),\n                               \"duration_ms\": (time.perf_counter() - t0) * 1000,\n                               \"status\": status, \"error\": err, \"tags\": json.dumps(tags)})\n\n    def llm_call(self, provider: Provider, prompt: str, *, tier: str = \"standard\",\n                 tags: dict | None = None, **kw) -> Response:\n        parent = _current.get()\n        span_id = uuid.uuid4().hex[:16]\n        trace_id = parent[\"trace_id\"] if parent else uuid.uuid4().hex\n        started, t0 = self.clock(), time.perf_counter()\n        row = {\n            \"span_id\": span_id, \"trace_id\": trace_id,\n            \"parent_id\": parent[\"span_id\"] if parent else None,\n            \"name\": f\"llm.{provider.model}\", \"provider\": provider.name, \"model\": provider.model,\n            \"started_at\": started.isoformat(), \"tier\": tier,\n            \"prompt_sha256\": hashlib.sha256(prompt.encode()).hexdigest(),\n            \"prompt_chars\": len(prompt),\n            \"tags\": json.dumps({**(tags or {}), **({\"prompt\": prompt} if self.capture_prompts else {})}),\n        }\n        try:\n            resp = provider.complete(prompt, **kw)\n        except Exception as exc:\n            row.update(duration_ms=(time.perf_counter() - t0) * 1000,\n                       status=\"error\", error=type(exc).__name__ + \":\" + str(exc)[:40])\n            self.store.insert(row)\n            raise\n        duration = resp.simulated_ms if resp.simulated_ms is not None else (time.perf_counter() - t0) * 1000\n        cost = self.prices.cost(provider.model, resp.usage, started.date(), tier)\n        row.update(duration_ms=duration, ttft_ms=resp.ttft_ms, status=\"ok\",\n                   input_tokens=resp.usage.input_tokens,\n                   cached_input_tokens=resp.usage.cached_input_tokens,\n                   output_tokens=resp.usage.output_tokens,\n                   cost_micro_usd=int((cost * 1_000_000).to_integral_value()))\n        self.store.insert(row)\n        return resp\n```\n\nThe tracer prices each call with the date from its own clock, using `started.date()`. Injecting the clock is what lets the demo replay traffic across the December 1 boundary. It also makes unit tests deterministic.\n\n## Step 8: Report Latency Percentiles, Cache Hits and Cost\n\nAverages hide the calls users complain about. A model with a 3-second mean and a 14-second 99th percentile feels broken to one request in a hundred, and the mean never shows it. The report computes p50, p95 and p99 per model with the nearest-rank method, then adds the cache hit ratio (cached tokens divided by all input tokens) and cost per successful call. The `--daily` flag prints one line per day and model, which is the view that exposes a price change.\n\n`llmscope/report.py`\n\n``` python\nfrom __future__ import annotations\n\nimport argparse\nimport math\nfrom datetime import datetime, timedelta, timezone\n\nfrom .store import Store\n\ndef percentile(values: list[float], p: float) -> float:\n    if not values:\n        return 0.0\n    ordered = sorted(values)\n    rank = max(1, math.ceil(p / 100 * len(ordered)))\n    return ordered[rank - 1]\n\ndef by_model(store: Store, since_iso: str) -> list[dict]:\n    rows = store.query(\n        \"SELECT model, status, duration_ms, input_tokens, cached_input_tokens, output_tokens, cost_micro_usd \"\n        \"FROM spans WHERE model IS NOT NULL AND started_at >= ?\", (since_iso,))\n    groups: dict[str, list] = {}\n    for r in rows:\n        groups.setdefault(r[\"model\"], []).append(r)\n    out = []\n    for model, rs in sorted(groups.items()):\n        ok = [r for r in rs if r[\"status\"] == \"ok\"]\n        fresh = sum(r[\"input_tokens\"] for r in ok)\n        cached = sum(r[\"cached_input_tokens\"] for r in ok)\n        lat = [r[\"duration_ms\"] for r in ok]\n        out.append({\n            \"model\": model, \"calls\": len(rs), \"errors\": len(rs) - len(ok),\n            \"p50_ms\": percentile(lat, 50), \"p95_ms\": percentile(lat, 95), \"p99_ms\": percentile(lat, 99),\n            \"input_tokens\": fresh, \"cached_tokens\": cached,\n            \"output_tokens\": sum(r[\"output_tokens\"] for r in ok),\n            \"cache_hit\": cached / (fresh + cached) if fresh + cached else 0.0,\n            \"cost_usd\": sum(r[\"cost_micro_usd\"] for r in ok) / 1_000_000,\n        })\n    return out\n\ndef daily_cost(store: Store, since_iso: str) -> list:\n    return store.query(\n        \"SELECT substr(started_at,1,10) AS day, model, COUNT(*) AS calls, \"\n        \"SUM(cost_micro_usd)/1000000.0 AS cost_usd FROM spans \"\n        \"WHERE model IS NOT NULL AND status='ok' AND started_at >= ? GROUP BY day, model ORDER BY day, model\",\n        (since_iso,))\n\ndef render(rows: list[dict]) -> str:\n    head = f\"{'model':<18}{'calls':>6}{'err':>5}{'p50 ms':>9}{'p95 ms':>9}{'p99 ms':>9}{'cache%':>8}{'cost USD':>11}{'$/call':>9}\"\n    lines = [head, \"-\" * len(head)]\n    for r in rows:\n        per_call = r[\"cost_usd\"] / max(1, r[\"calls\"] - r[\"errors\"])\n        lines.append(f\"{r['model']:<18}{r['calls']:>6}{r['errors']:>5}{r['p50_ms']:>9.0f}{r['p95_ms']:>9.0f}\"\n                     f\"{r['p99_ms']:>9.0f}{r['cache_hit']*100:>7.1f}%{r['cost_usd']:>11.2f}{per_call:>9.4f}\")\n    return \"\\n\".join(lines)\n\ndef main() -> None:\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--db\", default=\"llmscope.db\")\n    ap.add_argument(\"--days\", type=int, default=7)\n    ap.add_argument(\"--since\", help=\"ISO date, overrides --days\")\n    ap.add_argument(\"--daily\", action=\"store_true\")\n    a = ap.parse_args()\n    since = a.since or (datetime.now(timezone.utc) - timedelta(days=a.days)).date().isoformat()\n    store = Store(a.db)\n    print(render(by_model(store, since)))\n    if a.daily:\n        print()\n        for r in daily_cost(store, since):\n            print(f\"{r['day']}  {r['model']:<18}{r['calls']:>4} calls  ${r['cost_usd']:>6.2f}  ${r['cost_usd']/r['calls']:.4f}/call\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\nCost per call is the figure to watch when you compare models. It captures token volume, cache behavior and price in one number, and a router can use it directly. The [Claude vs GPT router build](https://shattered.io/build-llm-router-claude-gpt-2026/) shows where such a number plugs into routing logic.\n\nRead the columns together. A model with a low p50 and a high p99 usually has a long-tail problem, such as occasional very long outputs or retries, and cutting `max_tokens` often helps. A model with a high cache percentage and a high cost per call is probably producing long outputs, because output tokens dominate the bill. A model whose cache percentage fell from 60 to near zero overnight has a prompt-prefix problem. The percentile math runs in Python because SQLite has no built-in percentile function, and sorting a few hundred thousand floats in memory takes a moment, not minutes.\n\n## Step 9: Alert on Budget, Latency, Cache Hits and the December 1 Price Change\n\nReports are pull. Alerts are push. The alert module reads thresholds from `config/alerts.json` and checks five conditions: daily spend over budget, p95 latency over a ceiling, an error rate over a limit, a cache hit ratio under a floor, and any price change inside the next seven days. It prints one line per problem and exits with status 1 if anything fired, so a cron job or CI step can fail loudly.\n\nThe ratio checks skip models with fewer than 20 calls in the day, which avoids paging someone over a model that served three requests. Tune every threshold to your own traffic, because the values in the file are starting points and not recommendations.\n\n`config/alerts.json`\n\n```\n{\n  \"daily_budget_usd\": 25.0,\n  \"p95_ms\": 9000,\n  \"error_rate\": 0.03,\n  \"min_cache_hit_ratio\": 0.20,\n  \"min_calls_for_ratio_checks\": 20,\n  \"price_change_warn_days\": 7\n}\n```\n\n`llmscope/alerts.py`\n\n``` python\nfrom __future__ import annotations\n\nimport argparse\nimport json\nimport sys\nfrom datetime import date\nfrom pathlib import Path\n\nfrom .pricing import PriceBook\nfrom .report import by_model\nfrom .store import Store\n\ndef check(store: Store, prices: PriceBook, rules: dict, today: date) -> list[str]:\n    alerts: list[str] = []\n    day = today.isoformat()\n\n    spend = store.query(\n        \"SELECT SUM(cost_micro_usd)/1000000.0 AS usd FROM spans \"\n        \"WHERE model IS NOT NULL AND status='ok' AND substr(started_at,1,10)=?\", (day,))[0][\"usd\"] or 0.0\n    if spend > rules[\"daily_budget_usd\"]:\n        alerts.append(f\"BUDGET  ${spend:.2f} spent on {day}, limit ${rules['daily_budget_usd']:.2f}\")\n\n    for m in by_model(store, day):\n        if m[\"calls\"] < rules[\"min_calls_for_ratio_checks\"]:\n            continue\n        if m[\"p95_ms\"] > rules[\"p95_ms\"]:\n            alerts.append(f\"LATENCY {m['model']} p95 {m['p95_ms']:.0f} ms, limit {rules['p95_ms']} ms\")\n        if m[\"errors\"] / m[\"calls\"] > rules[\"error_rate\"]:\n            alerts.append(f\"ERRORS  {m['model']} error rate {m['errors']/m['calls']:.1%}, limit {rules['error_rate']:.1%}\")\n        if m[\"cache_hit\"] < rules[\"min_cache_hit_ratio\"]:\n            alerts.append(f\"CACHE   {m['model']} cache hit {m['cache_hit']:.1%}, floor {rules['min_cache_hit_ratio']:.1%}\")\n\n    for c in prices.upcoming_changes(today, rules[\"price_change_warn_days\"]):\n        alerts.append(\n            f\"PRICE   {c['model']} changes on {c['effective_from']}: input ${c['input_before']:.2f} -> \"\n            f\"${c['input_after']:.2f}, output ${c['output_before']:.2f} -> ${c['output_after']:.2f} per 1M tokens\")\n    return alerts\n\ndef main() -> None:\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--db\", default=\"llmscope.db\")\n    ap.add_argument(\"--prices\", default=\"config/prices.json\")\n    ap.add_argument(\"--rules\", default=\"config/alerts.json\")\n    ap.add_argument(\"--today\", default=date.today().isoformat())\n    a = ap.parse_args()\n    rules = json.loads(Path(a.rules).read_text())\n    found = check(Store(a.db), PriceBook.load(a.prices), rules, date.fromisoformat(a.today))\n    for line in found:\n        print(line)\n    print(f\"{len(found)} alert(s)\")\n    sys.exit(1 if found else 0)\n\nif __name__ == \"__main__\":\n    main()\n```\n\nTeams that prefer a central choke point can log at a proxy instead of in app code. [Cloudflare AI Gateway](https://shattered.io/cloudflare-ai-gateway-setup-2026/) is one way to do that, and it complements this design rather than replacing it. A gateway sees traffic, while only your application knows which feature, route or customer a call belongs to.\n\nTo wire the alerts into a schedule, add one cron line. Because the module exits with status 1 when any rule fires, the right-hand side of `||` runs only when there is something to read:\n\n```\n15 7 * * * cd /srv/llmscope && .venv/bin/python -m llmscope.alerts > alerts.log 2>&1 || curl -fsS -X POST \"$WEBHOOK_URL\" --data-binary @alerts.log\n```\n\nSet `WEBHOOK_URL` to your chat or paging endpoint. If the alert text will reach a shared channel, remember that it names models and spend levels, so route it to a channel with the right audience.\n\n## Steps 10 to 12: Tests, a Demo Run and an OpenTelemetry Export\n\n**Step 10: write the tests.** Pricing is money, so it gets unit tests before anything else. Each expected value below comes from arithmetic you can do by hand. The Fable case, for example, is 1,000 fresh tokens at $8, 500 cached tokens at $0.20 and 2,000 output tokens at $40 per million, which sums to $0.0881. One test pins the Carbon price flip at midnight on December 1, another proves that the long-context multiplier applies to the whole request, and others check that unknown tiers, pre-launch dates and negative usage all raise.\n\n`tests/test_pricing.py`\n\n``` python\nimport unittest\nfrom datetime import date\nfrom decimal import Decimal\n\nfrom llmscope.pricing import PriceBook, Usage\n\nBOOK = PriceBook.load(\"config/prices.json\")\n\nclass PricingTests(unittest.TestCase):\n    def test_fable_standard(self):\n        # 1,000 fresh in, 500 cached in, 2,000 out at $8 / $0.20 / $40 per 1M\n        c = BOOK.cost(\"claude-fable-5-2\", Usage(1000, 500, 2000), date(2026, 11, 25))\n        self.assertEqual(c, Decimal(\"0.0881\"))\n\n    def test_carbon_price_changes_on_december_first(self):\n        u = Usage(1_000_000, 0, 1_000_000)\n        self.assertEqual(BOOK.cost(\"gemini-4-carbon\", u, date(2026, 11, 30)), Decimal(\"12.00\"))\n        self.assertEqual(BOOK.cost(\"gemini-4-carbon\", u, date(2026, 12, 1)), Decimal(\"24.00\"))\n\n    def test_long_context_multiplier_applies_to_whole_request(self):\n        small = BOOK.cost(\"gpt-6.2-astra\", Usage(100_000, 0, 1000), date(2026, 11, 25))\n        big = BOOK.cost(\"gpt-6.2-astra\", Usage(300_000, 0, 1000), date(2026, 11, 25))\n        self.assertEqual(small, Decimal(\"0.84\"))\n        self.assertEqual(big, Decimal(\"4.86\"))\n\n    def test_batch_tier_halves_cost(self):\n        u = Usage(1000, 0, 1000)\n        std = BOOK.cost(\"claude-fable-5-2\", u, date(2026, 11, 25))\n        self.assertEqual(BOOK.cost(\"claude-fable-5-2\", u, date(2026, 11, 25), \"batch\"), std / 2)\n\n    def test_unknown_tier_fails_loudly(self):\n        with self.assertRaises(KeyError):\n            BOOK.cost(\"gemini-4-carbon\", Usage(1, 0, 1), date(2026, 11, 25), \"batch\")\n\n    def test_price_before_launch_fails_loudly(self):\n        with self.assertRaises(KeyError):\n            BOOK.cost(\"gpt-6.2-astra\", Usage(1, 0, 1), date(2026, 11, 1))\n\n    def test_negative_usage_is_rejected(self):\n        with self.assertRaises(ValueError):\n            Usage(-5, 100, 10)\n\n    def test_upcoming_change_found(self):\n        found = BOOK.upcoming_changes(date(2026, 11, 25), 7)\n        self.assertEqual([f[\"model\"] for f in found], [\"gemini-4-carbon\"])\n\nif __name__ == \"__main__\":\n    unittest.main()\n```\n\n**Step 11: run the demo.** The script replays simulated traffic spread over the three models. Each call sits inside a parent span named `support.answer`, so the database holds both span types.\n\n`scripts/demo.py`\n\n```\n\"\"\"Fill llmscope.db with simulated traffic across a price change. No API keys needed.\"\"\"\nfrom __future__ import annotations\n\nimport argparse\nimport random\nfrom datetime import datetime, timedelta, timezone\n\nfrom llmscope.pricing import PriceBook\nfrom llmscope.providers import FakeProvider, ProviderError\nfrom llmscope.store import Store\nfrom llmscope.tracer import Tracer\n\nFLEET = [\n    (\"gpt-6.2-astra\",    dict(ms_per_token=7, base_ms=700, cache_rate=0.55), \"openai\"),\n    (\"claude-fable-5-2\", dict(ms_per_token=8, base_ms=900, cache_rate=0.60), \"anthropic\"),\n    (\"gemini-4-carbon\",  dict(ms_per_token=5, base_ms=650, cache_rate=0.35), \"google\"),\n]\n\ndef main() -> None:\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--db\", default=\"llmscope.db\")\n    ap.add_argument(\"--start\", default=\"2026-11-27\")\n    ap.add_argument(\"--days\", type=int, default=6)\n    ap.add_argument(\"--calls-per-day\", type=int, default=60)\n    a = ap.parse_args()\n\n    store = Store(a.db)\n    prices = PriceBook.load(\"config/prices.json\")\n    start = datetime.fromisoformat(a.start).replace(tzinfo=timezone.utc)\n    clock_value = [start]\n    tracer = Tracer(store, prices, clock=lambda: clock_value[0])\n    providers = [(FakeProvider(m, name=n, **kw), m) for m, kw, n in FLEET]\n    rng = random.Random(11)\n\n    for day in range(a.days):\n        for i in range(a.calls_per_day):\n            clock_value[0] = start + timedelta(days=day, seconds=i * 1200)\n            provider, _ = rng.choice(providers)\n            try:\n                with tracer.span(\"support.answer\", route=\"faq\"):\n                    tracer.llm_call(provider, \"Summarize the refund policy for order \" + str(i) * 40)\n            except ProviderError:\n                pass\n    print(f\"wrote {store.query('SELECT COUNT(*) AS n FROM spans')[0]['n']} spans to {a.db}\")\n\nif __name__ == \"__main__\":\n    main()\n```\n\n**Step 12: export to OpenTelemetry (optional).** If you already run a collector or a vendor backend that accepts OTLP, replay the stored spans through the OpenTelemetry SDK. The exporter emits attributes named after the GenAI conventions (`gen_ai.request.model`, `gen_ai.usage.input_tokens` and so on) plus `llmscope.*` attributes for cost and tier. Those conventions may still change, so check the current spec before you depend on a name. OpenTelemetry itself keeps shipping, and its [JavaScript SDK 3.0](https://opentelemetry.io/blog/2026/otel-js-sdk-3-0/) is a recent release. This project pins no Python SDK version, and you should install the latest release.\n\n`llmscope/otel_export.py`\n\n```\n\"\"\"Optional: replay stored spans through OpenTelemetry. Needs: pip install opentelemetry-sdk\"\"\"\nfrom __future__ import annotations\n\nimport argparse\nfrom datetime import datetime\n\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter\n\nfrom .store import Store\n\ndef export(store: Store, since_iso: str, limit: int = 1000, exporter=None) -> int:\n    provider = TracerProvider()\n    provider.add_span_processor(BatchSpanProcessor(exporter or ConsoleSpanExporter()))\n    tracer = provider.get_tracer(\"llmscope\")\n    rows = store.query(\n        \"SELECT * FROM spans WHERE model IS NOT NULL AND status='ok' AND started_at >= ? \"\n        \"ORDER BY started_at LIMIT ?\", (since_iso, limit))\n    for r in rows:\n        start_ns = int(datetime.fromisoformat(r[\"started_at\"]).timestamp() * 1e9)\n        attrs = {\n            \"gen_ai.provider.name\": r[\"provider\"],\n            \"gen_ai.request.model\": r[\"model\"],\n            \"gen_ai.usage.input_tokens\": r[\"input_tokens\"] + r[\"cached_input_tokens\"],\n            \"gen_ai.usage.output_tokens\": r[\"output_tokens\"],\n            \"llmscope.cached_input_tokens\": r[\"cached_input_tokens\"],\n            \"llmscope.cost_usd\": r[\"cost_micro_usd\"] / 1_000_000,\n            \"llmscope.tier\": r[\"tier\"],\n        }\n        span = tracer.start_span(r[\"name\"], start_time=start_ns, attributes=attrs)\n        span.end(end_time=start_ns + int(r[\"duration_ms\"] * 1e6))\n    provider.shutdown()\n    return len(rows)\n\nif __name__ == \"__main__\":\n    ap = argparse.ArgumentParser()\n    ap.add_argument(\"--db\", default=\"llmscope.db\")\n    ap.add_argument(\"--since\", required=True)\n    ap.add_argument(\"--limit\", type=int, default=3)\n    a = ap.parse_args()\n    print(f\"exported {export(Store(a.db), a.since, a.limit)} spans\")\n```\n\nRun everything from the project root so the `llmscope` package resolves:\n\n```\npython3 -m unittest -v\npython3 -m scripts.demo\npython3 -m llmscope.report --since 2026-11-27 --daily\npython3 -m llmscope.alerts --today 2026-11-28\npip install opentelemetry-sdk\npython3 -m llmscope.otel_export --since 2026-12-01 --limit 1\n```\n\n## Sample Output and How to Read It\n\nThe runs below came from the exact code above on Python 3.12.3. The unit tests finish in a few milliseconds, and the demo writes 720 spans. That is 360 LLM calls (6 days times 60) plus 360 parent spans.\n\n```\nRan 8 tests in 0.001s\n\nOK\nwrote 720 spans to llmscope.db\n```\n\nThe report for the whole window shows one line per model:\n\n```\nmodel              calls  err   p50 ms   p95 ms   p99 ms  cache%   cost USD   $/call\n------------------------------------------------------------------------------------\nclaude-fable-5-2     114    0     3656     7339    14002   60.0%       2.90   0.0254\ngemini-4-carbon      110    0     2467     5316     6048   33.5%       1.17   0.0106\ngpt-6.2-astra        136    1     3285     7378    10004   56.0%       3.68   0.0273\n```\n\nThe daily view for Carbon makes the price change visible. Cost per call sits near $0.007 to $0.009 through November 30, then roughly doubles once the new rate applies:\n\n``` bash\n2026-11-27  gemini-4-carbon      24 calls  $  0.21  $0.0087/call\n2026-11-28  gemini-4-carbon      13 calls  $  0.10  $0.0074/call\n2026-11-29  gemini-4-carbon      18 calls  $  0.13  $0.0072/call\n2026-11-30  gemini-4-carbon      20 calls  $  0.16  $0.0079/call\n2026-12-01  gemini-4-carbon      20 calls  $  0.31  $0.0154/call\n2026-12-02  gemini-4-carbon      15 calls  $  0.27  $0.0177/call\n```\n\nThe jump is a bit under 2x on some days and a bit over on others, because cache share and output length vary from call to call. Run the alert check three days before the switch and it warns you:\n\n``` php\nPRICE   gemini-4-carbon changes on 2026-12-01: input $2.00 -> $4.00, output $10.00 -> $20.00 per 1M tokens\n1 alert(s)\n```\n\nA replayed span from the OpenTelemetry export carries the attributes below. The input token count there is fresh plus cached tokens, a choice you should confirm against the current spec:\n\n```\n\"attributes\": {\n    \"gen_ai.provider.name\": \"openai\",\n    \"gen_ai.request.model\": \"gpt-6.2-astra\",\n    \"gen_ai.usage.input_tokens\": 3019,\n    \"gen_ai.usage.output_tokens\": 141,\n    \"llmscope.cached_input_tokens\": 2717,\n    \"llmscope.cost_usd\": 0.009143,\n    \"llmscope.tier\": \"standard\"\n}\n```\n\n### Limits of the Simulated Data\n\nTreat the numbers above as a test of the plumbing and not as a model comparison. The latencies, token counts and cache rates come from a seeded random generator, and I chose the per-token delays myself. Nothing here says Fable 5.2 is slower than Carbon. What the output does prove is that the price book, the date logic, the percentile math and the alert exit codes behave as designed. Swap in the live adapters and your real traffic fills the same tables.\n\n## Common Pitfalls That Corrupt LLM Cost Numbers\n\n**Counting cached tokens twice.** OpenAI and Gemini report a total input count that already includes the cached portion, while Anthropic reports fresh input separately. Add cached tokens on top of the wrong provider’s total and you overbill that provider’s calls by the cached share, which can be most of the prompt.\n\n**Using one flat price for a model that changes.** Carbon’s introductory rate ends on November 30. A config with a single row under-reports spend by half from December 1. Dated rows fix this, and the upcoming-change alert tells you to add the next row before it matters.\n\n**Ignoring the provider’s day boundary.** The store works in UTC. OpenAI states its Ultrafast multiplier change in Pacific time, and a call at 11 p.m. Pacific on November 30 is already December 1 in UTC. For the Carbon switch I found no time zone in the text I checked, so confirm the cutover moment with Google before you reconcile to the cent.\n\n**Reporting the mean.** A mean latency of 3 seconds can coexist with a p99 of 14 seconds, as the sample output shows. Alert on p95 and chart p99.\n\n**Logging prompts by default.** Prompt text turns an ops database into a privacy liability. Keep the hash and length, gate full capture behind a flag, and expire captured text on a short schedule.\n\n**Skipping tier and context multipliers.** A batch job at half price and a 300,000-token request at double the input rate both distort averages if you price them as standard. Record the tier on every span, and let the price book apply the multipliers.\n\n**Mixing model generations.** OpenAI’s pricing table reportedly lists GPT-6 Astra next to GPT-6.2 Astra, and one result I checked showed $10 and $50 for the older ID. Pin exact IDs in config and fail on any ID the price book does not know. Spend measured against the wrong generation looks plausible and is wrong.\n\n**Storing money as floats.** Summing 100,000 floating-point costs leaves rounding noise you will chase for an afternoon. Integers in micro-dollars and `Decimal` in the pricing math avoid the whole class.\n\nIf your goal is cost per accepted output and not cost per call, [the writing-cost experiment](https://shattered.io/claude-vs-chatgpt-writing-cost-per-accepted-1000-words-12-steps-2026/) shows how to divide spend by results a human actually kept. Add an `accepted` tag to the span and the same tables answer that question.\n\n## Troubleshooting: 10 Errors and Their Fixes\n\n- **KeyError: no price row for ‘x’ on a date.** Either the model ID is misspelled or the call date falls before the row’s`effective_from` . Compare the ID in your provider object with`config/prices.json` , and check the clock if you are replaying old data.\n- **KeyError: no ‘batch’ tier.** The Carbon rows define only`standard` , so the engine refuses to guess. Add a tier multiplier after you confirm the vendor’s batch discount for that model.\n- **KeyError about cache_write.** The usage block reported cache-creation tokens and the row has no`cache_write` price. Copy the write price from the vendor’s pricing page into the row. Do not set it to zero.\n- **ValueError: negative token count.** An adapter assumption is wrong for that provider or model. Print the raw usage block (snippet below) and compare it with the table in Step 3.\n- **sqlite3.OperationalError: database is locked.** Two processes are writing at once and one waited past the default five-second timeout. Run a single writer, or open the connection with a longer`timeout` value.\n- **ProviderError http_401 or http_403.** The key is missing, wrong or lacks access to the model. Google developers have reportedly seen Carbon shown as unavailable on some plans, so confirm you use a paid Gemini API key and not a consumer plan.\n- **ModuleNotFoundError: No module named ‘llmscope’.** You ran a script by path. Run`python3 -m scripts.demo` from the project root so Python adds the root to its path.\n- **The report prints only a header.** The default window is the last seven days by the real clock, and your data is dated elsewhere. Pass`--since 2026-11-27` or the first date in your data.\n- **The cache alert fires on every run.** The stable prefix of your prompt is probably changing, so nothing matches the cache. Move variable text such as user names and timestamps to the end of the prompt. One developer reportedly saw degraded Carbon cache reuse in a Google tool, so a sudden drop on a stable prompt is worth a support ticket.\n- **ImportError: opentelemetry.** The SDK is not installed in the active environment. Run`pip install opentelemetry-sdk` inside the virtual environment you use for the export.\n\nTo inspect a raw usage block from a live Anthropic call, reuse the project’s own HTTP helper. The same pattern works for the other two providers with their URLs and headers. I did not run this snippet here because it needs a live key.\n\n``` python\nimport json, os\nfrom llmscope.providers import _post_json\n\ndata = _post_json(\n    \"https://api.anthropic.com/v1/messages\",\n    {\"x-api-key\": os.environ[\"ANTHROPIC_API_KEY\"], \"anthropic-version\": \"2023-06-01\"},\n    {\"model\": \"claude-fable-5-2\", \"max_tokens\": 64,\n     \"messages\": [{\"role\": \"user\", \"content\": \"Say hi\"}]},\n)\nprint(json.dumps(data[\"usage\"], indent=2))\n```\n\n## Advanced Tips for Production LLM Observability\n\n**Model time-limited multipliers as rows.** OpenAI’s page says Ultrafast costs 3 times the standard rate through February 28, 2027 and 6 times from March 1, 2027, in Pacific time. Add an `ultrafast` tier of 3 to the current row now, then copy the row with `\"effective_from\": \"2027-03-01\"` and a tier of 6. The engine needs no code change.\n\n```\n{\"model\": \"gpt-6.2-astra\", \"effective_from\": \"2027-03-01\",\n \"input\": 8.00, \"cached_input\": 0.40, \"output\": 40.00,\n \"tiers\": {\"standard\": 1, \"batch\": 0.5, \"fast\": 2, \"ultrafast\": 6}}\n```\n\n**Tag spend by owner.** Pass `tags={\"feature\": \"search\", \"tenant\": \"acme\"}` to `llm_call`, then group by JSON fields with SQLite’s `json_extract`. Budgets by feature stop arguments about whose traffic caused the overrun.\n\n**Measure time to first token with streaming.** Non-streaming calls report only total duration. Users feel the first token, so add a streaming path that stamps `ttft_ms` when the first chunk arrives. The column already exists in the schema.\n\n**Sample, do not drop.** At high volume, keep every error and every call above your p95 latency, and sample the rest. Cost totals stay exact if you still price every call and only sample what gets stored in detail.\n\n**Reconcile weekly against invoices.** Export each vendor’s usage CSV, compare it with your span totals per model per day, and investigate gaps over a couple of percent. Gaps usually point to a missing multiplier, such as regional inference pricing, or to calls made outside the tracer.\n\n**Use price parity as a prompt to re-measure.** When two flagship models land at the same list price, as with [GPT-6.2 Astra and Claude at $8](https://shattered.io/gpt-6-2-astra-sol-anthropic-real-winner-8-dollar-price-parity/), cost per call depends on caching and output length, not the list price. Your daily view settles the question for your workload. For more model and tooling coverage, see the [AI and machine learning section](https://shattered.io/category/ai-machine-learning/).\n\n**Schedule the price check.** Run the alert module from cron every morning. A nightly job that exits non-zero on a pending price change is cheap insurance, and it keeps the price book honest as vendors keep shipping new model versions.\n\n## FAQ: LLM Observability and Cost Tracking\n\n**What is LLM observability?**\n\nIt is the practice of capturing structured telemetry for each model call, including tokens, cache use, latency, errors and cost, so you can debug quality and spending problems with data. It borrows ideas from application tracing and adds money and token accounting.\n\n**Do I need OpenTelemetry to do this?**\n\nNo. The core project writes to SQLite and needs only the standard library. OpenTelemetry becomes useful when you want spans in a shared backend next to your other services, and Step 12 shows the bridge.\n\n**How do I track LLM costs when prompt caching is on?**\n\nRecord fresh and cached input tokens separately and price each at its own rate. Cached reads cost $0.40 per million tokens on GPT-6.2 Astra and $0.20 on Claude Fable 5.2 according to the vendors’ pages, against $8 for fresh input on both. Blending them into one input number hides the savings and the regressions.\n\n**Will the Carbon price change corrupt my history?**\n\nNo. Old spans keep the cost computed at the rate in force on their date, because the cost is stored on the row when the call happens. Only new calls use the December 1 row.\n\n**Is it safe to store prompts in the trace database?**\n\nOnly with care. The default design stores a hash and a length. If you capture text for debugging, restrict access, redact personal data first and delete captured text on a short schedule.\n\n**Which latency percentile should trigger an alert?**\n\nStart with p95 on a per-model basis, since p99 gets noisy at low volume. Chart p99 so tail problems stay visible, and alert on it once you have enough calls for it to mean something.\n\n**Can I run this next to a gateway or proxy?**\n\nYes. A gateway records traffic at the network edge, and this project records application context such as feature, route and tenant. Reconcile the two weekly, and treat differences as bugs in one of them.", "url": "https://wpnews.pro/news/llm-observability-in-python-12-steps-80-min", "canonical_source": "https://shattered.io/llm-observability-python-tokens-cost-latency-12-steps-2026/", "published_at": "2026-11-25 10:30:25+00:00", "updated_at": "2026-11-25 10:43:59.103583+00:00", "lang": "en", "topics": ["ai-tools", "mlops", "ai-infrastructure", "large-language-models", "developer-tools"], "entities": ["Shattered.io", "Anthropic", "Claude Fable 5.2", "OpenAI", "GPT-6.2 Astra", "Google", "Gemini 4 Carbon", "llmscope"], "also_reported_by": [], "takeaway": "Record fresh input tokens, cached input tokens, output and thinking tokens, duration, time to first token, status and micro-dollar cost per call in one SQLite schema so a cache that stops hitting or a call path that doubles spend surfaces before the monthly invoice does.", "recommendation": {"advice": "Log fresh and cached input tokens, output tokens, latency and micro-dollar cost for every model call in one schema across providers, then alert on per-feature spend and cache hit rate instead of waiting for the invoice.", "playbook": "production-ops", "playbook_url": "https://wpnews.pro/playbooks/production-ops"}, "alternates": {"html": "https://wpnews.pro/news/llm-observability-in-python-12-steps-80-min", "markdown": "https://wpnews.pro/news/llm-observability-in-python-12-steps-80-min.md", "text": "https://wpnews.pro/news/llm-observability-in-python-12-steps-80-min.txt", "jsonld": "https://wpnews.pro/news/llm-observability-in-python-12-steps-80-min.jsonld"}}