跳到正文

第 18 课 · Tracing and LLM Apps

Tracing Basics

Understand MLflow traces and spans, add manual tracing with decorators and context managers, set span types and read a trace tree to debug an app.

An LLM app may search documents, build a prompt, call a model, call a tool and call the model again. When the answer is wrong, which step caused it? Tracing records each step so you can look inside.

Traces and spans

A trace is the record of one request through your app. It is made of spans. Each span is one step, with a name, inputs, outputs, timing and status. Spans form a tree, because one step can contain others.

flowchart TD
  A["answer_question"] --> B["retrieve_documents"]
  A --> C["call_model"]
  C --> E["tool: lookup_order"]
  A --> D["check_answer"]

One trace: a root span with child spans.

MLflow Tracing is compatible with OpenTelemetry, an open standard for telemetry data. See agent observability for the wider idea.

The decorator

The easiest way is @mlflow.trace:

Python
import mlflow
from mlflow.entities import SpanType

@mlflow.trace(span_type=SpanType.RETRIEVER)
def retrieve(question: str):
    return search_index(question)

@mlflow.trace(name="answer_question", span_type=SpanType.CHAIN)
def answer(question: str):
    docs = retrieve(question)
    return write_answer(question, docs)

answer("How long is the return window?")

The decorator records arguments and return values as inputs and outputs. When answer calls retrieve, the second span is nested under the first. You can set a name, a span_type and extra attributes. Span types include ones for language model calls, chains, retrievers and tools.

Spans for a block of code

When you only want to trace part of a function, use mlflow.start_span. Here you record inputs and outputs yourself:

Python
with mlflow.start_span(name="rank_documents") as span:
    span.set_inputs({"count": len(docs)})
    ranked = rank(docs)
    span.set_outputs({"top": ranked[:3]})

Build a tiny tracer

This stand-in shows how nesting works with a stack. It is far simpler than a real tracing library.

Python Stand-in: a tiny tracer that records a span tree

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

How to read a trace

  1. Find the root and the final output.
  2. Check the retrieval or tool spans first: did the app get the right information?
  3. Look at the model span: what exactly was in the prompt?
  4. Check errors and slow spans.
  5. If the information was wrong, fix retrieval. If it was right but the answer was wrong, look at the prompt or the model.

This order saves time. Many problems that look like model errors are really missing or wrong context.

Names and attributes

Give spans stable, meaningful names such as retrieve_policy. Add attributes such as an index version or an app version. When a release changes behavior, those attributes help you group traces.

Traces record inputs and outputs. These can include personal data, secrets or confidential documents. Decide what may be stored, and redact before logging. The next lesson shows how.

Metadata that makes traces useful

A trace on its own shows one request. Metadata lets you group thousands of them. Useful items are:

Item Question it answers
App version Did a release change behavior?
Prompt version Which text was used?
Model name Which model answered?
Environment Test or production?
Session ID What happened earlier in this conversation?

Add them as trace tags or span attributes. The decorator accepts attributes, and mlflow.update_current_trace(tags=...) adds trace-level tags.

What a good span records

For a retrieval span, record the query and the identifiers of the documents found, possibly with their scores. For a tool span, record the tool name, the arguments and a short result. For a model span, record the prompt, the response, the model and token usage. Many integrations record the model details for you.

Do not record everything. Large documents repeated in every span make traces slow to read and expensive to store. Identifiers plus a short preview are often enough, as long as you can look up the full document elsewhere.

Errors and partial work

If a step raises an error, the span is marked with the failure, and you can see how far the request got. This is much better than a log line that only says "request failed". Handle errors in your app as usual. Tracing observes what happened, and it does not fix problems or retry calls.

Traces versus logs

Traditional logs are separate lines of text. A trace connects the steps of one request into a tree with timing. You still need normal logs and monitoring for servers and infrastructure. Tracing adds the application view: which steps ran, in what order, with what content, and how long each took. When someone reports a bad answer, a trace ID in your app logs lets you jump from the user report to the exact trace.

Common mistakes

Do not trace only the model call. If retrieval and tool steps are missing, you see the prompt but not how it was built. Also avoid decorating tiny helper functions that run thousands of times, which creates noise and cost. Trace the steps that you would want to inspect when something goes wrong.

After you add tracing, send one request and open its trace. Confirm that the tree matches your mental picture of the app. If a step is missing or nested in a strange place, fix it now.

Practice

Change the stand-in so that write_answer raises an error, then run it. Watch which spans are marked as errors. Because the error travels up through the callers, you should see more than one failed span, and the deepest one shows where it started. You will need to wrap the final call in try to see the printed tree.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. What is a span?

    A trace is a tree of spans, and each one describes a step.
  2. 2. What happens when a traced function calls another traced function?

    Calls made inside a traced function become child spans.
  3. 3. A retrieval-based answer is wrong. What should you inspect early?

    If the context was wrong or missing, changing the prompt will not fix it.

Summary

  • A trace is a tree of spans for one request.
  • Use @mlflow.trace for functions and mlflow.start_span for blocks.
  • Read traces from retrieval to model to errors and timing.
  • Protect sensitive data in traces.

Next: Auto Tracing, Feedback and Production

你的学习进度保存在此浏览器中,无需账号。