CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 6 · Lesson 55/56

    Custom code-based scorers in MLflow: @scorer, Feedback and the Scorer class

    Use Databricks custom Scorers for evaluating agents and LLMs

    23 min read
    1.2% of exam
    5 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Write an @scorer function that declares only the inputs it needs (inputs, outputs, expectations or trace) and returns the right type for the check
    • Predict the metric name a scorer will produce from its function name, Scorer.name or Feedback.name
    • Iterate on a scorer against stored traces, score from span data and wrap a built-in LLM judge
    • Choose between letting a scorer's exception propagate and returning a Feedback with an error
    • Decide between the @scorer decorator and the Scorer class, given that only @scorer functions run under production monitoring

    Key concept

    Code-based scorer — A Python function you write that receives an MLflow trace, or the inputs, outputs and expectations taken from it, and returns a value or Feedback that MLflow attaches to that trace as a named metric. The same function can score evaluation runs in development and live traffic in production.

    1.Where code-based scorers fit

    A code-based scorer is a plain Python function that grades one trace of your agent. MLflow offers several kinds of scorer. Built-in judges, Guidelines judges and custom LLM judges all ask a language model for a verdict (Kinds of scorer: built-in judges, guidelines, custom judges, code scorers). A code-based scorer gives you the most control of any of them, because the grade comes from logic you wrote and can read line by line.

    That control matters most for deterministic checks. Exact matching, format validation and performance metrics such as latency have a single right answer, and the same output should get the same grade every time. Take a requirement that every response contain a valid JSON object with a fixed set of fields. A Guidelines judge would check a natural-language rule describing the structure, but an LLM still decides whether that rule passed. The built-in Correctness judge is also an LLM judge, and it compares the response with a labelled expected answer rather than validating a schema. The fit is a function decorated with @scorer that parses outputs and returns True or False. Making that function call an LLM and return a written critique would bring judgment back into a check that needs none.

    Code-based scorers also do more than heuristics. They let you control how trace data is mapped to a Databricks built-in LLM judge, and they let you grade with your own LLM instead of a Databricks-hosted judge. Every scorer, whatever its kind, follows the same cycle. It receives a trace from mlflow.genai.evaluate() or from the monitoring service, pulls out the fields it needs, runs its assessment and returns Feedback that is attached to the trace.

    Code-based scorers next to the LLM-based kinds
    ApproachWho decides the gradeTypical use
    Built-in judges (including Guidelines)A Databricks-hosted LLMCorrectness, RetrievalGroundedness, natural-language style rules
    Custom judgesAn LLM following your detailed criteriaDomain-specific criteria, numerical or categorical grades
    Code-based scorersYour Python logicExact matching, format validation, performance metrics

    Checkpoint 1 of 10· Match them up

    Match each kind of scorer to how it reaches its grade and what it is typically used for

    Tap a term, then the definition that fits it.

    Checkpoint 2 of 10· Exam question

    An evaluation team needs a check that confirms each agent response contains a syntactically valid JSON object matching a required schema — a deterministic pass/fail check that does not need any LLM judgment. Which approach fits this requirement, and what should it return?

    Sources12

    2.The @scorer signature: four optional inputs

    A scorer function can accept four keyword-only arguments, and you declare only the ones you need. MLflow passes the complete trace and also pulls out the fields most scorers want, so outputs alone is enough for a length check. The return annotation lists everything a scorer can hand back.

    Full signature of a @scorer function, with every input it can receivepython
    from mlflow.genai.scorers import scorer
    from typing import Optional, Any
    from mlflow.entities import Feedback
    
    @scorer
    def my_custom_scorer(
        *,  # All arguments are keyword-only
        inputs: Optional[dict[str, Any]],       # App's raw input, a dictionary of input argument names and values
        outputs: Optional[Any],                 # App's raw output
        expectations: Optional[dict[str, Any]], # Ground truth, a dictionary of label names and values
        trace: Optional[mlflow.entities.Trace]  # Complete trace with all spans and metadata
    ) -> Union[int, float, bool, str, Feedback, List[Feedback]]:
        # Your evaluation logic here
    What each input carries, and where it comes from
    ParameterContentsSource during evaluate()Source in production monitoring
    inputsThe request sent to your app, such as the user queryThe data argument, or parsed from the traceAlways parsed from the trace
    outputsThe app's response, such as generated text or tool callsThe data argument, or parsed from the traceAlways parsed from the trace
    expectationsGround truth or labels, such as an expected responseThe data argument, or parsed from the traceNot available
    traceThe full MLflow trace: every span, attribute and outputPassed as an mlflow.entities.TracePassed as an mlflow.entities.Trace

    Only trace shows how the app ran. inputs and outputs hold the request and the final response, and expectations holds labels. None of the three records how long a tool span took or which tools were called in between. A rule such as "flag runs where a tool span took over 2 seconds" therefore has to declare trace, then search its spans and read their start and end times. Switching to the Scorer class gains nothing here, because the trace reaches both styles the same way.

    Checkpoint 3 of 10· Check yourself

    Your team wants a code-based scorer that flags any agent run where a single tool span took longer than 2 seconds. How should the scorer get the timing data it needs?

    Checkpoint 4 of 10· Exam question

    A team is writing a custom scorer that must flag agent runs where a particular tool span took longer than 2 seconds, using the full execution trace rather than just the final input and output text. Which parameter should the scorer function declare to access this span-level timing information?

    Sources3

    3.Return types and how metric names are derived

    A scorer's return type sets how the result appears in the MLflow UI. Use a simple value for a single pass/fail or numeric result. Use a Feedback object when a reviewer also needs to know why.

    Return types and how the MLflow UI shows them
    Return typeUI displayUse case
    "yes"/"no"Pass/FailBinary evaluation
    True/FalseTrue/FalseBoolean checks
    int/floatNumeric valueScores, counts
    FeedbackValue + rationaleDetailed assessment
    List[Feedback]Multiple metricsMulti-aspect evaluation

    Feedback stores the score and the reason in separate fields. value holds the grade, which can be numeric, boolean, a string or another type. rationale holds the explanation shown next to it on the trace. Optional source and metadata fields record who or what made the assessment. If stakeholders need to see a 0.85 together with a short reason for it, return Feedback(value=0.85, rationale=...). A bare float has no field for a reason. Packing the score and the reason into one string loses the numeric value. A list of raw floats is not a valid return type at all: when one scorer reports several results, the list must contain Feedback objects.

    One scorer that reports three separately named metricspython
    @scorer
    def comprehensive_check(inputs, outputs):
        return [
            Feedback(name="relevance", value=True, rationale="Directly addresses query"),
            Feedback(name="tone", value="professional", rationale="Appropriate for audience"),
            Feedback(name="length", value=150, rationale="Word count within limits")
        ]

    Metric names follow one rule: if a Feedback.name is set, it wins. A primitive return value or an unnamed Feedback takes the function name under @scorer, or the name field under the Scorer class. So response_length returning an int appears as the metric response_length, while comprehensive_check above produces relevance, tone and length and never shows its own name. Every metric in an evaluation or monitoring run must have a distinct name. That is why each Feedback in a returned list needs its own name. Pick names that state the purpose, such as safety_check, because they become the column headers on your evaluation results and monitoring dashboards.

    Checkpoint 5 of 10· Check yourself

    A teammate's @scorer function quality_suite returns [Feedback(value=True, rationale="..."), Feedback(value=0.7, rationale="...")] and sets no name on either Feedback. What goes wrong, and what is the fix?

    Checkpoint 6 of 10· Exam question

    A team writes a custom scorer for a support agent and wants stakeholders reviewing evaluation runs to see not just a numeric score but also a short written reason for that score, attached to each trace. What should the @scorer-decorated function return to achieve this?

    Sources3

    4.Iterating against stored traces

    Running the whole app again for every small change to a scorer is slow and costs LLM calls. The development workflow avoids this by generating traces once and reusing them. mlflow.genai.evaluate() needs at least one scorer, so the first run uses a placeholder @scorer that returns 1. That run calls the app through predict_fn and leaves one trace per row of the evaluation dataset.

    Next, mlflow.search_traces(run_id=eval_results.run_id) returns those traces as a Pandas DataFrame. Pass that DataFrame to evaluate() as data and leave out predict_fn. MLflow then scores the stored traces without calling the app again. Edit the scorer, run it again and compare. Every result reflects only your change, because the app outputs stay fixed.

    Scoring precomputed traces: no predict_fn, so the app is not called againpython
    from mlflow.genai.scorers import scorer
    
    @scorer
    def response_length(outputs: str) -> int:
        # Example metric.
        # Implement your actual metric logic here.
        return len(outputs)
    
    # Note the lack of a predict_fn parameter.
    mlflow.genai.evaluate(
        data=generated_traces,
        scorers=[response_length],
    )

    Checkpoint 7 of 10· Fill the gap

    You are tuning a scorer and don't want to call the app again. Which value belongs in the blank so that evaluate() scores the traces you already generated?

    from mlflow.genai.scorers import scorer
    
    @scorer
    def response_length(outputs: str) -> int:
        # Example metric.
        # Implement your actual metric logic here.
        return len(outputs)
    
    # Note the lack of a predict_fn parameter.
    mlflow.genai.evaluate(
        data= ? ,
        scorers=[response_length],
    )

    Sources4

    5.Scoring from spans and wrapping a judge

    A scorer that reads span data declares trace and searches the trace for the span it cares about. The example below finds the first CHAT_MODEL span and computes its duration from start_time_ns and end_time_ns. It returns a yes/no Feedback whose rationale includes the measured time. For a tool-latency check you would search a different span type and set a different threshold, but the code has the same shape.

    Reading span timing from the trace to grade LLM latencypython
    @scorer
    def llm_response_time_good(trace: Trace) -> Feedback:
        # Search particular span type from the trace
        llm_span = trace.search_spans(span_type=SpanType.CHAT_MODEL)[0]
    
        response_time = (llm_span.end_time_ns - llm_span.start_time_ns) / 1e9 # convert to seconds
        max_duration = 5.0
        if response_time <= max_duration:
            return Feedback(
                value="yes",
                rationale=f"LLM response time {response_time:.2f}s is within the {max_duration}s limit."
            )
        else:
            return Feedback(
                value="no",
                rationale=f"LLM response time {response_time:.2f}s exceeds the {max_duration}s limit."
            )

    Wrapping a built-in judge solves a different problem: the judge expects one shape of input and your app produces another. Here the app's inputs is a chat history, {"messages": [...]}, but the relevance judge needs a single request. The wrapper walks the messages backwards to find the last user turn. It then passes that turn and the response to is_context_relevant and returns the judge's Feedback unchanged. The same pattern can post-process the judge's output instead, for example by renaming or reshaping its feedback.

    Pre-processing chat inputs before handing them to a built-in judgepython
    @scorer
    def is_message_relevant(inputs: dict[str, Any], outputs: str) -> Feedback:
        last_user_message_content = None
        if "messages" in inputs and isinstance(inputs["messages"], list):
            for message in reversed(inputs["messages"]):
                if message.get("role") == "user" and "content" in message:
                    last_user_message_content = message["content"]
                    break
    
        if not last_user_message_content:
            raise Exception("Could not extract the last user message from inputs to evaluate relevance.")
    
        # Call the `relevance_to_query judge. It will return a Feedback object.
        return is_context_relevant(
            request=last_user_message_content,
            context={"response": outputs},
        )

    Any scorer that reads expectations must cope with getting none. Offline, labels arrive through an expectations column in data, or through the trace field of a DataFrame returned by mlflow.search_traces(). In production, scorers run on live traffic that has no ground truth, and registered monitoring scorers never receive expectations (Judges that require ground truth (expectations)). A scorer meant for both settings should check that expectations is present before indexing into it, and fall back to a reference-free grade or report that it could not score.

    Checkpoint 8 of 10· Fill the gap

    The app receives a chat history, but the relevance judge needs a single request. Which value belongs in the blank so that the wrapper hands the judge what it expects?

    @scorer
    def is_message_relevant(inputs: dict[str, Any], outputs: str) -> Feedback:
        last_user_message_content = None
        if "messages" in inputs and isinstance(inputs["messages"], list):
            for message in reversed(inputs["messages"]):
                if message.get("role") == "user" and "content" in message:
                    last_user_message_content = message["content"]
                    break
    
        if not last_user_message_content:
            raise Exception("Could not extract the last user message from inputs to evaluate relevance.")
    
        # Call the `relevance_to_query judge. It will return a Feedback object.
        return is_context_relevant(
            request= ? ,
            context={"response": outputs},
        )

    Sources53

    6.When a scorer throws

    A scorer error on one trace does not stop the run. MLflow records the error details for that trace and keeps scoring the others. The recommended approach is to let exceptions propagate. MLflow catches the exception and creates a Feedback with value set to None and error holding the exception, its message and the stack trace. Open that row in the evaluation results to read the details. The raise Exception(...) in the relevance wrapper relies on this behaviour.

    Handle exceptions yourself when the default message isn't specific enough. Return a Feedback with no value and an error. That field accepts either a Python exception object passed directly, or an AssessmentError with your own error_code and error_message. The JSON validator below does both. A missing required field becomes a structured MISSING_REQUIRED_FIELDS error, and a parse failure passes the JSONDecodeError straight through.

    Explicit error handling: a structured AssessmentError and a passed-through exceptionpython
            if missing:
                return Feedback(
                    error=AssessmentError(
                        error_code="MISSING_REQUIRED_FIELDS",
                        error_message=f"Missing required fields: {missing}",
                    ),
                )
    
            return Feedback(
                value=True,
                rationale="Valid JSON with all required fields"
            )
    
        except json.JSONDecodeError as e:
            return Feedback(error=e)  # Can pass exception object directly to the error parameter

    Checkpoint 9 of 10· Fill the gap

    This validator handles a JSON parse failure itself instead of letting the exception propagate. Which keyword argument belongs in the blank so that MLflow records the failure as an error on that trace?

            if missing:
                return Feedback(
                    error=AssessmentError(
                        error_code="MISSING_REQUIRED_FIELDS",
                        error_message=f"Missing required fields: {missing}",
                    ),
                )
    
            return Feedback(
                value=True,
                rationale="Valid JSON with all required fields"
            )
    
        except json.JSONDecodeError as e:
            return Feedback( ? =e)  # Can pass exception object directly to the error parameter

    Sources3

    7.@scorer versus the Scorer class, and running in production

    Subclass Scorer when a scorer needs internal state, complex initialization or configurable fields. Scorer is a Pydantic object. You declare extra fields on the class, read them in __call__, and must set name because it becomes the metric name. Any state must live in instance attributes created in __init__. A mutable class attribute such as results = [] is shared by every instance of the scorer.

    A Scorer subclass with a mandatory name and extra Pydantic fieldspython
    from mlflow.genai.scorers import Scorer
    from mlflow.entities import Feedback
    from typing import Optional
    
    # Scorer class is a Pydantic object
    class CustomScorer(Scorer):
        # The `name` field is mandatory
        name: str = "response_quality"
        # Define additional fields
        my_custom_field_1: int = 50
        my_custom_field_2: Optional[list[str]] = None
    
        # Override the __call__ method to implement the scorer logic
        def __call__(self, outputs: str) -> Feedback:
            # Your logic here
            return Feedback(
                value=True,
                rationale="Response meets all quality criteria"
            )

    The decorator is the default because of production. Monitoring runs built-in LLM judges and @scorer functions on a sample of live traces (Agent Monitoring: scheduled scorers on production traces), and it does not run Scorer subclasses. If you need state in production, write an @scorer function and manage that state inside the function body. There is a second condition. The monitoring service serializes the function's code to run it remotely, and that serialization requires the notebook environment. So the function must be defined and registered from a Databricks notebook.

    Because the function runs remotely, it can't assume anything from the notebook session that defined it. dbutils is not available in the scorer runtime by default. A scorer that needs a secret, such as an API key for its own LLM endpoint, imports dbutils from databricks.sdk.runtime inside the function body. The same code works in development evaluation and production monitoring. Once the scorer is written, register() and start() with a ScorerSamplingConfig deploy it.

    A production-ready @scorer: secret access imported inside the body, then registered and startedpython
    @scorer
    def custom_llm_scorer(trace: Trace) -> Feedback:
        # Explicitly import dbutils to access secrets
        from databricks.sdk.runtime import dbutils
    
        # Retrieve your API key from Databricks secrets
        api_key = dbutils.secrets.get(scope='my-scope', key='api-key')
    
        # Use the API key to call your custom LLM endpoint
        # ... your custom evaluation logic here ...
    
        return Feedback(
            value="yes",
            rationale="Evaluation completed using custom endpoint"
        )
    
    # Register and start the scorer
    custom_llm_scorer.register()
    custom_llm_scorer.start(sampling_config = ScorerSamplingConfig(sample_rate=1))
    Choosing the definition style
    ApproachUse whenProduction monitoring
    @scorer decoratorMost cases; the recommended starting pointSupported, when defined and registered from a Databricks notebook
    Scorer classStateful scorers, complex initialization, or Pydantic fieldsNot supported

    Checkpoint 10 of 10· Fill the gap

    This scorer will run remotely under production monitoring and needs an API key from Databricks secrets. Which module belongs in the blank so that dbutils is available inside the scorer runtime?

    @scorer
    def custom_llm_scorer(trace: Trace) -> Feedback:
        # Explicitly import dbutils to access secrets
        from  ?  import dbutils
    
        # Retrieve your API key from Databricks secrets
        api_key = dbutils.secrets.get(scope='my-scope', key='api-key')
    
        # Use the API key to call your custom LLM endpoint
        # ... your custom evaluation logic here ...
    
        return Feedback(
            value="yes",
            rationale="Evaluation completed using custom endpoint"
        )
    
    # Register and start the scorer
    custom_llm_scorer.register()
    custom_llm_scorer.start(sampling_config = ScorerSamplingConfig(sample_rate=1))

    Sources32

    Practise it for real

    Develop a code-based scorer against stored traces without calling your app again on each iteration

    1. 1.Define a small evaluation dataset of inputs rows and a placeholder @scorer that returns 1, then run mlflow.genai.evaluate(data=eval_dataset, predict_fn=sample_app, scorers=[placeholder_metric]).

      Why: evaluate() needs at least one scorer, and this run calls the app to produce the traces you will reuse.

      You should see: One trace per dataset row in the experiment, with the app's reply in the Response column.

    2. 2.Store the traces with generated_traces = mlflow.search_traces(run_id=eval_results.run_id).

      Why: The DataFrame becomes a fixed input, so later runs reflect only your scorer changes.

      You should see: A Pandas DataFrame with one row per trace.

    3. 3.Write a response_length scorer that declares only outputs and run mlflow.genai.evaluate(data=generated_traces, scorers=[response_length]) with no predict_fn.

      Why: Without predict_fn, MLflow scores the stored traces and does not call the app.

      You should see: A numeric metric named response_length on every trace.

    4. 4.Add llm_response_time_good, which declares trace and returns a yes/no Feedback, and evaluate it on the same traces.

      Why: It reads span timing, which only the trace carries.

      You should see: A Pass/Fail-style result per trace, with a rationale stating the measured response time.

    Stuck? Get a nudge

    If a result shows value None, open the row to see the error. An exception your scorer let propagate is recorded there rather than stopping the run.

    Sources

    (5)

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

    1. 1.
      “Programmatic and deterministic scorers that evaluate things like exact matching, format validation, and performance metrics.”
      ↩︎ Where code-based scorers fit
      “Guidelines judges, built-in judges that check whether responses pass or fail custom natural-language rules”
      ↩︎ Where code-based scorers fit
      “Returns the quality assessment as Feedback to attach to the trace”
      ↩︎ Where code-based scorers fit
    2. 2.
      “Customize how trace data is mapped to a Databricks built-in LLM judge.”
      ↩︎ Where code-based scorers fit
      “The monitoring service serializes the function code for remote execution, and this serialization requires the notebook environment.”
      ↩︎ @scorer versus the Scorer class, and running in production
      “If you need stateful scorers in production, use the @scorer decorator and manage state inside the function body.”
      ↩︎ @scorer versus the Scorer class, and running in production
      “You can use the same code-based scorer for evaluation in development and monitoring in production.”
      ↩︎ Key concept
      “Production monitoring supports built-in LLM judges and @scorer-decorated functions.”
      ↩︎ Exam trap 1
      “Class-based Scorer subclasses are not supported for production monitoring.”
      ↩︎ Prediction
    3. 3.
      “All input arguments are optional, so declare only what your scorer needs”
      ↩︎ The @scorer signature: four optional inputs
      “The complete MLflow trace including all spans, allowing analysis of intermediate steps, latency, tool usage, and more.”
      ↩︎ The @scorer signature: four optional inputs
      “Return a Feedback object or list of Feedback objects for detailed assessments with scores, rationales, and metadata.”
      ↩︎ Return types and how metric names are derived
      “If the scorer returns one or more Feedback objects, then Feedback.name fields take precedence, if specified.”
      ↩︎ Return types and how metric names are derived
      “For evaluation and monitoring, all metrics must have distinct names.”
      ↩︎ Return types and how metric names are derived
      “Registered scorers for production monitoring always parse the inputs and outputs parameters from the trace. expectations is not available.”
      ↩︎ Scoring from spans and wrapping a judge
      “Let exceptions propagate (recommended) so that MLflow can capture error messages for you.”
      ↩︎ When a scorer throws
      “When a scorer encounters an error for a trace, MLflow can capture error details for that trace and then continue executing gracefully.”
      ↩︎ When a scorer throws
      “The Scorer class is a Pydantic object, so you can define additional fields and use them in the __call__ method.”
      ↩︎ @scorer versus the Scorer class, and running in production
      “By default, dbutils isn't available in the scorer runtime environment.”
      ↩︎ @scorer versus the Scorer class, and running in production
      “Registered scorers for production monitoring always parse the inputs and outputs parameters from the trace. expectations is not available.”
      ↩︎ Exam trap 2
      “Let exceptions propagate (recommended) so that MLflow can capture error messages for you.”
      ↩︎ Exam trap 3
      “For evaluation and monitoring, all metrics must have distinct names.”
      ↩︎ Exam trap 4
      “The complete MLflow trace including all spans, allowing analysis of intermediate steps, latency, tool usage, and more.”
      ↩︎ Exam trap 5
      “trace: The complete MLflow trace including all spans, allowing analysis of intermediate steps, latency, tool usage, and more.”
      ↩︎ Checkpoint
      “If a scorer returns List[Feedback], then each Feedback in the List must have a distinct name.”
      ↩︎ Checkpoint
    4. 4.
      “Since evaluate() requires at least one scorer, define a placeholder scorer for this initial trace generation”
      ↩︎ Iterating against stored traces
      “This allows you to quickly iterate on your metric without having to re-run your app.”
      ↩︎ Iterating against stored traces
    5. 5.
      “Create a custom scorer that wraps MLflow's built-in LLM judges. Use this to preprocess trace data for the judge or post-process its feedback.”
      ↩︎ Scoring from spans and wrapping a judge
      “If you intend to use the same scorer for both offline and online evaluation, design it to handle expectations gracefully”
      ↩︎ Scoring from spans and wrapping a judge

    Ready to test yourself?

    Practise the 6 questions on this subdomain.

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