AS·177
AI Observability
Seeing inside AI systems in production: why AI needs more than classic metrics, logs and traces, the four layers the roadmap lists (model: model and prompt versions, tokens, latency, errors; retrieval: queries, documents, scores, reranking, context; agents: trajectories, tools, arguments, results, retries, state; infrastructure: CPU, GPU, VRAM, queue depth, throughput), OpenTelemetry tracing with the GenAI semantic conventions implemented in Python, prompt and model version management, token and cost accounting per feature and tenant, quality signals and online evaluation, drift detection (population stability, embedding drift), GPU and inference-server metrics, dashboards, SLOs and alerts, privacy and retention for prompts and outputs, debugging workflows from trace to fix, and the tooling landscape.
Start here: seeing inside an AI request
When a user says "the assistant gave me a wrong answer and took ages", you need to know what happened inside that one request: which documents were retrieved, what prompt the model actually saw, how many tokens it used, how long each step took, and what it cost. Observability for AI is the practice of recording that, for every request, in a form you can search and aggregate.
Traces and spans
A trace is the story of one request; each step in it is a span with a start time, an end time and attributes:
chat_request 136 ms user=cust-10
├─ retrieve 0.2 ms top_score=1.65, k=2
└─ chat tiny-gpt 136 ms input_tokens=171, output_tokens=24, ttft=4.6 ms
OpenTelemetry is the open standard for producing traces, and its GenAI semantic conventions name the attributes every model call should carry (gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens…), so any tracing tool can understand them.
What the lab's traces revealed
The lab traced 120 requests to a small question-answering pipeline. Without looking at any code, the traces showed:
- Time went into generation: retrieval took 0.2 ms, generation 136 ms (median), and duration tracked output tokens almost perfectly (correlation 0.94).
- A silent bug: every one of the 120 prompts was longer than the 100 tokens the generator kept, so the top of the retrieved context was being cut off.
- Wasted spend: 41 requests were flagged as low-confidence ("should say I don't know"), yet each still paid for a full generation.
- A privacy leak: 16 span attributes contained customers' email addresses or phone numbers copied from their questions, until a redaction step scrubbed them before recording (0 after).
How deep to go in AI observability
Volume 17 defines six mastery levels; for AI observability they look like this:
| Level | You can… |
|---|---|
| L1 | explain traces, spans, token metrics and why prompts need logging with care |
| L2 | instrument an AI app with OpenTelemetry GenAI spans and view traces |
| L3 | design attributes, metrics, sampling and redaction for AI workloads |
| L4 | debug quality, latency and cost problems from traces and evaluations of logged data |
| L5 | design an observability platform linking traces, evals, feedback and cost |
| L6 | run AI observability across teams with governance, retention and access control |
Why AI observability is different
Classic observability (chapters 114–116) answers "is it up, is it fast, where are the errors?". AI systems add questions those signals can't answer:
- The request succeeded (HTTP 200) but the answer was wrong, ungrounded or unsafe.
- Latency doubled because the agent took nine tool steps instead of three, or retrieval returned huge chunks.
- Costs tripled after a prompt change added 4,000 tokens of instructions.
- Quality drifted because users started asking about a new product the index doesn't cover.
- A model version upgrade by the provider changed behaviour.
So AI observability records the content and structure of each interaction (prompts, retrieved context, tool calls, outputs, versions, token counts) linked as traces, plus quality signals, alongside the usual infrastructure telemetry.
Model layer
Track for every model call:
| Signal | Why |
|---|---|
| Model name and version (exact snapshot id, provider, region) | Behaviour changes with versions; correlate regressions |
| Prompt template id and version | Know which prompt produced which output; roll back |
| Parameters (temperature, max tokens, tools offered, structured-output schema version) | Reproduce behaviour |
| Input / output / cached / reasoning tokens | Cost, context pressure, cache effectiveness |
| Latency: TTFT, total, tokens/s | User experience; SLOs (chapter 166) |
| Finish reason (end_turn, max_tokens, tool_use, refusal, content_filter) | Truncation and refusal rates |
| Errors: rate limits (429), timeouts, provider 5xx, validation failures, retries | Reliability, fallbacks |
| Inputs and outputs (subject to privacy policy) | Debugging and evaluation |
Manage prompts as versioned artefacts (in a registry or in code with version ids), not ad-hoc strings, so traces can reference them and you can diff behaviour between versions.
Retrieval layer
For RAG (chapters 159–162):
- The query as issued (after rewriting), and any filters (tenant, date, ACL).
- Retrieved documents: ids, sources, versions, scores per retriever (dense, BM25), fused ranks.
- Reranking: scores before and after; which chunks were cut.
- Final context: which chunks went into the prompt, total context tokens, truncation.
- Empty or low-score retrievals: a leading indicator of corpus gaps.
With these, a wrong answer can be traced to "the right document ranked 14th" versus "the right document was never indexed".
Agent layer
For agents (chapters 168–171):
- The trajectory: ordered steps with the model's decision, tool name, arguments, results (or summaries), errors, retries, and durations.
- State transitions and checkpoints; human approvals (who, when, decision).
- Budgets consumed: steps, tokens, time, cost; reasons for stopping.
- Anomalies: loops, repeated failing calls, denied tool calls (policy, chapter 176), unusually long runs.
Infrastructure layer
For self-hosted models and AI services:
| Metric | Source | Use |
|---|---|---|
| GPU utilisation, SM activity, memory (VRAM) used, temperature, power | NVIDIA DCGM exporter, nvidia-smi |
Capacity, throttling, failing hardware |
| KV-cache utilisation | Inference server metrics (e.g. vLLM's GPU cache usage) | Concurrency headroom (chapter 166) |
| Queue depth / waiting requests | Server metrics, gateway | Autoscaling signal; TTFT predictor |
| Throughput (tokens/s, requests/s), batch size | Server metrics | Efficiency |
| CPU, memory, network | Node exporters | Tokenisation, pre/post-processing, data loaders |
| Provider quotas and rate-limit headroom | API responses, gateways | Avoid 429 storms |
OpenTelemetry and the GenAI conventions
OpenTelemetry (chapter 115) is the standard for traces, metrics and logs; its GenAI semantic conventions define attribute names for AI operations so tools interoperate: for example gen_ai.operation.name (chat, embeddings, execute_tool), gen_ai.provider.name, gen_ai.request.model, gen_ai.response.model, gen_ai.request.temperature, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, gen_ai.response.finish_reasons, gen_ai.tool.name, plus conventions for agent spans and (opt-in) message content capture. The conventions are still marked as in development, so names can change; instrumentation libraries (OpenLLMetry, OpenInference, provider and framework integrations) emit them automatically.
import time, json, hashlib
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
class MemoryExporter(SpanExporter): # in production: OTLP exporter to your backend
def __init__(self): self.spans = []
def export(self, spans): self.spans.extend(spans); return SpanExportResult.SUCCESS
exporter = MemoryExporter()
provider = TracerProvider(); provider.add_span_processor(SimpleSpanProcessor(exporter))
trace.set_tracer_provider(provider)
tracer = trace.get_tracer("support-assistant", "1.4.0")
PRICES = {"model-x-2026-09": (3.0, 15.0)} # USD per million input/output tokens (illustrative)
def traced_llm_call(messages, model="model-x-2026-09", prompt_version="answer-v14", temperature=0.2):
with tracer.start_as_current_span(f"chat {model}") as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.provider.name", "example-provider")
span.set_attribute("gen_ai.request.model", model)
span.set_attribute("gen_ai.request.temperature", temperature)
span.set_attribute("app.prompt.version", prompt_version)
t0 = time.monotonic()
reply = {"text": "Order A17 has shipped.", "input_tokens": 6200, "output_tokens": 120,
"finish_reason": "end_turn"} # stand-in for the real API call
span.set_attribute("gen_ai.usage.input_tokens", reply["input_tokens"])
span.set_attribute("gen_ai.usage.output_tokens", reply["output_tokens"])
span.set_attribute("gen_ai.response.finish_reasons", [reply["finish_reason"]])
pin, pout = PRICES[model]
span.set_attribute("app.cost_usd", (reply["input_tokens"] * pin + reply["output_tokens"] * pout) / 1e6)
span.set_attribute("app.latency_ms", round(1000 * (time.monotonic() - t0)))
return reply
def traced_retrieval(query, tenant):
with tracer.start_as_current_span("retrieve") as span:
hits = [("handbook#41", 0.82), ("handbook#7", 0.64), ("faq#3", 0.51)]
span.set_attribute("app.retrieval.query_hash", hashlib.sha256(query.encode()).hexdigest()[:12])
span.set_attribute("app.tenant", tenant)
span.set_attribute("app.retrieval.doc_ids", [d for d, _ in hits])
span.set_attribute("app.retrieval.scores", [s for _, s in hits])
return hits
def traced_tool(name, args):
with tracer.start_as_current_span(f"execute_tool {name}") as span:
span.set_attribute("gen_ai.operation.name", "execute_tool")
span.set_attribute("gen_ai.tool.name", name)
span.set_attribute("app.tool.args", json.dumps(args))
return {"status": "shipped"}
with tracer.start_as_current_span("POST /ask") as root:
root.set_attribute("app.feature", "order-status")
traced_retrieval("where is order A17", tenant="acme")
traced_tool("get_order", {"order_id": "A17"})
traced_llm_call([{"role": "user", "content": "Where is A17?"}])
[(s.name, s.parent.span_id == exporter.spans[-1].context.span_id if s.parent else None) for s in exporter.spans]
# [('retrieve', True), ('execute_tool get_order', True), ('chat model-x-2026-09', True), ('POST /ask', None)]
# every child span is parented to the request span, so the backend shows one waterfall
Cost accounting
Attribute every token and tool cost to feature, tenant, user and model:
- Dashboards of cost per request, per successful task, per tenant; trends after releases.
- Budgets and alerts per tenant/feature; hard caps for runaway agents (chapter 176's unbounded consumption).
- Cache hit rates (prompt caching, semantic caching) and their savings.
- Unit economics: cost per resolved ticket vs human handling; cost of routing choices (chapter 158).
from collections import defaultdict
def cost_report(spans):
by = defaultdict(lambda: {"calls": 0, "in": 0, "out": 0, "usd": 0.0})
for s in spans:
a = s.attributes
if a.get("gen_ai.operation.name") == "chat":
k = a.get("gen_ai.request.model")
by[k]["calls"] += 1; by[k]["in"] += a["gen_ai.usage.input_tokens"]
by[k]["out"] += a["gen_ai.usage.output_tokens"]; by[k]["usd"] += a["app.cost_usd"]
return dict(by)
cost_report(exporter.spans) # {'model-x-2026-09': {'calls': 1, 'in': 6200, 'out': 120, 'usd': 0.0204}}
Quality signals
Attach quality to traces so you can filter "show me bad answers about refunds last week":
- Deterministic checks: schema validity, citation validity, refusal detection, PII in output, length.
- Sampled online evaluations: LLM-judge faithfulness, relevance, policy compliance (chapter 175), recorded as span attributes or linked scores.
- User feedback: thumbs up/down, edits to drafts, escalations, follow-up rephrasing.
- Business outcomes joined later (ticket reopened, conversion).
Drift detection
Inputs and behaviour change over time:
- Input drift: new topics, languages, longer prompts, different user populations. Track distributions of input length, language, intent categories, and embedding drift (distance between recent query embeddings and a reference window; cluster to find new topics).
- Retrieval drift: falling top scores, more empty results.
- Output drift: length, refusal rate, tool-call rates, sentiment, judge scores.
- Model drift: provider-side changes under a floating alias; pin versions and monitor anyway.
Population stability index (PSI) compares a feature's distribution between a reference and a current window; values above ≈ 0.2 commonly signal meaningful shift. For classic ML models (chapter 178), also monitor prediction drift and, when labels arrive, performance drift.
import numpy as np
def psi(reference, current, bins=10):
edges = np.quantile(reference, np.linspace(0, 1, bins + 1)); edges[0], edges[-1] = -np.inf, np.inf
r = np.histogram(reference, edges)[0] / len(reference); c = np.histogram(current, edges)[0] / len(current)
r, c = np.clip(r, 1e-6, None), np.clip(c, 1e-6, None)
return float(np.sum((c - r) * np.log(c / r)))
rng = np.random.default_rng(0)
ref = rng.lognormal(6.0, 0.5, 5000) # prompt lengths last month (tokens)
same = rng.lognormal(6.0, 0.5, 5000)
longer = rng.lognormal(6.4, 0.6, 5000) # a new feature sends longer prompts
round(psi(ref, same), 3), round(psi(ref, longer), 3) # ≈ 0.005 vs ≈ 0.52: the longer prompts are a real shift
def embedding_drift(ref_vecs, cur_vecs):
"""Cosine distance between mean embeddings of two windows (simple, cheap signal)."""
a, b = ref_vecs.mean(0), cur_vecs.mean(0)
return 1 - float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
Dashboards, SLOs and alerts
A useful AI service dashboard:
- Traffic and reliability: requests, error rate by type (provider, validation, tool), fallbacks taken.
- Latency: TTFT and end-to-end p50/p95/p99; per step (retrieval, model, tools).
- Cost: tokens and dollars per request, per feature, per tenant; cache hit rate.
- Quality: judge scores, validation failure rate, refusal and truncation rates, user feedback.
- Retrieval: empty-result rate, top-score distribution.
- Agents: steps per task, success rate, loop detections, denied tool calls, approvals pending.
- Infrastructure: GPU/KV-cache utilisation, queue depth, throughput.
SLOs (chapter 116) for AI: latency SLOs on TTFT; availability including fallbacks; quality SLOs such as "≥ 95% of sampled answers grounded" or "schema-valid outputs ≥ 99.5%". Alert on burn rates, sudden shifts after deploys or provider changes, cost anomalies, and safety signals (spikes in injection detections or denied external calls).
Privacy and retention
Prompts and outputs contain personal data, secrets and confidential business information:
- Minimise and redact before storage (PII detection, secret scanning); hash user identifiers.
- Access control on trace content (often stricter than on metrics); audit access.
- Retention limits and deletion workflows (honour user deletion requests in traces too).
- Content capture toggles: OpenTelemetry GenAI instrumentation keeps message content opt-in for this reason.
- Data residency: where your observability vendor stores data.
- Evaluation datasets drawn from traces need consent and anonymisation review.
Debugging workflow
- Start from a symptom (user report, failed eval, alert) and find the trace.
- Inspect retrieval: were the right documents retrieved and included?
- Inspect the prompt actually sent (rendered template, version) and the model response (finish reason, tokens).
- Inspect tool calls: arguments, results, errors, retries.
- Reproduce offline with the same versions and inputs; add the case to the regression suite (chapter 175).
- Fix (prompt, retrieval, tool, policy), verify against the suite, deploy, and watch the metric that caught it.
Tooling
| Category | Examples |
|---|---|
| Open standards and instrumentation | OpenTelemetry GenAI conventions, OpenLLMetry, OpenInference |
| LLM observability platforms | Langfuse, LangSmith, Arize Phoenix, Helicone, Braintrust, Weights & Biases Weave, Datadog LLM Observability, New Relic and Dynatrace AI monitoring, cloud-native options |
| Gateways (central logging, cost, limits) | LiteLLM, cloud AI gateways, API-management products |
| Inference and GPU metrics | vLLM/SGLang/TGI Prometheus endpoints, NVIDIA DCGM exporter, Kubernetes metrics |
| Classic ML monitoring | Evidently, WhyLabs, Arize, SageMaker Model Monitor, Vertex AI Model Monitoring |
Prefer tools that ingest OpenTelemetry so traces join the rest of your system's telemetry (chapter 115) instead of living in a silo.
Lab: tracing a small AI pipeline with OpenTelemetry
Setup. OpenTelemetry Python SDK 1.45.1 with an in-memory span exporter (no tracing backend is installed on the lab machine; an OTLP exporter to Jaeger, Tempo, Langfuse, Phoenix or a vendor would receive the same spans). The pipeline: BM25 retrieval over the five-paragraph tiffin FAQ from the Start Here chapter, then chapter 156's tiny GPT generating 24 tokens (64 for every 25th request) greedily. 120 requests from 40 simulated users; every 15th question includes an email address and phone number, as real users' messages do. Attributes follow the OpenTelemetry GenAI semantic conventions where they exist (gen_ai.operation.name, gen_ai.request.model, gen_ai.request.max_tokens, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens) and an app. prefix otherwise. (The prompt is recorded as an attribute here for simplicity; the conventions treat message content as opt-in, captured only when explicitly enabled, for the privacy reasons Experiment 3 shows.)
Experiment 1: where the time goes
| Span | n | p50 | p95 | max |
|---|---|---|---|---|
chat_request (root) |
120 | 136.6 ms | 187.3 ms | 422.9 ms |
retrieve |
120 | 0.2 ms | 0.3 ms | 1.4 ms |
chat tiny-gpt |
120 | 136.2 ms | 186.9 ms | 422.4 ms |
The six slowest generations were the five 64-token requests (362–442 ms) and one 24-token outlier (207 ms). Across all requests, duration correlated 0.94 with output tokens and −0.03 with input tokens. To cut latency, cap and shorten outputs, or stream them; a faster retriever would save nothing.
Cost, from the token attributes alone: 16,139 input and 3,080 output tokens; at illustrative prices of $3 per million input and $15 per million output tokens, $0.095 for 120 requests, and the same attributes grouped by app.user_id gave per-user usage (top user: 1,162 tokens of 19,219).
Experiment 2: bugs the traces exposed
- Truncated context.
gen_ai.usage.input_tokenswas above 100 on 120 of 120 requests, but the generator keeps only the last 100 tokens to fit the model's 128-token window. Every prompt silently lost its beginning, which is where the top-ranked FAQ paragraph was. Alert when input tokens approach the context limit, and order prompts so truncation can't remove what matters. - Paying for refusals. 41 of 120 requests had a top retrieval score below 1.0 (
app.refused), the Start Here threshold for "I don't know", yet each still ran a full generation, because the check happened after the model call. One attribute made the waste visible and the fix obvious: check before generating.
Experiment 3: personal data in telemetry
| Configuration | Spans | Attributes containing an email or phone number |
|---|---|---|
| raw | 360 | 16 |
all attributes set through one put() helper that scrubs emails and 10-digit numbers |
360 | 0 |
Telemetry is a copy of your users' data, often kept longer and seen by more people than the data itself. The first attempt (a span processor that edited attributes after the span ended) failed: the SDK makes finished spans immutable, so redaction must happen when attributes are set, or in the collector before export. Regex scrubbing is a floor, not a ceiling: names, addresses and document contents need content policies, access controls and retention limits.
Experiment 4: sampling
Keeping the slowest 10%, every refused request and 10% of the rest retained 54 of 120 traces (45%), with every trace you'd want for debugging. At high volume the "rest" fraction can drop much further; metrics (counts, latency histograms, token sums) should be computed from all requests before sampling.
Try it yourself
- Export the spans over OTLP to a Jaeger all-in-one container or binary and find the slowest trace in its UI.
- Add a span event per retrieved document (ID and score) and query for answers whose top document was never cited.
- Emit a metric
gen_ai.client.token.usage(histogram) and graph tokens per minute by model. - Attach user feedback (thumbs up/down) to traces by trace ID and compute satisfaction by retrieval score bucket.
Revision sheet: AI observability
Key ideas
- Trace every AI request: retrieval, prompt assembly, model calls, tool calls, guardrails, post-processing, with parent–child spans.
- OpenTelemetry GenAI conventions: model, operation, token usage, finish reasons, request parameters; content capture opt-in.
- Metrics: latency (TTFT, TPOT, end-to-end), tokens, cost, error and refusal rates, cache hit rates, tool-call success, retrieval scores.
- Quality signals: online evals on sampled traces, user feedback, escalations; link traces to eval results.
- Privacy: redact at source or in the collector, minimise content capture, restrict access, set retention; telemetry is user data.
- Sampling: head vs tail; keep errors, slow and flagged traces; compute metrics before sampling.
- Tools: OpenTelemetry collectors and backends; LLM-specific platforms (Langfuse, Arize Phoenix, LangSmith, MLflow Tracing, vendor APM).
- Alerts on cost spikes, latency SLOs, context-limit proximity, refusal/error rates and drift in quality scores.
Numbers to remember
- Lab: generation 136 ms p50 vs retrieval 0.2 ms; duration correlated 0.94 with output tokens.
- Lab: 120/120 prompts exceeded the generator's 100-token window (silent truncation).
- Lab: 16 attributes leaked personal data before redaction, 0 after.
- Lab: tail sampling kept 54/120 traces.
Pitfalls
- Logging full prompts and outputs with no redaction or retention policy.
- Sampling before computing metrics.
- No alert on prompts near the context limit.
- Token and cost data not attributed to users, tenants or features.
- Traces that stop at the model call and miss tools and retrieval.
Glossary
- Span / trace: a timed operation / a tree of spans for one request.
- Semantic conventions: standard attribute names in OpenTelemetry.
- Tail sampling: deciding which traces to keep after they finish.
- Collector: a service that receives, processes and exports telemetry.
- Cost attribution: assigning token spend to users, tenants or features.