Sub topic 3
Tracing Retrieval in RAG Pipelines
Assume you know basic Python, context managers, LLM API calls, logs, metrics, and HTTP services. This chapter focuses on the spans around retrieval and agent behavior.
Trace retrieval and failures
In a retrieval-augmented generation (RAG) pipeline, retrieval finds relevant documents before the model writes an answer. Create a child span for each retrieval operation. Record the data source, query embedding model, top_k, result count, and duration. Avoid storing the full query or document text by default.
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
tracer = trace.get_tracer("support_agent")
def retrieve(query, top_k=5):
with tracer.start_as_current_span("retrieve documents") as span:
span.set_attribute("gen_ai.operation.name", "retrieve")
span.set_attribute("rag.retrieval.top_k", top_k)
try:
results = [{"id": "doc-17"}, {"id": "doc-42"}]
span.set_attribute("rag.retrieval.result_count", len(results))
return results
except TimeoutError as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, "retrieval timeout"))
raiseRetries should be visible. Create either a span for each attempt or an event such as retry, including the attempt number and reason. Set a timeout so a slow vector database cannot consume the whole agent budget.
Protect content and choose instrumentation
Prompt and response text can contain personal or confidential data. Capture content only when there is a clear debugging purpose, with redaction, access controls, short retention, and separate sampling rules. Hash identifiers when correlation is enough. Token counts and model names usually provide useful debugging information without storing the text.
Instrumentation libraries can create model or database spans automatically. Auto-instrumentation reduces manual code, but check its span names, attributes, retry behavior, and content-capture settings. Add manual spans around agent decisions and application-specific retrieval steps.
Read traces and control cost
A trace should show the agent run as a parent with model, retrieval, and tool children. Compare their durations to find the bottleneck. A repeated sequence of model and tool spans may indicate a runaway loop. A retrieval error followed by a model call may reveal an unsafe fallback.
Sample high-volume successful traces, but retain errors, slow traces, and selected complete agent runs. Apply sampling before exporting when possible, and configure retention by environment.
Pair traces with GenAI metrics such as request count, error rate, latency, input tokens, output tokens, and estimated cost. Metrics show trends; traces explain individual requests.
Exercise
Which retrieval data should you record first when prompt privacy is a concern?
Show answer
Record operation, data source, top_k, result count, duration, errors, and token or identifier metadata. Do not record raw queries or documents unless protected capture is necessary.