Observability and Tracing

Trace every query through retrieval and generation with Langfuse, LangSmith or OpenTelemetry.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 20 · Lesson 8 of 9 · Advanced

Observability and Tracing

Trace every query through retrieval and generation with Langfuse, LangSmith or OpenTelemetry.

When a user reports "the assistant gave me a wrong answer yesterday", you need to see exactly what happened: what they asked, how the query was rewritten, which chunks were retrieved with what scores, the exact prompt, the model's response, the latency and the cost. Observability means recording this for every request as a trace so that any answer can be explained after the fact.

What to record per request

StageRecord
RequestTrace ID, timestamp, user or session ID (pseudonymised), app version, prompt version
Query processingOriginal question, condensed or rewritten query, routing decision
RetrievalRetrieved chunk IDs, scores, filters, index version, latency
RerankingFinal chunk IDs and rerank scores
GenerationModel, effort, input/output/cache tokens, stop reason, latency, the answer
OutcomeCitations used, guardrail results, user feedback (linked later by trace ID)

Start simple: structured JSON logs

One JSON line per request, with a trace ID, already answers most debugging questions and can be loaded into any log system.

tracing.py
import json
import logging
import time
import uuid

logger = logging.getLogger("rag")
logging.basicConfig(level=logging.INFO, format="%(message)s")

class Trace:
    def __init__(self, question: str, user: str, app_version: str):
        self.data = {"trace_id": str(uuid.uuid4()), "ts": time.time(), "question": question,
                     "user": user, "app_version": app_version, "spans": []}

    def span(self, name: str, **fields) -> None:
        self.data["spans"].append({"name": name, **fields})

    def finish(self, **fields) -> str:
        self.data.update(fields)
        logger.info(json.dumps(self.data, default=str))
        return self.data["trace_id"]

# In the request handler
trace = Trace(question, user="u_3f9a", app_version="2026.11.2")
hits = retriever.search(question, k=5)
trace.span("retrieve", ids=[h.id for h in hits], scores=[round(h.score, 3) for h in hits])
response = generate(question, hits)
trace.span("generate", model="claude-opus-5-5", input_tokens=response.usage.input_tokens,
           output_tokens=response.usage.output_tokens, stop_reason=response.stop_reason)
trace_id = trace.finish(answer=response.content[0].text)     # return trace_id to the client for feedback

OpenTelemetry

OpenTelemetry is the vendor-neutral standard for traces. Spans nest naturally, timing is automatic, and traces can be sent to any compatible backend (Jaeger, Grafana Tempo, Datadog, Honeycomb, Arize Phoenix, Langfuse and others).

# pip install opentelemetry-api opentelemetry-sdk
from opentelemetry import trace

tracer = trace.get_tracer("rag-service")

def answer(question: str) -> str:
    with tracer.start_as_current_span("rag.request") as root:
        root.set_attribute("rag.question_length", len(question))
        with tracer.start_as_current_span("rag.retrieve") as span:
            hits = retriever.search(question, k=5)
            span.set_attribute("rag.chunk_ids", [h.id for h in hits])
        with tracer.start_as_current_span("rag.generate") as span:
            response = generate(question, hits)
            span.set_attribute("llm.model", "claude-opus-5-5")
            span.set_attribute("llm.input_tokens", response.usage.input_tokens)
            span.set_attribute("llm.output_tokens", response.usage.output_tokens)
        return response.content[0].text

Configure an exporter (for example the OTLP exporter) at application startup to send spans to your backend. Instrumentation packages exist for popular libraries, including LLM SDKs, which add spans for model calls automatically.

LLM-specific observability tools

Tools built for LLM applications add views that general tracing lacks: rendered prompts and responses, token and cost dashboards, datasets built from traces, evaluation scores attached to traces, and feedback collection.

  • Langfuse: open source and self-hostable; decorators and an SDK for tracing, plus prompt management and evaluations.
  • LangSmith: from the LangChain team; deep integration with LangChain and LangGraph, but usable without them.
  • Arize Phoenix: open source, OpenTelemetry-based tracing and evaluation.

With Langfuse, for example, decorating your functions creates nested traces automatically:

# pip install langfuse ; set LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_HOST
from langfuse import observe

@observe()
def retrieve_step(query: str):
    return retriever.search(query, k=5)

@observe()
def rag_answer(question: str) -> str:
    hits = retrieve_step(question)
    return generate(question, hits).content[0].text

SDK details change between major versions; follow the tool's current documentation.

Dashboards and alerts

  • Quality: share of "not found" answers, thumbs-down rate, groundedness scores on sampled traces.
  • Retrieval: average top score, share of queries with no result above the threshold.
  • Performance: p50 and p95 latency per stage, time to first token, error rate.
  • Cost: tokens and spend per request, per user and per day; cache hit rate.

Alert on sudden changes: a spike in "not found" answers often means an ingestion job failed; a drop in cache hits means something started changing the prompt prefix.

Privacy

Traces contain questions, documents and answers, which may include personal or confidential data. Restrict access to traces, set retention periods, pseudonymise user IDs, and redact sensitive fields where possible (PII Detection and Redaction).

Key takeaways

  • Record a trace per request: query processing, retrieval results, prompt, model usage, answer and feedback.
  • Start with structured JSON logs and a trace ID; adopt OpenTelemetry or an LLM observability tool as you grow.
  • Build dashboards for quality, retrieval, latency and cost, with alerts on sudden changes.
  • Treat traces as sensitive data with access control and retention limits.