CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 6 · Lesson 49/56

    Evaluating agents with MLflow traces, evaluate() and scorers

    Evaluate agent performance using MLflow scoring and tracing

    19 min read
    1.2% of exam
    7 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Explain how a scorer reads a trace and attaches its result to that trace as feedback
    • Run mlflow.genai.evaluate() in direct mode with predict_fn or in answer-sheet mode with pre-computed outputs or existing traces
    • Choose between built-in judges, Guidelines judges, custom judges and code-based scorers for a given quality check
    • Pick the built-in judge that fits a dataset, including Correctness when expected_response ground truth is present, and change the judge model
    • Write natural-language Guidelines that an LLM judge applies as pass/fail checks

    Key concept

    Scorer-on-trace contract — Every MLflow scorer works the same way. It takes a trace, pulls out the fields it needs, makes its assessment, and attaches the result to that same trace as Feedback. Evaluation can only judge what the trace recorded.

    1.Traces are the evidence every score rests on

    Evaluating an agent in MLflow means attaching quality judgements to recorded runs of that agent. The record is the trace. MLflow Tracing (autolog and spans) captures one trace per request, with a span for each step. Tracing records the inputs, outputs, latency, token usage and cost of every intermediate step, so the trace maps the whole execution flow. Debugging, evaluation and production monitoring all work from that same evidence.

    A scorer does three things, and they are the same whether evaluate() or the production monitoring service hands it the trace:

    1. It parses the trace to extract the fields and data it needs to assess quality.
    2. It runs its assessment on those fields.
    3. It returns the result as Feedback and attaches it to the trace.

    Because a scorer reads specific parts of the trace, how you instrument the agent decides which scorers can work. In the Databricks email-generation tutorial, the CRM lookup function is decorated with @mlflow.trace(span_type="RETRIEVER"). That marker is what enables MLflow's retrieval-specific LLM judges. RetrievalGroundedness has to find the retrieved context before it can check whether the email sticks to it, and it finds that context in the retriever span. If the retrieval step is not marked as a retriever span, that judge has no context to read.

    Scores and traces answer different questions. A Correctness score says whether one answer was right, but it does not show which tool the agent called or how long each step took. When an agent sometimes picks the wrong tool, open the trace for a failing request and walk its span tree (agent → LLM call → tool call). Each span shows the inputs, outputs and latency of one step, which is where the wrong tool choice becomes visible.

    Checkpoint 1 of 8· Fill the gap

    An email agent's CRM lookup returns customer documents. You want RetrievalGroundedness to check whether each email sticks to what was retrieved. Which span type must decorate the lookup function?

    @mlflow.trace(span_type=" ? ")

    Checkpoint 2 of 8· Exam question

    An engineer is debugging an agent that occasionally invokes the wrong tool for a user's request. For one specific problematic request, they need to see the exact sequence of retriever calls, LLM calls, and tool calls, along with the inputs, outputs, and latency of each individual step. What should they inspect?

    Sources123

    2.The mlflow.genai.evaluate() harness: direct and answer-sheet modes

    mlflow.genai.evaluate() runs an agent against test data and scores every result automatically, so you don't have to run cases and inspect outputs by hand. Typical uses are nightly or weekly checks against a curated dataset, validating a prompt or model change across app versions, and gating a release or PR against quality regressions. The signature shows the whole contract. Only data and scorers are required.

    Signature of mlflow.genai.evaluate(); predict_fn is used only in direct evaluationpython
    def mlflow.genai.evaluate(
        data: Union[pd.DataFrame, List[Dict], mlflow.genai.datasets.EvaluationDataset],  # Test data.
        scorers: list[mlflow.genai.scorers.Scorer],  # Quality metrics, built-in or custom.
        predict_fn: Optional[Callable[..., Any]] = None,  # App wrapper. Used for direct evaluation only.
        model_id: Optional[str] = None,  # Optional version tracking.
    ) -> mlflow.models.evaluation.base.EvaluationResult:

    Direct evaluation is the recommended mode. You pass the app's entry point as predict_fn, or wrap a Databricks Model Serving endpoint with to_predict_fn. MLflow runs each row's inputs through the app, captures a trace, and runs the scorers on that trace. Since MLflow generated the traces itself, they are identical to production traces, and the scorers you wrote for offline evaluation can be reused in production monitoring without changes.

    Direct evaluation: each row's inputs dict is passed to predict_fn, and the resulting traces are scoredpython
    # Evaluate your app
    results = mlflow.genai.evaluate(
        data=[
            {"inputs": {"question": "What is MLflow?"}},
            {"inputs": {"question": "How do I get started?"}}
        ],
        predict_fn=my_chatbot_app,
        scorers=[RelevanceToQuery(), Safety()]
    )

    Answer-sheet evaluation is for cases where you can't, or don't want to, run the agent during evaluation. The outputs may come from an external system, a batch job or historical traces. Each row supplies either inputs plus pre-computed outputs, or a trace object. When you give inputs and outputs, evaluate() builds traces from them first. Either way it then runs the scorers on those traces. One catch: if these traces differ in shape from your production traces, you may have to rewrite the scorers before you can use them for monitoring.

    Answer-sheet evaluation over existing traces pulled with search_tracespython
    import mlflow
    
    # Retrieve traces from production
    traces = mlflow.search_traces(
        filter_string="trace.status = 'OK'",
    )
    
    # Evaluate problematic traces
    evaluation = mlflow.genai.evaluate(
        data=traces,
        scorers=[Safety(), RelevanceToQuery()]
    )
    Direct versus answer-sheet evaluation
    ModeEach data row suppliespredict_fnWins when
    Direct evaluationinputs (plus optional expectations)Required: app wrapper, or endpoint via to_predict_fnYou can run the app and want scorers that carry over unchanged to production monitoring
    Answer sheet: inputs and outputsinputs, pre-computed outputs, optional expectationsNot usedOutputs already exist from batch jobs or external systems
    Answer sheet: existing tracestrace (mlflow.entities.Trace), optional expectationsNot usedYou want to score production or historical traces again

    Both modes store their output the same way: as traces with scorer feedback in the active MLflow experiment. Each trace is one dataset row, annotated by every scorer. You can view them under the experiment's Evaluation runs page, or load them as a DataFrame whose assessments column holds each judge's feedback. Evaluation runs on a background thread pool, and MLFLOW_GENAI_EVAL_MAX_WORKERS sets the number of workers.

    Loading the evaluated traces and their judge feedback for an evaluation runpython
    eval_traces = mlflow.search_traces(run_id=eval_results.run_id)
    
    # eval_traces is a Pandas DataFrame that has the evaluated traces.  The column `assessments` includes each judge's feedback.
    print(eval_traces)

    Checkpoint 3 of 8· Check yourself

    A team can call its agent during evaluation. They want the scorers they build offline to run in production monitoring with no changes. Which setup fits, and why?

    Sources43

    3.Four kinds of scorer, from least to most control

    Scorers come in kinds that build on one another, each giving more complexity and control than the one before. The usual path is to start with built-in judges, add custom LLM judges for domain-specific criteria, and write code-based scorers for deterministic business logic. A scorer's result can be pass/fail, true/false, a number or a category. Whichever kind you pick, it goes in the same scorers list and follows the same trace-in, feedback-out contract.

    The four kinds of scorer, ordered by how much control they give
    KindHow it decidesControlPick it when
    Built-in judges (e.g. Correctness, RetrievalGroundedness, Safety)Databricks-hosted LLM with a predefined, research-validated criterionMinimalYou need a common quality dimension measured quickly
    Guidelines judgesBuilt-in LLM judge applying your natural-language pass/fail rulesModerateThe criterion is a style, tone or content rule you can state in words
    Custom judges (make_judge())LLM with your own instructions over inputs, outputs, expectations or the full traceFullYou need graded scores or categories, or must judge whether the agent's decisions and operations were right
    Code-based scorersPython logic over the trace, with no LLM requiredFullThe check is deterministic: exact matching, format validation, performance metrics

    A custom judge is still an LLM, but you write its prompt. make_judge() takes natural-language instructions with template variables: {{ inputs }}, {{ outputs }}, {{ expectations }} and {{ trace }}. The instructions must use at least one of them. No other variables are allowed, so a custom one such as {{ question }} fails validation. With {{ trace }} the judge can read the full execution, which is how you check whether the agent made the right decisions and not only whether the final text reads well.

    Code-based scorers are the most flexible kind. Use them for a heuristic or programmatic metric, for changing how trace data is mapped into a built-in judge, for calling your own LLM in place of a Databricks-hosted judge, or for anything a custom judge can't express. The @scorer signature and return types explains how to write one. For this lesson, the key fact is that a decorated function goes straight into evaluate() alongside the LLM judges. The Databricks results view shows the built-in Safety judge and a custom exact_match scorer side by side on the same traces.

    Checkpoint 4 of 8· Check yourself

    Your support agent chooses among five tools for each request. You want a score from 1 to 5 for whether it picked the right tool and passed sensible arguments, graded against a rubric you write yourself. Which scorer setup fits?

    Checkpoint 5 of 8· Exam question

    A support agent must include a case ticket number in a fixed format (e.g. TCKT-000000) in every response. An ML engineer wants to score whether each trace's output matches this exact pattern, and needs the result to be a deterministic pass/fail rather than a probabilistic LLM judgment. How should they implement this scorer in MLflow?

    Sources25

    4.Built-in LLM judges and the model behind them

    Built-in judges are predefined scorers that use Databricks-hosted LLMs to measure common quality dimensions, and they are the quickest way to start. They differ in which trace fields they read. Some need only the request and response. Others also need expectations, the optional ground-truth column of the evaluation dataset.

    Core built-in single-turn judges and what each needs
    JudgeReadsNeeds ground truthChecks
    RelevanceToQueryinputs, outputsNoIs the response directly relevant to the user's request?
    Safetyinputs, outputsNoIs the content free from harmful, offensive or toxic material?
    RetrievalGroundednessinputs, outputsNoIs the response grounded in the retrieved context, or is the agent hallucinating?
    RetrievalRelevanceinputs, outputsNoIs the retrieved context relevant to the request?
    Correctnessinputs, outputs, expectationsYesIs the response correct compared with the provided ground truth?
    RetrievalSufficiencyinputs, outputs, expectationsYesDoes the context contain everything needed to produce the ground-truth facts?

    Correctness is the judge for a dataset with expert-written answers. expectations has reserved keys that built-in judges look for, and Correctness reads two of them: expected_response, an exact or similar expected output, and expected_facts, a list of facts the answer should contain. If an SME has written an expected_response for each FAQ row, register Correctness() to score factual accuracy against it. RelevanceToQuery, Safety and Guidelines all ignore that column, so none of them can tell you whether the answer matches the expert's version.

    Each judge runs on a Databricks-hosted LLM built for GenAI quality assessment unless you pass the model argument. The value uses the format <provider>:/<model-name>. Swapping the model also matters when partner-powered AI features are disabled in the workspace: that blocks the default judge from calling partner models, but a judge given your own model still works. Judge outputs are for evaluating your application and must not be used to train or fine-tune an LLM.

    Overriding the model that powers a built-in judgepython
    from mlflow.genai.scorers import Correctness
    
    Correctness(model="databricks:/databricks-gpt-5-mini")

    Checkpoint 6 of 8· Fill the gap

    Partner-powered AI features are disabled in your workspace, so the default judge can no longer call partner models. You still need Correctness to score answers against the SME-written expected_response. Which argument lets the judge run on a model you choose?

    from mlflow.genai.scorers import Correctness
    
    Correctness( ? ="databricks:/databricks-gpt-5-mini")

    Checkpoint 7 of 8· Exam question

    An engineer has curated an evaluation dataset for a support FAQ agent, where each row includes an expected_response written by a subject-matter expert. They want to run mlflow.genai.evaluate() to score how factually accurate each generated answer is against that expected response. Which built-in judge should they register for this evaluation run?

    Sources672

    5.Guidelines judges: pass/fail rules in plain language

    A Guidelines judge is a built-in judge whose criterion you write yourself. You give it a name and a natural-language guidelines string, and an LLM decides whether each response passes or fails. It sits between the fixed built-ins and fully custom judges. Use it for rules that are easy to say but hard to code, such as tone, structure or what an email must mention.

    Guidelines judges mixed with a built-in judge in one scorer list (from the email-generation tutorial)python
    email_judges = [
            RetrievalGroundedness(),  # Checks if email content is grounded in retrieved data
            Guidelines(
                name="follows_instructions",
                guidelines="The generated email must follow the user_instructions in the request.",
            ),
            Guidelines(
                name="concise_communication",
                guidelines="The email MUST be concise and to the point. The email should communicate the key message efficiently without being overly brief or losing important context.",
            ),
            Guidelines(
                name="mentions_contact_name",
                guidelines="The email MUST explicitly mention the customer contact's first name (e.g., Alice, Bob, Carol) in the greeting. Generic greetings like 'Hello' or 'Dear Customer' are not acceptable.",
            ),

    The rules in that list are written so a judge can't hedge. mentions_contact_name gives examples of passing names and spells out which greetings fail. includes_next_steps, further down the same list, asks for a specific next step with a concrete timeline. Phrasing like that is why the tutorial's first run could clearly report weak instruction-following, emails that were too long and missing next steps. Each rule becomes a named Pass or Fail assessment on every trace, and hovering over the label in the Evaluation runs view shows the judge's rationale.

    Guidelines applies the same rules to every row. When the rule changes from row to row, use ExpectationsGuidelines, which reads per-example criteria from the guidelines key in expectations. It needs no factual ground truth, only those guidelines. Whichever you use, the verdict comes from an LLM. Choose Guidelines when an expert reader could judge the rule from the text, and move to a code-based scorer when the rule is a pattern a program can check.

    Checkpoint 8 of 8· Fill the gap

    Every generated email, on every row of the dataset, must greet the contact by first name. An LLM should give a Pass or Fail on that one fixed rule, and no ground truth is needed. Which scorer class completes this entry in the tutorial's scorer list?

             ? (
                name="mentions_contact_name",
                guidelines="The email MUST explicitly mention the customer contact's first name (e.g., Alice, Bob, Carol) in the greeting. Generic greetings like 'Hello' or 'Dear Customer' are not acceptable.",
            ),

    Sources236

    Practise it for real

    Run a direct evaluation that mixes a built-in judge with a Guidelines judge, then read the feedback attached to the resulting traces.

    1. 1.Install the packages with pip install --upgrade "mlflow[databricks]>=3.1.0" openai "databricks-connect>=16.1", and set an MLflow experiment.

      Why: evaluate() writes its traces and feedback into the active experiment.

      You should see: MLflow 3 imports cleanly and the experiment exists.

    2. 2.Decorate a small app function with @mlflow.trace that returns {"response": ...}, and call it once by hand.

      Why: Direct evaluation scores the traces your app produces, so the app has to be traced.

      You should see: A trace for that call appears on the experiment's Traces tab.

    3. 3.Call mlflow.genai.evaluate() with two rows of inputs, predict_fn set to your function, and scorers=[RelevanceToQuery(), Safety(), Guidelines(name="professional_tone", guidelines="The response must be in a professional tone.")].

      Why: Built-in and Guidelines judges go in the same scorers list and run on each trace.

      You should see: An evaluation run with one trace per row, each carrying three assessments.

    4. 4.Run mlflow.search_traces(run_id=results.run_id) and inspect the assessments column, then hover over a Pass/Fail label under Evaluation runs.

      Why: Feedback is stored on the traces, and the rationale explains each verdict.

      You should see: A DataFrame of evaluated traces with per-judge feedback, and a rationale for each label in the UI.

    Stuck? Get a nudge

    If professional_tone passes everything, make the rule stricter and run again. The point is to see one rule change the verdicts across the same traces.

    Sources

    (7)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Tracing records the inputs, outputs, latency, token usage, and cost of every intermediate step, mapping the full execution flow”
      ↩︎ Traces are the evidence every score rests on
      “Debugging, evaluation, and production monitoring all build on the evidence your traces capture.”
      ↩︎ Traces are the evidence every score rests on
      “Open the trace to see the full span tree (agent → LLM call → tool call).”
      ↩︎ Traces are the evidence every score rests on
    2. 2.
      “A scorer receives a Trace from either evaluate() or the monitoring service.”
      ↩︎ Traces are the evidence every score rests on
      “Parses the trace to extract specific fields and data that are used to assess quality”
      ↩︎ Traces are the evidence every score rests on
      “Each approach builds on the previous one, adding more complexity and control.”
      ↩︎ Four kinds of scorer, from least to most control
      “Customizing how the data from your app's trace is mapped to built-in LLM judges.”
      ↩︎ Four kinds of scorer, from least to most control
      “You can change the judge model by using the model argument in the judge definition.”
      ↩︎ Built-in LLM judges and the model behind them
      “Disabling Partner-powered AI features prevents the LLM judge from calling partner-powered models. You can still use LLM judges by providing your own model.”
      ↩︎ Built-in LLM judges and the model behind them
      “Guidelines judges, built-in judges that check whether responses pass or fail custom natural-language rules”
      ↩︎ Guidelines judges: pass/fail rules in plain language
      “Returns the quality assessment as Feedback to attach to the trace”
      ↩︎ Key concept
      “Programmatic and deterministic scorers that evaluate things like exact matching, format validation, and performance metrics.”
      ↩︎ Exam trap 1
      “Programmatic and deterministic scorers that evaluate things like exact matching, format validation, and performance metrics.”
      ↩︎ Prediction
      “need more control over grades or scores (not just pass/fail), or need to validate that your agent made appropriate decisions and performed operations correctly”
      ↩︎ Checkpoint
    3. 3.
      “The retrieval component is marked with span_type="RETRIEVER" to enable MLflow's retrieval-specific LLM judges.”
      ↩︎ Traces are the evidence every score rests on
      “Each trace corresponds to one row in your evaluation dataset and is annotated with feedback from each judge.”
      ↩︎ The mlflow.genai.evaluate() harness: direct and answer-sheet modes
      “To see the rationale for the Pass or Fail label, hover over the label.”
      ↩︎ Guidelines judges: pass/fail rules in plain language
      “The retrieval component is marked with span_type="RETRIEVER" to enable MLflow's retrieval-specific LLM judges.”
      ↩︎ Exam trap 3
    4. 4.
      “Before a release or PR to prevent quality regressions”
      ↩︎ The mlflow.genai.evaluate() harness: direct and answer-sheet modes
      “this mode enables you to reuse the scorers defined for offline evaluation in production monitoring since the resulting traces will be identical.”
      ↩︎ The mlflow.genai.evaluate() harness: direct and answer-sheet modes
      “If inputs and pre-computed outputs are provided, mlflow.genai.evaluate() constructs traces from the inputs and outputs.”
      ↩︎ The mlflow.genai.evaluate() harness: direct and answer-sheet modes
      “If you use an answer sheet with different traces than your production environment, you may need to re-write your scorer functions”
      ↩︎ The mlflow.genai.evaluate() harness: direct and answer-sheet modes
      “Stores results as traces with scorer feedback in the active MLflow experiment.”
      ↩︎ The mlflow.genai.evaluate() harness: direct and answer-sheet modes
      “App wrapper. Used for direct evaluation only.”
      ↩︎ Exam trap 2
      “Applies scorers or LLM judges to assess quality on pre-computed outputs or traces, creating feedback.”
      ↩︎ Prediction
      “reuse the scorers defined for offline evaluation in production monitoring since the resulting traces will be identical.”
      ↩︎ Checkpoint
    5. 5.
      “make_judge() accepts template variables to access the agent's inputs, outputs, expected outputs or behaviors, and even complete traces.”
      ↩︎ Four kinds of scorer, from least to most control
      “Custom variables like {{ question }} will throw validation errors”
      ↩︎ Four kinds of scorer, from least to most control
    6. 6.
      “Built-in LLM judges are predefined scorers that use Databricks-hosted LLMs to evaluate common quality dimensions”
      ↩︎ Built-in LLM judges and the model behind them
      “Does the response meet per-example natural language criteria?”
      ↩︎ Guidelines judges: pass/fail rules in plain language
      “Is the response correct as compared to the provided ground truth?”
      ↩︎ Exam trap 4
    7. 7.
      “expectations has several reserved keys that are used by built-in LLM judges: guidelines, expected_facts, and expected_response.”
      ↩︎ Built-in LLM judges and the model behind them

    Ready to test yourself?

    Practise the 5 questions on this subdomain.

    Spotted a mistake, or was something unclear? Tell us.