RAG Tracing

RAG tracing records every step of a retrieval-augmented generation request, from the user query and the documents retrieved to the final prompt and the model's answer, as a single trace you can inspect. It shows you what context the LLM was actually given, which is the first thing you need to know when a RAG application gives a wrong or unsupported answer.

MLflow Tracing is an open-source, OpenTelemetry-compatible way to do this. It captures each retrieval, rerank, prompt, and generation step as a span with inputs, outputs, latency, and token usage. You can turn it on with one line for popular frameworks, or add it to a custom pipeline with a decorator.

Last updated: 2026-11-26

MLflow trace UI showing the span tree of a single agent request, with per-span latency, token counts, estimated cost, and the request's input and output
A trace in the MLflow UI: the span tree on the left with latency, tokens, and cost per step, and the request's input and output on the right. Demo data.

Quick Navigation:

Why Should You Trace a RAG Pipeline?

You trace a RAG pipeline to find out where a bad answer came from: retrieval, prompt assembly, or generation. From the outside, all three failures look the same, a wrong answer. A trace shows each step, so you can fix the right one.

Irrelevant retrieval

Symptom: The answer is off-topic or generic.

What the trace shows: The retrieval span returned documents that do not match the query, pointing at chunking, embeddings, filters, or top-k.

Missing context

Symptom: The model says it does not know, or guesses.

What the trace shows: The needed document was never retrieved, or a rerank or filter step dropped it.

Ungrounded answers

Symptom: The answer sounds right but cites facts that are not in your data.

What the trace shows: The right context was in the prompt, but the generation span's output contradicts or goes beyond it.

Slow or costly requests

Symptom: High latency or token spend on some queries.

What the trace shows: Per-step latency and token usage, such as an oversized context window or a slow vector-store call.

What Does a RAG Trace Contain?

A RAG trace is a tree of spans, one for each pipeline step: query handling, retrieval, reranking, prompt assembly, and generation. Each span has a type, so you can find the retrieval step in any request without reading logs. A typical trace looks like this:

StepSpan typeWhat to look at
Query handlingCHAIN or PARSERThe raw user query and any rewritten or expanded query
RetrievalRETRIEVERThe documents returned: content, source metadata, ids, and scores
Reranking or filteringRERANKER or TOOLWhich documents were kept, reordered, or dropped
Prompt assemblyPARSER or CHAINThe final prompt, including the context actually passed to the model
GenerationLLM or CHAT_MODELThe model, parameters, response, latency, and token usage

The RETRIEVER span type matters most. MLflow's RAG judges use it to find your retrieval step, and the LangChain, LlamaIndex, and Haystack integrations set it for you.

How Do You Trace RAG with MLflow?

Call autolog() for a supported framework, or decorate your retrieval function with @mlflow.trace(span_type="RETRIEVER") for a custom pipeline. Both produce the same kind of trace, and you can combine them.

Option 1: Use autolog for popular frameworks

MLflow provides automatic tracing for the frameworks most RAG applications are built on, including LangChain, LlamaIndex, Haystack, DSPy, and the OpenAI SDK. Call autolog() once and every retriever, chain, and LLM call is recorded.

python
import mlflow
mlflow.set_experiment("rag-app")
# Enable once, before your app runs. Pick the line that matches your stack.
mlflow.langchain.autolog() # LangChain and LangGraph retrievers and chains
# mlflow.llama_index.autolog() # LlamaIndex query engines and retrievers
# mlflow.haystack.autolog() # Haystack pipelines
# mlflow.openai.autolog() # the LLM call inside any custom pipeline
answer = rag_chain.invoke({"question": "How do I enable tracing?"})

Option 2: Decorate your own retrieval code

For a custom pipeline, use manual tracing. Mark the retrieval function as a RETRIEVER span and return Document objects. Use mlflow.start_span for any extra step you want to see, such as prompt assembly.

python
import mlflow
from mlflow.entities import Document, SpanType
@mlflow.trace(span_type=SpanType.RETRIEVER)
def retrieve(query: str) -> list[Document]:
hits = vector_store.search(query, top_k=5) # your vector database
return [
Document(
id=h.id,
page_content=h.text,
metadata={"source": h.source, "score": h.score},
)
for h in hits
]
@mlflow.trace(span_type=SpanType.CHAIN)
def answer(query: str) -> str:
docs = retrieve(query)
with mlflow.start_span(name="build_prompt", span_type=SpanType.PARSER) as span:
context = "\n\n".join(d.page_content for d in docs)
prompt = f"Answer using only this context:\n{context}\n\nQuestion: {query}"
span.set_inputs({"query": query, "num_docs": len(docs)})
span.set_outputs(prompt)
return call_llm(prompt) # traced by mlflow.openai.autolog() or similar

The two options combine well. You can autolog the LLM call and decorate the retrieval function, and both appear in the same trace.

How Do You Debug Bad Retrieval?

Open the trace of a bad answer and ask three questions in order: were the right documents retrieved, did they reach the prompt, and did the model use them? The first "no" tells you which stage to fix.

  1. Were the right documents retrieved? Open the retrieval span. If the answer was in your corpus but not in the output, look at chunking, embeddings, metadata filters, and top-k.
  2. Did they reach the prompt? Open the prompt span. A rerank, truncation, or formatting bug can drop good documents after retrieval.
  3. Did the model use them? If the context was right and the answer is still wrong, the problem is in generation, such as the prompt wording or the model choice.

In the MLflow UI, filter the Traces tab to find failing requests, open one, and click through the span tree. To find patterns across many requests, search traces from code and inspect the retriever spans programmatically. See searching traces for the filter syntax.

python
import mlflow
from mlflow.entities import SpanType
traces = mlflow.search_traces(max_results=50, return_type="list")
for trace in traces:
for span in trace.search_spans(span_type=SpanType.RETRIEVER):
docs = span.outputs or []
print(trace.info.trace_id, f"{len(docs)} documents retrieved")

How Do You Score Retrieval Quality on Your Traces?

Use MLflow's built-in RAG judges. They read the retriever spans in your traces and score each request, so you can find weak retrieval across thousands of requests instead of reading traces one at a time:

JudgeQuestion it answersNeeds ground truth
RetrievalRelevanceIs each retrieved document relevant to the user's request?No
RetrievalGroundednessIs the response supported by the retrieved context?No
RetrievalSufficiencyDo the retrieved documents contain everything needed for the expected answer?Yes
python
import mlflow
from mlflow.genai.scorers import RetrievalRelevance, RetrievalGroundedness
# Score the retrieval step and the grounding of the answer on recent traces
traces = mlflow.search_traces(max_results=100)
results = mlflow.genai.evaluate(
data=traces,
scorers=[RetrievalRelevance(), RetrievalGroundedness()],
)

Results are logged to MLflow, so you can compare retrieval changes, such as a new chunk size or embedding model, on the same set of requests. Judge scores are model-generated and can be wrong, so spot-check a sample of low and high scores against your own judgment before you rely on them. For the full workflow, see LLM evaluation and the RAG judges guide.

Can You Trace RAG in Production?

Yes. The same tracing works in production. For high-volume services, MLflow recommends the lightweight production tracing SDK, asynchronous trace logging, and sampling through the MLFLOW_TRACE_SAMPLING_RATIO environment variable to control overhead and storage. Tracing is OpenTelemetry compatible, so it fits alongside existing observability tools.

Retrieved documents can be large or sensitive. You can trim what a retriever span stores and mask sensitive data before it is logged. See production tracing for the full checklist.

Getting started: Install MLflow with pip install mlflow, start the UI with mlflow server, and follow the tracing quickstart.

Frequently Asked Questions

RAG tracing is the practice of recording every step of a retrieval-augmented generation request as a structured trace: the user query, any query rewriting, the retrieval call and the documents it returned, reranking, the assembled prompt, and the LLM generation. Each step is a span with inputs, outputs, latency, and errors, so you can see exactly which context the model was given and why an answer was good or bad.

Related Resources