# LLM Observability in Python: 12 Steps, 80 Min

> Source: <https://shattered.io/llm-observability-python-tokens-cost-latency-12-steps-2026/>
> Published: 2026-11-25 10:30:25+00:00

**Recommendation:** 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.
More in the playbook "Running AI in production": <https://wpnews.pro/playbooks/production-ops>

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.
