Sub topic 12
Tracing Retrieval in RAG Pipelines
This chapter assumes you can use the tracer setup from earlier chapters and know how parent-child spans nest. Retrieval-augmented generation (RAG) fetches documents from a vector store or search index and adds them to the prompt. When an answer is wrong, you need to know whether retrieval or the model caused it.
Why retrieval gets its own span
A slow or empty retrieval step looks like a slow or bad model answer unless it has its own span. A separate span lets you see its latency, how many documents came back, and which query it ran.
The GenAI semantic conventions define a retrieval operation. Name the span retrieval <data source>, set gen_ai.operation.name to retrieval, and use SpanKind.CLIENT because the call goes to another service.
Where retrieval sits in the trace
Retrieval usually runs inside the agent or pipeline span, before the model call. Both are siblings under the same parent.
Instrumenting a retrieval call
This example uses a fake search function so it runs without a vector database. Replace search_index with your real client.
from opentelemetry import trace
from opentelemetry.trace import SpanKind, Status, StatusCode
tracer = trace.get_tracer("support_agent")
def search_index(query, top_k):
# Stand-in for a vector store query.
return [
{"id": "doc-7", "score": 0.91},
{"id": "doc-3", "score": 0.84},
][:top_k]
def traced_retrieve(query, top_k=5, source="product-docs"):
with tracer.start_as_current_span(f"retrieval {source}", kind=SpanKind.CLIENT) as span:
span.set_attribute("gen_ai.operation.name", "retrieval")
span.set_attribute("gen_ai.data_source.id", source)
span.set_attribute("app.retrieval.top_k", top_k)
try:
docs = search_index(query, top_k)
except Exception as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
raise
span.set_attribute("app.retrieval.result_count", len(docs))
if docs:
span.set_attribute("app.retrieval.top_score", docs[0]["score"])
span.add_event("retrieval.completed", {"doc_ids": [d["id"] for d in docs]})
return docsThe gen_ai.* names come from the conventions. The app.retrieval.* names are custom, and the app. prefix keeps them from clashing with standard names. Check the current convention version for exact names, because GenAI attributes are still evolving.
What to record
- Result count. Zero results is a common cause of hallucinated answers.
- Top score. A low top score means the index had nothing close to the query.
- Document IDs. IDs let you find the exact chunks later. They are safer than storing document text.
- Top-k and source. These show which configuration produced the result.
Common mistakes
- Putting query text on every span. Queries can contain personal data. Apply the same redaction rules you use for prompts.
- Storing full documents as attributes. This inflates span size and may leak private content. Store IDs.
- Starting the retrieval span outside the agent span. The retrieval then becomes its own trace and loses its link to the answer. Call it inside the agent's
withblock. - Not recording empty results. An empty list is not an exception, so the span ends with an unset status. The
result_countattribute is the only signal.
Exercise
A user reports a confident but wrong answer. The trace shows a fast chat span and a retrieval span with status unset. What attribute on the retrieval span do you check first, and why?
Show answer
Check the result count, then the top score. A retrieval that returns zero results, or only low-scoring results, does not raise an error, so the status stays unset. The model then answers without relevant context and can produce a plausible but wrong answer.