Learn to operate an AI feature: tracing and cost¶
A short guide to read alongside RnR phases 3 and 5. The README has setup and the labs; learn-evals.md comes before this one.
1. What operating an AI feature means, and why it needs its own tools¶
Once a feature runs on real traffic, two questions come every week: "why did this one happen?" and "what does it cost?". The first is answered by a trace: one record per unit of work (here, a review) made of spans, one per step, each with timing, status and the facts that matter (prompt version, tokens, decision). The second by a cost meter: tokens in, tokens out, calls and GPU time, priced by a rate card.
The problem they solve: an AI feature is a chain of steps (API, queue, rules, model, checks, policy), and the price of one request can move 10x with a prompt edit or one flag (think=True). Logs give you scattered lines, metrics give you averages, the monthly bill gives you one number. None of them says what happened to this review, or which feature and prompt version spent the money.
| Question | Without | With traces and a meter |
|---|---|---|
| Why was RV00064 held? | grep two processes' logs | open its trace: policy.needs_human held=True |
| Where do the 2 seconds go? | one average per endpoint | per step: model 99%, rules under 1 ms |
| Should we turn on reasoning? | a debate | +₹1 per 1,000 reviews on a small API tier, hard cases 85% → 100% |
| API or our own GPU? | a guess | the volume where the two lines cross |
Analogy: a courier's tracking page and an electricity meter per appliance. The tracking page shows the parcel sat at one hub for two days; the meter shows the geyser is ₹2,500 of a ₹4,000 bill. You don't buy LED bulbs to fix a geyser problem.
When you need them: from the first feature with more than one step or a background job, and before every "bigger model / reasoning on / self-host?" discussion. With agents, the trace is how you see what the agent did.
2. The mental model¶
Four ideas carry the two phases.
- The trace id travels with the work. The API puts a
traceparentin the job payload; the worker continues the same trace, even hours later when a moderator decides. - Instrument once, in OpenTelemetry's shape. Spans are written in one place; SQLite today, Phoenix or your APM tomorrow, is just another sink.
- Meter at the one door. Every call goes through
ai/llm.pyand lands inllm_calls;ai/cost.pyonly multiplies byai/rate_card.json. Find the big meter first: moderation pays ~89% of its price for input, extraction more for output. - Cheaper ships only with an eval. Thinking, caching, a fallback model: each can change answers, so the price sits in the same table as "honest rejected".
Analogy: a restaurant kitchen. Ingredients (tokens), plates (calls) and chef hours (GPU time) are separate costs, and every dish has a ticket that follows it from order to table (the trace). A cheaper ingredient is a saving only if the dish still passes the tasting.
3. The labs in two stages¶
Stage 1: see every step (06)¶
| Script | What you see | Key takeaway |
|---|---|---|
06_traces.py |
Six reviews as waterfalls: rules-only injection (no model span), held abuse, masked PII, a retry as two attempts in one trace, a moderator's later decision in the same trace; p50/p95 per step | The model is nearly all the time for one review; in a batch, later reviews wait in the queue longer than the model runs |
Then run the worker (python -m worker.run --backlog 10 --once), open Ops → Traces, and follow the "trace" link on any decided review.
Stage 2: price it, then pull the levers (09–11)¶
| Script | What you see | Key takeaway |
|---|---|---|
09_cost_meter.py |
Every call priced two ways (API tiers, self-host GPU time), ₹ per 1,000 reviews, build vs buy at your volume, model spend vs mistake spend (no model) | ~₹14.5 per 1,000 reviews on a small API tier; the mistakes and human time cost ~₹300. Optimise the bigger number first |
10_thinking_and_cascade.py |
Think off vs on on the hard cases (and --golden), then escalation: think only when the quick answer would be held or says ABUSIVE |
Thinking fixed 3 hard cases at ~10x the output but broke an easy review. Escalation kept the fix for 6% second passes |
11_gateway.py |
The layer in front of the model: a response cache (pass 2 of the same reviews), a daily token budget stopping a feature, a rate limit, retries with backoff, a fallback model; --litellm for the same with LiteLLM |
Cache only temperature-0 calls keyed by prompt version (pass 2 cost 0 tokens). Limits per feature; retry only what can succeed next time; a fallback model is a release that needs its own eval |
4. Decisions your team will face¶
| Decision | Start with | Change when |
|---|---|---|
| Trace store | Hand-rolled spans in your DB, OTel-shaped | More than one service, or people need search and dashboards: export to Phoenix, Langfuse or your APM |
| Prompts in spans | On, masked text only (RNR_TRACE_CONTENT=1) |
Regulated data, or the trace store has wider access than the product DB: sizes and hashes only |
| Sampling | Keep every trace | Volume grows: keep errors, holds and slow traces, sample the rest |
| API or self-host | A small hosted model through one door, metered | The GPU line crosses the API line (lab 09), or data must stay in your network |
| Reasoning | Off by default, escalate when unsure | The eval shows a case type only reasoning fixes: add it to the escalation trigger |
| Response cache | On for temperature-0 calls, keyed by prompt version | Answers depend on context outside the request (time, user, stock) |
| Budgets | A daily token budget and rate limit per feature, alert at 80% | Many teams share one model: a gateway with keys per team |
5. What the labs don't cover¶
- Metrics and alerts: p95 and error rate as time series with alerts. The Ops tables are a snapshot, not a monitor.
- A real tracing backend: sending the same spans to Arize Phoenix through OpenTelemetry (see Going deeper and FAQ-more.md).
- Batching and parallel requests: several items per prompt cut input tokens, but can raise GPU time and cause cross-talk (FAQ-more.md).
- Real provider bills: the rate card is an assumption; reconcile it with the invoice monthly.
- GPU serving (vLLM, continuous batching, quantisation) and cost per customer.
Check yourself¶
Answer each in a sentence or two, without looking. If one is hard, reread the section in brackets.
- Why does the API put the trace id in the job payload, instead of the worker starting its own trace? (section 2, lab 06)
- For one review, the model is nearly all the time. Why is that not the whole story for a batch of reviews? (section 3, lab 06)
- A manager asks you to halve the model bill. Lab 09 also prices mistakes and human time. Where would you look first, and why? (section 3, lab 09)
- Why does the gateway cache only temperature-0 calls, and why is the cache keyed by prompt version? (section 3, lab 11)
- A teammate wants to add a cheaper fallback model and ship it today, since "it only runs during outages". Would you agree? Why? (section 2, lab 11)
Same pattern, other industries¶
| Industry | Use case | What changes |
|---|---|---|
| Banking | KYC document extraction | Spans never hold raw PAN or account numbers; long documents make input tokens dominate |
| Customer support | RAG chatbot | One trace per turn with the chunk ids used; history grows every turn, so cost per resolved ticket |
| Healthcare | Discharge summary drafting | Content capture off; self-host for data residency even if an API is cheaper |
| Logistics | Dispatch agent calling route and ETA tools | Tool spans show loops and wasted calls; spiky volume makes rate limits matter more than price |
| B2C e-commerce | Search query understanding | Millions of short, repeated queries: sample traces heavily; the cache hit rate decides the bill |
Going deeper: advanced topics¶
| Topic | What it solves | Search for |
|---|---|---|
| OpenTelemetry for LLMs | Vendor-neutral span names; tools that understand your spans | "opentelemetry gen_ai semantic conventions", "openinference", "arize phoenix" |
| Auto-instrumentation | Spans for SDK and framework calls without code changes | "openllmetry", "openinference instrumentation" |
| Tail-based sampling | Keep the interesting traces, decided after the trace ends | "otel collector tail sampling" |
| Model routing | Send each request to the cheapest model that can handle it | "llm router", "routellm" |
| Prompt caching and batch APIs | Discounts on repeated prefixes and offline jobs | "prompt caching", "llm batch api" |
| Serving efficiency | More requests per GPU | "vllm", "continuous batching", "quantization" |
Try it¶
Make the model slow for one review and find it from the trace alone: in obs/samples.py, wrap fake_chat so the "blunt complaint" sample sleeps 3 seconds, run python 06_traces.py --fake, and see how the p95 for llm.generate moved while the p50 did not. Then run python 09_cost_meter.py --per-day 20000: at 10x the volume, does self-hosting win?
Then practise: the exercises in PRACTICE.md: a seller scorecard by month, a regression gate for prompt changes, seller reply drafts with output guardrails, then build a "why did this drop?" insights agent yourself.
Next: the WhatsApp ordering agent, or back to SYSTEM-DESIGN.md to size a feature of your own.