Sub topic 9
Tracing requests with MLflow
This chapter assumes you can call a served chat model from Python (the chat completions client chapter) and that you have built a small retrieve-then-generate function like the one in the RAG chapter. You should also know how Python decorators work.
Why trace a generative AI request
A single user question in a RAG application passes through several steps: retrieval, prompt assembly, and a model call. When the answer is wrong, the final string does not tell you which step failed. A trace is a record of one request that captures each step's inputs, outputs, timing, and errors. MLflow Tracing produces these records for you.
Each step in a trace is a span. Spans nest, so a parent span such as answer contains child spans such as retrieve. Each span has a type, for example RETRIEVER, CHAT_MODEL, or CHAIN, which the MLflow UI uses to display the step.
Tracing your own functions
The @mlflow.trace decorator turns a function call into a span. It records the arguments, the return value, the duration, and any exception raised. Nested decorated calls become child spans automatically.
import mlflow
@mlflow.trace(span_type="RETRIEVER")
def retrieve(question: str, k: int = 3) -> list[str]:
# Replace with a real Vector Search query
return ["Vector indexes store embeddings.", "They support similarity search."]
@mlflow.trace
def answer(question: str) -> str:
context = "\n\n".join(retrieve(question))
return f"Context used:\n{context}"
print(answer("What is a vector index?"))The earlier RAG function already uses this pattern. The decorators on retrieve and answer produce one trace with a RETRIEVER child span, without any other change to the code.
Tracing model calls automatically
You do not need to decorate the model call. MLflow can patch supported client libraries so that each call is traced. For the OpenAI-compatible client that the Databricks SDK returns, enable it once:
import mlflow
from databricks.sdk import WorkspaceClient
mlflow.openai.autolog()
client = WorkspaceClient().serving_endpoints.get_open_ai_client()
response = client.chat.completions.create(
model="<your-chat-endpoint-name>",
messages=[{"role": "user", "content": "Say hello in five words."}],
)
print(response.choices[0].message.content)The trace now includes a chat span with the messages, model name, parameters, and token usage. Combined with @mlflow.trace on your own functions, the model call appears as a child of the function that made it.
Where traces appear
In a Databricks notebook, traces display inline under the cell that ran the traced code. They are also stored on an MLflow experiment, where you can open the Traces tab to search and inspect them. To group traces under a known experiment, set it before running your code:
import mlflow
mlflow.set_experiment("/Users/<your-user>/rag-tracing-demo")Common errors
- No trace appears. The function was not decorated, or autologging was enabled after the client was created in another process. Enable autologging first, then run the call.
- A step is missing. Only decorated functions and autologged libraries create spans. Add
@mlflow.traceto the missing function. - Traces are in the wrong experiment. Call
mlflow.set_experimentbefore the traced code runs. - Sensitive data in traces. Spans store inputs and outputs as they are. Do not trace functions that handle secrets, and limit who can view the experiment.
What traces give you next
Traces are the raw material for later work. In the evaluation chapter you will score traced outputs against a dataset, and in production monitoring you will use traces from a live endpoint to find failures.
Exercise
A RAG request returns a wrong answer. The final output looks fine, but you suspect retrieval returned irrelevant chunks. Which span should you inspect, and what should you look at in it?
Show answer
Inspect the RETRIEVER span (the retrieve function). Check its input (the question and k) and its output (the returned chunks) to see whether the chunks are relevant to the question.
Exercise
You enabled mlflow.openai.autolog() and decorated answer with @mlflow.trace. How does the model call appear in the trace?
Show answer
It appears as a chat model child span under the answer span, with the messages, parameters, and token usage recorded.