A user asks your support assistant how to rotate an API key and gets a confident answer about billing. The model call succeeded, latency was fine, and the response was well formed. The failure happened two steps earlier: the vector search returned four chunks from the billing docs because the query rewrite dropped the word "key". If all you trace is the model call, that request looks healthy. RAG observability means tracing the whole pipeline, so a bad answer can be traced back to the stage that caused it.
This guide covers how to lay out spans for a retrieval augmented generation pipeline, which attributes to put on each stage using the OpenTelemetry GenAI semantic conventions, the retrieval quality signals worth recording, and how to keep prompts and documents out of your telemetry unless you decide otherwise. If you are new to tracing model calls in general, start with our guide to what to trace on every LLM call; this article assumes that and goes one level deeper into retrieval.
Why tracing only the model call is not enough
A typical RAG request runs six stages in sequence: rewrite the user question into a search query, embed that query, search a vector index, rerank the candidates, assemble the prompt from the survivors, and generate the answer. Each stage can fail without raising an exception:
- Query rewrite can drop or invent terms, so retrieval searches for the wrong thing.
- Embedding can silently use a different model from the one the index was built with after a config change, which makes every similarity score meaningless.
- Vector search can return nothing, or return k results that are all weakly related, because the answer is not in the corpus.
- Reranking can push the one relevant chunk below the cut-off.
- Prompt assembly can truncate context to fit a token budget and drop the chunk that mattered.
- Generation can ignore the context it was given, or hit the output token limit mid-answer.
None of these show up as errors in an HTTP dashboard. They show up as wrong answers, and the only way to explain a wrong answer after the fact is a record of what each stage received and produced. A trace with one span per stage gives you that record, plus a latency breakdown for free.
One span per stage
Model the request as a root span for the whole pipeline with a child span for each stage. Stages that call a model or a remote service are CLIENT spans; stages that run in process, such as prompt assembly, are INTERNAL spans. The resulting trace looks like this:
rag.answer INTERNAL 1840 ms chat small-model (rewrite) CLIENT 210 ms embeddings embed-model CLIENT 35 ms retrieval kb-articles-v3 CLIENT 60 ms rag.rerank CLIENT 140 ms rag.prompt_assembly INTERNAL 4 ms chat large-model CLIENT 1380 ms
The span names for model and retrieval stages follow the conventions: inference spans are named {gen_ai.operation.name} {gen_ai.request.model}, so a chat call to a model is chat <model>, embeddings spans are embeddings <model>, and retrieval spans are retrieval {gen_ai.data_source.id}. Keep span names low cardinality. The question text never goes in a span name.
If you use auto-instrumentation such as OpenLLMetry or the OpenTelemetry contrib instrumentations for your model SDK, the chat and embeddings spans may already exist. Add manual spans only for the stages the libraries cannot see, usually reranking, prompt assembly and any retrieval logic of your own, and wrap the whole thing in the root span so everything lands in one trace.
Attributes per stage with the GenAI semantic conventions
The OpenTelemetry GenAI semantic conventions define attribute names for model calls, embeddings and retrieval. They are still marked Development, and names have changed between releases: gen_ai.system was replaced by gen_ai.provider.name, and the retrieval span recently gained its own gen_ai.retrieval.top_k in place of the generic gen_ai.request.top_k. Pin the semantic conventions version your instrumentation targets and check the changelog when you upgrade.
The attributes that matter for each stage:
- Query rewrite and generation (inference spans):
gen_ai.operation.name(chat),gen_ai.provider.name,gen_ai.request.model,gen_ai.response.model,gen_ai.usage.input_tokens,gen_ai.usage.output_tokens,gen_ai.response.finish_reasons, anderror.typeon failure. If the provider reports cached input tokens, addgen_ai.usage.cache_read.input_tokens. - Embedding:
gen_ai.operation.name(embeddings),gen_ai.request.model,gen_ai.usage.input_tokens, andgen_ai.embeddings.dimension.countif you set the output dimension. - Vector search:
gen_ai.operation.name(retrieval),gen_ai.data_source.idfor the index or collection,gen_ai.retrieval.top_kfor the k you asked for, plusdb.*attributes if your vector store is a database with its own conventions. - Rerank and prompt assembly: the conventions do not define these stages, so use your own namespace (
rag.*below) and keep the names stable.
Record the embedding model on the retrieval span too, or on the root span, with an index version. "The index was built with model A and queries were embedded with model B" is one of the hardest RAG bugs to spot from outputs, and one of the easiest to spot when both values sit on the same trace.
A Python example with the OpenTelemetry API
The code below instruments the pipeline by hand with the OpenTelemetry API. The helper functions (rewrite, embed, vector_search, rerank, build_prompt, generate) stand in for your own code, and the model names are placeholders. SDK and exporter setup are covered in the Python OpenTelemetry setup guide.
from opentelemetry import trace
from opentelemetry.trace import SpanKind
tracer = trace.get_tracer("rag.pipeline", "1.4.0")
PROVIDER = "openai" # a well-known gen_ai.provider.name value
EMBED_MODEL = "embed-model" # placeholder model names
CHAT_MODEL = "large-model"
INDEX = "kb-articles-v3"
TOP_K = 8
MIN_SCORE = 0.35 # tune against your own score distribution
def answer(question: str) -> str:
with tracer.start_as_current_span("rag.answer") as root:
root.set_attribute("rag.index.version", INDEX)
query = rewrite(question) # its own "chat <model>" span inside
with tracer.start_as_current_span(
f"embeddings {EMBED_MODEL}", kind=SpanKind.CLIENT
) as span:
span.set_attribute("gen_ai.operation.name", "embeddings")
span.set_attribute("gen_ai.request.model", EMBED_MODEL)
vector, usage = embed(query)
span.set_attribute("gen_ai.usage.input_tokens", usage.input_tokens)
with tracer.start_as_current_span(
f"retrieval {INDEX}", kind=SpanKind.CLIENT
) as span:
span.set_attribute("gen_ai.operation.name", "retrieval")
span.set_attribute("gen_ai.data_source.id", INDEX)
span.set_attribute("gen_ai.retrieval.top_k", TOP_K)
span.set_attribute("rag.embedding.model", EMBED_MODEL)
hits = vector_search(INDEX, vector, k=TOP_K)
scores = [h.score for h in hits]
span.set_attribute("rag.retrieval.returned", len(hits))
span.set_attribute("rag.retrieval.top_score", max(scores, default=0.0))
span.set_attribute(
"rag.retrieval.above_threshold",
sum(s >= MIN_SCORE for s in scores),
)
if not hits:
span.add_event("rag.retrieval.empty")
with tracer.start_as_current_span("rag.rerank", kind=SpanKind.CLIENT) as span:
ranked = rerank(query, hits)[:4]
span.set_attribute("rag.rerank.input_count", len(hits))
span.set_attribute("rag.rerank.output_count", len(ranked))
span.set_attribute(
"rag.rerank.top_score", ranked[0].score if ranked else 0.0
)
with tracer.start_as_current_span("rag.prompt_assembly") as span:
prompt, used = build_prompt(question, ranked, max_context_tokens=6000)
span.set_attribute("rag.context.chunks", len(used))
span.set_attribute("rag.context.tokens", prompt.context_tokens)
span.set_attribute("rag.context.truncated", len(used) < len(ranked))
span.set_attribute("rag.context.doc_ids", [c.doc_id for c in used])
with tracer.start_as_current_span(
f"chat {CHAT_MODEL}", kind=SpanKind.CLIENT
) as span:
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.provider.name", PROVIDER)
span.set_attribute("gen_ai.request.model", CHAT_MODEL)
resp = generate(prompt)
span.set_attribute("gen_ai.response.model", resp.model)
span.set_attribute("gen_ai.usage.input_tokens", resp.input_tokens)
span.set_attribute("gen_ai.usage.output_tokens", resp.output_tokens)
span.set_attribute("gen_ai.response.finish_reasons", [resp.finish_reason])
root.set_attribute("rag.grounded", len(used) > 0)
return resp.textTwo details worth knowing. start_as_current_span records an exception and sets the span status to error by default when the block raises, so failed stages are marked without extra code; add an error.type attribute with a low-cardinality value (timeout, rate_limited) so you can group them. And the document IDs on the prompt assembly span are identifiers, not text: they tell you which chunks the model saw without copying your knowledge base into your trace store.
Retrieval quality signals
Latency and errors tell you whether the pipeline ran. Retrieval quality signals tell you whether it ran on the right material. These are the ones that have earned a place on the span in practice:
- Top score. The similarity score of the best hit. Plot its distribution per index. A drift downward after a deploy usually means the query side changed (a new rewrite prompt, a new embedding model) while the index did not.
- Empty retrievals. Zero results, or zero results above your relevance threshold. This is the closest thing RAG has to a 404, and it should be a rate on a dashboard, broken down by index and by feature.
- Hits above threshold. Of the k results returned, how many scored above the cut-off. A search that always returns k results tells you nothing; the count above threshold tells you how much usable context there was.
- Score gap. The difference between the first and the k-th score. A flat distribution means the retriever could not distinguish relevant from irrelevant chunks.
- Context truncation. Whether prompt assembly dropped chunks to fit the token budget. Frequent truncation means either k is too high or chunks are too long.
- Finish reason. A
lengthfinish reason on the generation span means the answer was cut off, which users read as a broken product.
Absolute similarity scores are not comparable across embedding models or distance metrics, so set thresholds per index and recalibrate them when you change the model. Treat the numbers as relative signals for one configuration over time, not as universal quality measures.
The quality signals also make good sampling rules. If you sample traces, a tail sampling policy that keeps every trace with an empty retrieval or a truncated context gives you the interesting failures at a fraction of the volume; see head vs tail sampling for how to set that up in the Collector.
Latency breakdown
RAG latency is the sum of sequential stages, so the trace waterfall is the profiler. In most pipelines generation dominates, but the stages around it are where regressions hide: a reranker that went from 80ms to 400ms after someone raised the candidate count, or a query rewrite step that doubled end-to-end time for a small quality gain. Chart p50 and p95 duration per stage, grouped by span name, rather than only the end-to-end number.
If you stream the answer, users feel time to first token, not total duration. Record the moment the first chunk arrives as a span event on the generation span (or as an attribute of your own) so you can separate "the model took long to start" from "the model wrote a long answer". The fix for the first is usually a smaller prompt; the fix for the second is a tighter output limit or a better instruction.
Prompt and document privacy
RAG prompts contain the most sensitive text in your system: user questions, retrieved internal documents, sometimes personal data pulled from a CRM. The semantic conventions treat this content as opt-in. Attributes such as gen_ai.input.messages, gen_ai.output.messages, gen_ai.system_instructions, gen_ai.retrieval.query.text and gen_ai.retrieval.documents are only recorded when you explicitly enable content capture, and instrumentations default to capturing none. For example, the OpenAI instrumentation in opentelemetry-python-contrib reads OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT; check the documentation of each instrumentation you use for its exact switch.
A workable policy for most teams:
- Default to metadata only. Token counts, models, scores, document IDs and finish reasons answer most debugging questions without any content.
- Enable content per environment. Capture full prompts in staging and in a short-lived debugging window in production, not by default.
- Strip at the Collector as a backstop. An
attributesprocessor withaction: deleteon the content keys guarantees they never reach storage, even if an application enables capture by mistake. - Give content a shorter retention than the rest of your traces if you do keep it, and restrict who can query it.
RAG observability in aiAxonIQ
aiAxonIQ ingests these spans over OTLP like any other trace, so the retrieval stages sit in the same waterfall as the HTTP request and database calls that surround them. LLM Insights is OpenLLMetry-compatible, records vector database retrieval spans for RAG pipelines, and breaks down token counts, latency and model per call, so the quality signals above can be charted next to the cost and latency of the model calls they feed.