LLM Observability in Python: 12 Steps, 80 Min 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. Don't miss new tech stories on Google Add Shattered once in the Google app and our stories show up in your news suggestions. Add now https://www.google.com/preferences/source?hl=en&q=https%3A%2F%2Fshattered.io%2F LLM Observability: What to Record for Every Model Call Three 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. LLM 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. The 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. | Signal | Why it matters | Where it comes from | |---|---|---| | Fresh input tokens | Billed at the full input rate | Provider usage block | | Cached input tokens | Billed at a steep discount, so a drop signals a broken cache | Provider usage block | | Output and thinking tokens | Usually the largest line on the bill | Provider usage block | | Duration and time to first token | Drives user experience and timeouts | Your own timer | | Status and error class | Separates rate limits from outages | Exception type or HTTP status | | Cost in micro-dollars | The number finance asks about | Token counts times a dated price | | Tags feature, route, tenant | Assigns spend to an owner | Your call sites | Why Vendor Dashboards Are Not Enough Each 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. Prerequisites: Versions, Keys and Time Plan 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. | Requirement | Version or tier | Notes | |---|---|---| | Python | 3.12 or newer | Tested on 3.12.3 | | SQLite | Bundled with Python | Tested on 3.45.1 | | 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 | | Anthropic API access | A key for Claude Fable 5.2 | Anthropic lists Fable 5.2 as available to all customers on the Claude API | | Google API access | A paid Gemini API key | Gemini 4 Carbon is not available on the Free tier | | opentelemetry-sdk | Latest release | Optional, Step 12 only. Tested in a throwaway virtual environment | API Keys and Environment Create 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. mkdir llmscope && cd llmscope python3 --version expect 3.12 or newer python3 -m venv .venv && source .venv/bin/activate mkdir -p llmscope config scripts tests touch tests/ init .py only needed for live calls, skip for the offline demo export OPENAI API KEY="sk-your-key" export ANTHROPIC API KEY="your-key" export GEMINI API KEY="your-key" A 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. Steps 1 and 2: Project Layout and a Dated Price Book 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. llmscope/ config/ alerts.json prices.json llmscope/ init .py alerts.py otel export.py pricing.py providers.py report.py store.py tracer.py scripts/ demo.py tests/ init .py test pricing.py 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. The 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. config/prices.json { "currency": "USD", "per tokens": 1000000, "prices": { "model": "gpt-6.2-astra", "effective from": "2026-11-17", "input": 8.00, "cached input": 0.40, "output": 40.00, "tiers": {"standard": 1, "batch": 0.5, "fast": 2}, "long context": {"over input tokens": 272000, "input x": 2, "cached x": 2, "output x": 1.5}, "source": "OpenAI GPT-6.2 Astra model page, checked 2026-11-25" }, { "model": "claude-fable-5-2", "effective from": "2026-11-09", "input": 8.00, "cached input": 0.20, "output": 40.00, "tiers": {"standard": 1, "batch": 0.5, "fast": 2}, "source": "Claude Platform Docs, Fable 5.2 overview, checked 2026-11-25" }, { "model": "gemini-4-carbon", "effective from": "2026-11-10", "input": 2.00, "cached input": 0.10, "output": 10.00, "tiers": {"standard": 1}, "source": "Google introductory price, valid through 2026-11-30" }, { "model": "gemini-4-carbon", "effective from": "2026-12-01", "input": 4.00, "cached input": 0.20, "output": 20.00, "tiers": {"standard": 1}, "source": "Google post-introduction price", "note": "Cached rate assumes the 95% discount carries over. Confirm on Google's pricing page." } } | Model | Input per 1M | Cached input per 1M | Output per 1M | Valid from | |---|---|---|---|---| | GPT-6.2 Astra | $8.00 | $0.40 | $40.00 | November 17, 2026 | | Claude Fable 5.2 | $8.00 | $0.20 cache reads | $40.00 | November 9, 2026 | | Gemini 4 Carbon introductory | $2.00 | 95% below input rate | $10.00 | November 10 to 30, 2026 | | Gemini 4 Carbon after the introduction | $4.00 | Assumed 95% below input rate | $20.00 | December 1, 2026 | The 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. Steps 3 and 4: Normalize Usage and Price Every Call 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. | Provider | Input field | Cached tokens | Output and thinking | |---|---|---|---| | OpenAI Responses API | input tokens includes cached | input tokens details.cached tokens | output tokens includes reasoning | | Anthropic Messages API | input tokens excludes cache reads and writes | cache read input tokens and cache creation input tokens | output tokens | | Gemini API | promptTokenCount includes cached | cachedContentTokenCount | candidatesTokenCount plus thoughtsTokenCount | The 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. 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. llmscope/pricing.py python from future import annotations import json from dataclasses import dataclass from datetime import date, timedelta from decimal import Decimal from pathlib import Path @dataclass frozen=True class Usage: input tokens: int = 0 fresh input tokens, NOT served from cache cached input tokens: int = 0 input tokens read from a cache output tokens: int = 0 visible output plus reasoning tokens cache write tokens: int = 0 tokens written to an explicit cache def post init self : if min self.input tokens, self.cached input tokens, self.output tokens, self.cache write tokens < 0: raise ValueError "negative token count: the provider's usage fields are not what the adapter assumes" @property def total input self - int: return self.input tokens + self.cached input tokens class PriceBook: def init self, rows: list dict , per tokens: int = 1 000 000 : self.rows = rows self.per = Decimal per tokens @classmethod def load cls, path: str | Path - "PriceBook": raw = json.loads Path path .read text encoding="utf-8" return cls raw "prices" , raw.get "per tokens", 1 000 000 def lookup self, model: str, when: date - dict: rows = r for r in self.rows if r "model" == model and date.fromisoformat r "effective from" <= when if not rows: raise KeyError f"no price row for {model r} on {when}" return max rows, key=lambda r: r "effective from" def cost self, model: str, usage: Usage, when: date, tier: str = "standard" - Decimal: row = self.lookup model, when tiers = row.get "tiers", {"standard": 1} if tier not in tiers: raise KeyError f"{model r} has no {tier r} tier in the price book" if usage.cache write tokens and "cache write" not in row: raise KeyError f"{model r} has cache writes but no cache write price" d = lambda v: Decimal str v inp, cached, out = d row "input" , d row "cached input" , d row "output" lc = row.get "long context" if lc and usage.total input lc "over input tokens" : inp = d lc "input x" cached = d lc "cached x" out = d lc "output x" total = usage.input tokens inp + usage.cached input tokens cached + usage.output tokens out + usage.cache write tokens d row.get "cache write", 0 / self.per return total d tiers tier def upcoming changes self, today: date, days: int - list dict : horizon = today + timedelta days=days found = for r in self.rows: start = date.fromisoformat r "effective from" if today < start <= horizon: before = self.lookup r "model" , today found.append { "model": r "model" , "effective from": r "effective from" , "input before": before "input" , "input after": r "input" , "output before": before "output" , "output after": r "output" , } return found The 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. Rounding 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. Step 5: Store Spans in SQLite Without Storing Prompts SQLite 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. The 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 . llmscope/store.py python from future import annotations import sqlite3 import threading from pathlib import Path SCHEMA = """ CREATE TABLE IF NOT EXISTS spans span id TEXT PRIMARY KEY, trace id TEXT NOT NULL, parent id TEXT, name TEXT NOT NULL, provider TEXT, model TEXT, started at TEXT NOT NULL, duration ms REAL NOT NULL, ttft ms REAL, input tokens INTEGER NOT NULL DEFAULT 0, cached input tokens INTEGER NOT NULL DEFAULT 0, output tokens INTEGER NOT NULL DEFAULT 0, cost micro usd INTEGER NOT NULL DEFAULT 0, tier TEXT NOT NULL DEFAULT 'standard', status TEXT NOT NULL, error TEXT, prompt sha256 TEXT, prompt chars INTEGER, tags TEXT NOT NULL DEFAULT '{}' ; CREATE INDEX IF NOT EXISTS idx spans started ON spans started at ; CREATE INDEX IF NOT EXISTS idx spans model ON spans model, started at ; """ COLUMNS = "span id", "trace id", "parent id", "name", "provider", "model", "started at", "duration ms", "ttft ms", "input tokens", "cached input tokens", "output tokens", "cost micro usd", "tier", "status", "error", "prompt sha256", "prompt chars", "tags" class Store: def init self, path: str | Path = "llmscope.db" : self.conn = sqlite3.connect str path , check same thread=False self.conn.row factory = sqlite3.Row self.conn.execute "PRAGMA journal mode=WAL" self.conn.executescript SCHEMA self. lock = threading.Lock def insert self, span: dict - None: unknown = set span - set COLUMNS if unknown: raise ValueError f"unknown span fields: {sorted unknown }" cols = c for c in COLUMNS if span.get c is not None placeholders = ",".join "?" for in cols with self. lock, self.conn: self.conn.execute f"INSERT INTO spans {','.join cols } VALUES {placeholders} ", span c for c in cols , def query self, sql: str, params: tuple = - list sqlite3.Row : with self. lock: return self.conn.execute sql, params .fetchall The 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. Add 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. DELETE FROM spans WHERE started at < date 'now', '-90 days' ; Steps 6 and 7: Provider Adapters and a Tracer That Nests Spans 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. llmscope/providers.py python from future import annotations import json import os import random import urllib.error import urllib.request from dataclasses import dataclass from typing import Protocol from .pricing import Usage class ProviderError RuntimeError : pass @dataclass class Response: text: str usage: Usage ttft ms: float | None = None simulated ms: float | None = None only the fake provider sets this class Provider Protocol : name: str model: str def complete self, prompt: str, kw - Response: ... def post json url: str, headers: dict, body: dict, timeout: float = 60.0 - dict: req = urllib.request.Request url, data=json.dumps body .encode , headers={"content-type": "application/json", headers}, try: with urllib.request.urlopen req, timeout=timeout as resp: return json.loads resp.read except urllib.error.HTTPError as exc: raise ProviderError f"http {exc.code}" from None except urllib.error.URLError, TimeoutError : raise ProviderError "network" from None class OpenAIProvider: name = "openai" def init self, model: str = "gpt-6.2-astra", api key: str | None = None : self.model = model self.key = api key or os.environ "OPENAI API KEY" def complete self, prompt: str, kw - Response: data = post json "https://api.openai.com/v1/responses", {"authorization": f"Bearer {self.key}"}, {"model": self.model, "input": prompt, kw}, text = "".join part.get "text", "" for item in data.get "output", if item.get "type" == "message" for part in item.get "content", if part.get "type" == "output text" u = data "usage" cached = u.get "input tokens details" or {} .get "cached tokens", 0 input tokens INCLUDES cached tokens here; output tokens includes reasoning return Response text, Usage u "input tokens" - cached, cached, u "output tokens" class AnthropicProvider: name = "anthropic" def init self, model: str = "claude-fable-5-2", api key: str | None = None : self.model = model self.key = api key or os.environ "ANTHROPIC API KEY" def complete self, prompt: str, kw - Response: body = {"model": self.model, "max tokens": kw.pop "max tokens", 1024 , "messages": {"role": "user", "content": prompt} , kw} data = post json "https://api.anthropic.com/v1/messages", {"x-api-key": self.key, "anthropic-version": "2023-06-01"}, body, text = "".join b.get "text", "" for b in data.get "content", if b.get "type" == "text" u = data "usage" input tokens EXCLUDES cache reads and cache writes on this API return Response text, Usage u "input tokens" , u.get "cache read input tokens", 0 , u "output tokens" , u.get "cache creation input tokens", 0 , class GeminiProvider: name = "google" def init self, model: str = "gemini-4-carbon", api key: str | None = None : self.model = model self.key = api key or os.environ "GEMINI API KEY" def complete self, prompt: str, kw - Response: data = post json f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent", {"x-goog-api-key": self.key}, {"contents": {"role": "user", "parts": {"text": prompt} } , kw}, parts = data "candidates" 0 "content" .get "parts", text = "".join p.get "text", "" for p in parts m = data "usageMetadata" cached = m.get "cachedContentTokenCount", 0 promptTokenCount INCLUDES cached tokens; thinking tokens are reported separately from candidatesTokenCount and bill as output return Response text, Usage m "promptTokenCount" - cached, cached, m.get "candidatesTokenCount", 0 + m.get "thoughtsTokenCount", 0 , class FakeProvider: """Offline stand-in with plausible shapes. Latencies are simulated, not measured.""" def init self, model: str, seed: int = 7, ms per token: float = 12.0, base ms: float = 600.0, cache rate: float = 0.5, error rate: float = 0.01, context tokens: int = 3000, name: str = "fake" : self.name, self.model = name, model self.rng = random.Random f"{seed}:{model}" self.ms per token, self.base ms = ms per token, base ms self.cache rate, self.error rate, self.context = cache rate, error rate, context tokens def complete self, prompt: str, kw - Response: if self.rng.random < self.error rate: raise ProviderError "http 529" total in = self.context + len prompt // 4 cached = int total in 0.9 if self.rng.random < self.cache rate else 0 out = int self.rng.lognormvariate 5.8, 0.6 ms = self.base ms + out self.ms per token + self.rng.expovariate 1 / 250 return Response "ok", Usage total in - cached, cached, out , ttft ms=self.base ms 0.6, simulated ms=ms If 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. 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. llmscope/tracer.py python from future import annotations import contextvars import hashlib import json import time import uuid from contextlib import contextmanager from datetime import datetime, timezone from typing import Callable from .pricing import PriceBook from .providers import Provider, Response from .store import Store current: contextvars.ContextVar dict | None = contextvars.ContextVar "llmscope span", default=None def utc now - datetime: return datetime.now timezone.utc class Tracer: def init self, store: Store, prices: PriceBook, clock: Callable , datetime = utc now, capture prompts: bool = False : self.store, self.prices, self.clock = store, prices, clock self.capture prompts = capture prompts @contextmanager def span self, name: str, tags : parent = current.get me = {"span id": uuid.uuid4 .hex :16 , "trace id": parent "trace id" if parent else uuid.uuid4 .hex, "parent id": parent "span id" if parent else None} token = current.set me started, t0, status, err = self.clock , time.perf counter , "ok", None try: yield me except Exception as exc: status, err = "error", type exc . name raise finally: current.reset token self.store.insert { me, "name": name, "started at": started.isoformat , "duration ms": time.perf counter - t0 1000, "status": status, "error": err, "tags": json.dumps tags } def llm call self, provider: Provider, prompt: str, , tier: str = "standard", tags: dict | None = None, kw - Response: parent = current.get span id = uuid.uuid4 .hex :16 trace id = parent "trace id" if parent else uuid.uuid4 .hex started, t0 = self.clock , time.perf counter row = { "span id": span id, "trace id": trace id, "parent id": parent "span id" if parent else None, "name": f"llm.{provider.model}", "provider": provider.name, "model": provider.model, "started at": started.isoformat , "tier": tier, "prompt sha256": hashlib.sha256 prompt.encode .hexdigest , "prompt chars": len prompt , "tags": json.dumps { tags or {} , {"prompt": prompt} if self.capture prompts else {} } , } try: resp = provider.complete prompt, kw except Exception as exc: row.update duration ms= time.perf counter - t0 1000, status="error", error=type exc . name + ":" + str exc :40 self.store.insert row raise duration = resp.simulated ms if resp.simulated ms is not None else time.perf counter - t0 1000 cost = self.prices.cost provider.model, resp.usage, started.date , tier row.update duration ms=duration, ttft ms=resp.ttft ms, status="ok", input tokens=resp.usage.input tokens, cached input tokens=resp.usage.cached input tokens, output tokens=resp.usage.output tokens, cost micro usd=int cost 1 000 000 .to integral value self.store.insert row return resp The 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. Step 8: Report Latency Percentiles, Cache Hits and Cost Averages 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. llmscope/report.py python from future import annotations import argparse import math from datetime import datetime, timedelta, timezone from .store import Store def percentile values: list float , p: float - float: if not values: return 0.0 ordered = sorted values rank = max 1, math.ceil p / 100 len ordered return ordered rank - 1 def by model store: Store, since iso: str - list dict : rows = store.query "SELECT model, status, duration ms, input tokens, cached input tokens, output tokens, cost micro usd " "FROM spans WHERE model IS NOT NULL AND started at = ?", since iso, groups: dict str, list = {} for r in rows: groups.setdefault r "model" , .append r out = for model, rs in sorted groups.items : ok = r for r in rs if r "status" == "ok" fresh = sum r "input tokens" for r in ok cached = sum r "cached input tokens" for r in ok lat = r "duration ms" for r in ok out.append { "model": model, "calls": len rs , "errors": len rs - len ok , "p50 ms": percentile lat, 50 , "p95 ms": percentile lat, 95 , "p99 ms": percentile lat, 99 , "input tokens": fresh, "cached tokens": cached, "output tokens": sum r "output tokens" for r in ok , "cache hit": cached / fresh + cached if fresh + cached else 0.0, "cost usd": sum r "cost micro usd" for r in ok / 1 000 000, } return out def daily cost store: Store, since iso: str - list: return store.query "SELECT substr started at,1,10 AS day, model, COUNT AS calls, " "SUM cost micro usd /1000000.0 AS cost usd FROM spans " "WHERE model IS NOT NULL AND status='ok' AND started at = ? GROUP BY day, model ORDER BY day, model", since iso, def render rows: list dict - str: head = f"{'model':<18}{'calls': 6}{'err': 5}{'p50 ms': 9}{'p95 ms': 9}{'p99 ms': 9}{'cache%': 8}{'cost USD': 11}{'$/call': 9}" lines = head, "-" len head for r in rows: per call = r "cost usd" / max 1, r "calls" - r "errors" lines.append f"{r 'model' :<18}{r 'calls' : 6}{r 'errors' : 5}{r 'p50 ms' : 9.0f}{r 'p95 ms' : 9.0f}" f"{r 'p99 ms' : 9.0f}{r 'cache hit' 100: 7.1f}%{r 'cost usd' : 11.2f}{per call: 9.4f}" return "\n".join lines def main - None: ap = argparse.ArgumentParser ap.add argument "--db", default="llmscope.db" ap.add argument "--days", type=int, default=7 ap.add argument "--since", help="ISO date, overrides --days" ap.add argument "--daily", action="store true" a = ap.parse args since = a.since or datetime.now timezone.utc - timedelta days=a.days .date .isoformat store = Store a.db print render by model store, since if a.daily: print for r in daily cost store, since : print f"{r 'day' } {r 'model' :<18}{r 'calls' : 4} calls ${r 'cost usd' : 6.2f} ${r 'cost usd' /r 'calls' :.4f}/call" if name == " main ": main Cost 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. Read 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. Step 9: Alert on Budget, Latency, Cache Hits and the December 1 Price Change Reports 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. The 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. config/alerts.json { "daily budget usd": 25.0, "p95 ms": 9000, "error rate": 0.03, "min cache hit ratio": 0.20, "min calls for ratio checks": 20, "price change warn days": 7 } llmscope/alerts.py python from future import annotations import argparse import json import sys from datetime import date from pathlib import Path from .pricing import PriceBook from .report import by model from .store import Store def check store: Store, prices: PriceBook, rules: dict, today: date - list str : alerts: list str = day = today.isoformat spend = store.query "SELECT SUM cost micro usd /1000000.0 AS usd FROM spans " "WHERE model IS NOT NULL AND status='ok' AND substr started at,1,10 =?", day, 0 "usd" or 0.0 if spend rules "daily budget usd" : alerts.append f"BUDGET ${spend:.2f} spent on {day}, limit ${rules 'daily budget usd' :.2f}" for m in by model store, day : if m "calls" < rules "min calls for ratio checks" : continue if m "p95 ms" rules "p95 ms" : alerts.append f"LATENCY {m 'model' } p95 {m 'p95 ms' :.0f} ms, limit {rules 'p95 ms' } ms" if m "errors" / m "calls" rules "error rate" : alerts.append f"ERRORS {m 'model' } error rate {m 'errors' /m 'calls' :.1%}, limit {rules 'error rate' :.1%}" if m "cache hit" < rules "min cache hit ratio" : alerts.append f"CACHE {m 'model' } cache hit {m 'cache hit' :.1%}, floor {rules 'min cache hit ratio' :.1%}" for c in prices.upcoming changes today, rules "price change warn days" : alerts.append f"PRICE {c 'model' } changes on {c 'effective from' }: input ${c 'input before' :.2f} - " f"${c 'input after' :.2f}, output ${c 'output before' :.2f} - ${c 'output after' :.2f} per 1M tokens" return alerts def main - None: ap = argparse.ArgumentParser ap.add argument "--db", default="llmscope.db" ap.add argument "--prices", default="config/prices.json" ap.add argument "--rules", default="config/alerts.json" ap.add argument "--today", default=date.today .isoformat a = ap.parse args rules = json.loads Path a.rules .read text found = check Store a.db , PriceBook.load a.prices , rules, date.fromisoformat a.today for line in found: print line print f"{len found } alert s " sys.exit 1 if found else 0 if name == " main ": main Teams 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. To 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: 15 7 cd /srv/llmscope && .venv/bin/python -m llmscope.alerts alerts.log 2 &1 || curl -fsS -X POST "$WEBHOOK URL" --data-binary @alerts.log Set 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. Steps 10 to 12: Tests, a Demo Run and an OpenTelemetry Export 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. tests/test pricing.py python import unittest from datetime import date from decimal import Decimal from llmscope.pricing import PriceBook, Usage BOOK = PriceBook.load "config/prices.json" class PricingTests unittest.TestCase : def test fable standard self : 1,000 fresh in, 500 cached in, 2,000 out at $8 / $0.20 / $40 per 1M c = BOOK.cost "claude-fable-5-2", Usage 1000, 500, 2000 , date 2026, 11, 25 self.assertEqual c, Decimal "0.0881" def test carbon price changes on december first self : u = Usage 1 000 000, 0, 1 000 000 self.assertEqual BOOK.cost "gemini-4-carbon", u, date 2026, 11, 30 , Decimal "12.00" self.assertEqual BOOK.cost "gemini-4-carbon", u, date 2026, 12, 1 , Decimal "24.00" def test long context multiplier applies to whole request self : small = BOOK.cost "gpt-6.2-astra", Usage 100 000, 0, 1000 , date 2026, 11, 25 big = BOOK.cost "gpt-6.2-astra", Usage 300 000, 0, 1000 , date 2026, 11, 25 self.assertEqual small, Decimal "0.84" self.assertEqual big, Decimal "4.86" def test batch tier halves cost self : u = Usage 1000, 0, 1000 std = BOOK.cost "claude-fable-5-2", u, date 2026, 11, 25 self.assertEqual BOOK.cost "claude-fable-5-2", u, date 2026, 11, 25 , "batch" , std / 2 def test unknown tier fails loudly self : with self.assertRaises KeyError : BOOK.cost "gemini-4-carbon", Usage 1, 0, 1 , date 2026, 11, 25 , "batch" def test price before launch fails loudly self : with self.assertRaises KeyError : BOOK.cost "gpt-6.2-astra", Usage 1, 0, 1 , date 2026, 11, 1 def test negative usage is rejected self : with self.assertRaises ValueError : Usage -5, 100, 10 def test upcoming change found self : found = BOOK.upcoming changes date 2026, 11, 25 , 7 self.assertEqual f "model" for f in found , "gemini-4-carbon" if name == " main ": unittest.main 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. scripts/demo.py """Fill llmscope.db with simulated traffic across a price change. No API keys needed.""" from future import annotations import argparse import random from datetime import datetime, timedelta, timezone from llmscope.pricing import PriceBook from llmscope.providers import FakeProvider, ProviderError from llmscope.store import Store from llmscope.tracer import Tracer FLEET = "gpt-6.2-astra", dict ms per token=7, base ms=700, cache rate=0.55 , "openai" , "claude-fable-5-2", dict ms per token=8, base ms=900, cache rate=0.60 , "anthropic" , "gemini-4-carbon", dict ms per token=5, base ms=650, cache rate=0.35 , "google" , def main - None: ap = argparse.ArgumentParser ap.add argument "--db", default="llmscope.db" ap.add argument "--start", default="2026-11-27" ap.add argument "--days", type=int, default=6 ap.add argument "--calls-per-day", type=int, default=60 a = ap.parse args store = Store a.db prices = PriceBook.load "config/prices.json" start = datetime.fromisoformat a.start .replace tzinfo=timezone.utc clock value = start tracer = Tracer store, prices, clock=lambda: clock value 0 providers = FakeProvider m, name=n, kw , m for m, kw, n in FLEET rng = random.Random 11 for day in range a.days : for i in range a.calls per day : clock value 0 = start + timedelta days=day, seconds=i 1200 provider, = rng.choice providers try: with tracer.span "support.answer", route="faq" : tracer.llm call provider, "Summarize the refund policy for order " + str i 40 except ProviderError: pass print f"wrote {store.query 'SELECT COUNT AS n FROM spans' 0 'n' } spans to {a.db}" if name == " main ": main 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. llmscope/otel export.py """Optional: replay stored spans through OpenTelemetry. Needs: pip install opentelemetry-sdk""" from future import annotations import argparse from datetime import datetime from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter from .store import Store def export store: Store, since iso: str, limit: int = 1000, exporter=None - int: provider = TracerProvider provider.add span processor BatchSpanProcessor exporter or ConsoleSpanExporter tracer = provider.get tracer "llmscope" rows = store.query "SELECT FROM spans WHERE model IS NOT NULL AND status='ok' AND started at = ? " "ORDER BY started at LIMIT ?", since iso, limit for r in rows: start ns = int datetime.fromisoformat r "started at" .timestamp 1e9 attrs = { "gen ai.provider.name": r "provider" , "gen ai.request.model": r "model" , "gen ai.usage.input tokens": r "input tokens" + r "cached input tokens" , "gen ai.usage.output tokens": r "output tokens" , "llmscope.cached input tokens": r "cached input tokens" , "llmscope.cost usd": r "cost micro usd" / 1 000 000, "llmscope.tier": r "tier" , } span = tracer.start span r "name" , start time=start ns, attributes=attrs span.end end time=start ns + int r "duration ms" 1e6 provider.shutdown return len rows if name == " main ": ap = argparse.ArgumentParser ap.add argument "--db", default="llmscope.db" ap.add argument "--since", required=True ap.add argument "--limit", type=int, default=3 a = ap.parse args print f"exported {export Store a.db , a.since, a.limit } spans" Run everything from the project root so the llmscope package resolves: python3 -m unittest -v python3 -m scripts.demo python3 -m llmscope.report --since 2026-11-27 --daily python3 -m llmscope.alerts --today 2026-11-28 pip install opentelemetry-sdk python3 -m llmscope.otel export --since 2026-12-01 --limit 1 Sample Output and How to Read It The 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. Ran 8 tests in 0.001s OK wrote 720 spans to llmscope.db The report for the whole window shows one line per model: model calls err p50 ms p95 ms p99 ms cache% cost USD $/call ------------------------------------------------------------------------------------ claude-fable-5-2 114 0 3656 7339 14002 60.0% 2.90 0.0254 gemini-4-carbon 110 0 2467 5316 6048 33.5% 1.17 0.0106 gpt-6.2-astra 136 1 3285 7378 10004 56.0% 3.68 0.0273 The 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: bash 2026-11-27 gemini-4-carbon 24 calls $ 0.21 $0.0087/call 2026-11-28 gemini-4-carbon 13 calls $ 0.10 $0.0074/call 2026-11-29 gemini-4-carbon 18 calls $ 0.13 $0.0072/call 2026-11-30 gemini-4-carbon 20 calls $ 0.16 $0.0079/call 2026-12-01 gemini-4-carbon 20 calls $ 0.31 $0.0154/call 2026-12-02 gemini-4-carbon 15 calls $ 0.27 $0.0177/call The 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: php PRICE gemini-4-carbon changes on 2026-12-01: input $2.00 - $4.00, output $10.00 - $20.00 per 1M tokens 1 alert s A 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: "attributes": { "gen ai.provider.name": "openai", "gen ai.request.model": "gpt-6.2-astra", "gen ai.usage.input tokens": 3019, "gen ai.usage.output tokens": 141, "llmscope.cached input tokens": 2717, "llmscope.cost usd": 0.009143, "llmscope.tier": "standard" } Limits of the Simulated Data Treat 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. Common Pitfalls That Corrupt LLM Cost Numbers 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. 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. 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. 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. 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. 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. 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. 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. If 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. Troubleshooting: 10 Errors and Their Fixes - 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. - 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. - 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. - 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. - 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. - 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. - 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. - 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. - 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. - 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. To 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. python import json, os from llmscope.providers import post json data = post json "https://api.anthropic.com/v1/messages", {"x-api-key": os.environ "ANTHROPIC API KEY" , "anthropic-version": "2023-06-01"}, {"model": "claude-fable-5-2", "max tokens": 64, "messages": {"role": "user", "content": "Say hi"} }, print json.dumps data "usage" , indent=2 Advanced Tips for Production LLM Observability 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. {"model": "gpt-6.2-astra", "effective from": "2027-03-01", "input": 8.00, "cached input": 0.40, "output": 40.00, "tiers": {"standard": 1, "batch": 0.5, "fast": 2, "ultrafast": 6}} 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. 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. 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. 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. 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/ . 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. FAQ: LLM Observability and Cost Tracking What is LLM observability? It 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. Do I need OpenTelemetry to do this? No. 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. How do I track LLM costs when prompt caching is on? Record 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. Will the Carbon price change corrupt my history? No. 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. Is it safe to store prompts in the trace database? Only 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. Which latency percentile should trigger an alert? Start 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. Can I run this next to a gateway or proxy? Yes. 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.