FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

AI Tracing

How correlated model retrieval tool and application spans expose system behavior.

Freshness: current•15 min read•Evaluation, Reliability, and Observability

Key Learning Outcomes

  • ✓Correlate application retrieval model and tool spans
  • ✓Choose safe useful trace attributes
  • ✓Diagnose quality latency and cost from one trace
Full Technical Reference Document

Mental model

A raw vendor request_id shows only one isolated LLM hop cleanly, hiding upstream query rewrites, ACL vector lookup latency, tool failures, retries, and post-generation guardrails. AI tracing (OpenTelemetry GenAI conventions) treats every user request as a unified distributed causal tree of linked parent/child spans—measuring timing, tokens, costs, error taxonomies, and exact immutable version identifiers (model, prompt, index, policy) cleanly end-to-end without leaking raw PII payloads into observability lakes.

Ingress HTTP root span (`trace_id`)
Auth & ACL query rewrite child span
Retriever HNSW/rerank span (`index_rev`)
GenAI LLM inference span (TTFT/tokens)
Tool RPC + post-check spans + eval link
Conceptual teaching model synthesized from:OpenTelemetry Generative AI Semantic ConventionsOpenTelemetry Traces specification

Learning outcomes

  • Propagate W3C Trace Context (trace_id, span_id, links) across synchronous web gateways, streaming SSE responses, async background queues, and parallel tool fan-outs cleanly.
  • Instrument required OpenTelemetry GenAI semantic attributes (gen_ai.system, gen_ai.request.model, token counts, prompt hash, index version, error class) enabling rapid root-cause isolation cleanly.
  • Enforce privacy-safe observability via payload hashing/redaction alongside tail-based / risk-based sampling (keeping 100% of errors, high-latency tails, and risky write turns cleanly).

Theory

Observability platforms combine three orthogonal telemetry primitives anchored identically onto one shared trace_id: metrics (low-cardinality counters/histograms for P95 alerts cleanly), structured logs (discrete security audit receipts), and distributed traces (exact causal critical-path waterfalls explaining why single requests failed or stalled cleanly!). Crucial attributes separate reproducible configuration metadata from sensitive customer payloads:

Telemetry Span LayerKey Attributes CapturedSensitive Payload HandlingDiagnostic Question Answered
Edge Ingress Root Spantenant_tier, route, total_duration_ms, outcome_statusNever inject user_id or prompt prose into metric labelsWhich endpoints blew latency budgets today?
Retrieval & Rerank Spanindex_version, rewritten_count, acl_filter_ms, top_k_chunk_ids[], rerank_modelStore chunk IDs & score histograms (never full restricted paragraphs)Did latency come from slow SQL ACLs or missed candidate IDs?
LLM Inference (gen_ai.*)gen_ai.request.model, gen_ai.response.model, prompt_sha, cached_tokens, ttft_ms, tpot_ms, finish_reasonStore sha256(prompt) + token counts cleanly; mask raw bodies unless opt-in debugDid vendor snapshot silently shift verbosity (+40% output) or drop cache hits?
Tool Execution & Policy Spantool_name, duration_ms, error_kind, approval_bound, policy_decisionScrub auth tokens/secrets BEFORE telemetry export cleanlyWhich flaky downstream API caused 3 agent retries?
python
from dataclasses import dataclass, field
import hashlib
import time
​
@dataclass
class OTelGenAISpan:
trace_id: str
span_name: str
start_ns: int = field(default_factory=time.time_ns)
attributes: dict[str, object] = field(default_factory=dict)
​
def record_inference_metadata(
self,
model_snapshot: str,
prompt_text: str,
prompt_version: str,
input_tokens: int,
cached_tokens: int,
output_tokens: int,
ttft_ms: float,
) -> None:
"""Capture full reproducibility & cache efficiency metadata cleanly without raw PII leaks."""
prompt_digest = hashlib.sha256(prompt_text.encode("utf-8")).hexdigest()[:16]
self.attributes.update(
{
"gen_ai.request.model": model_snapshot,
"fsai.prompt.version": prompt_version,
"fsai.prompt.sha256": prompt_digest,
"gen_ai.usage.input_tokens": input_tokens,
"gen_ai.usage.cache_read_tokens": cached_tokens,
"gen_ai.usage.output_tokens": output_tokens,
"gen_ai.server.time_to_first_token_ms": round(ttft_ms, 2),
}
)

Trade-offs

Full 100% trace retention with raw prompt payloads catches obscure domain hallucinations rapidly cleanly during initial prototyping, yet explodes observability vendor bills cleanly at production traffic volumes while duplicating PII privacy liability across logging backends. Switching production onto privacy-preserving digest attributes + tail/risk-based sampling (1–5% baseline healthy traffic, 100% retention on errors, timeouts, high latency, tool mutations, and user thumbs-down flags linked straight to eval suites cleanly) keeps costs bounded while surfacing nearly every real defect cleanly.

Failure modes and misconceptions

  • Logging Raw Complete User Prompts by Default: Forwarding raw financial, healthcare, or auth credentials straight into third-party tracing dashboards turns telemetry into an immediate compliance hazard.
  • High-Cardinality Metric Labels (trace_id or query inside Prometheus): Injecting unique user/query strings directly into metric time-series tags crashes monitoring TSDB RAM quickly; high-cardinality details belong strictly cleanly on spans/logs!
  • Confusing Provider x-request-id With System Traces: Only logging LLM vendor request IDs hides whether 3.8s latency happened inside broken query rewriting, Postgres lock contention, or external webhooks cleanly.
  • Spans Without Version Metadata: Recording timing numbers cleanly without pinning prompt_version, index_rev, and model_snapshot makes A/B regressions indistinguishable cleanly.

Decision scenario

A multi-stage RAG support service reports random 6-second completion stalls and intermittent broken citations across enterprise accounts, yet engineers currently log only vendor HTTP status codes and raw message dumps cleanly. Instrument end-to-end OpenTelemetry GenAI trace propagation cleanly across rewrite, index_version, candidate chunk IDs, cached_tokens, citation allowlists, and thumbs_down eval links using hashed payload digests and tail sampling cleanly.

Reflect before revealing the guide

Which span attributes let engineering teams pinpoint and reproduce an AI quality or latency regression cleanly without storing sensitive raw customer text inside observability traces?

Prerequisites & Related Concepts (2)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next