Getting started with evaluation

Feature set: Evaluations Contact our support for access.

Why an agent needs evaluation tests

A unit test asserts that a call returns one expected value. An agent’s reply cannot be asserted that way. The model decides which tools to call and how to word the reply, and a real model does not make the same decisions twice.

An evaluation test sends the agent a fixed set of messages, the eval cases, and lets evaluator components judge each interaction: the tool calls, the reply, or a criterion scored by a judge. It counts the results over all cases and requires a minimum pass rate.

This page writes an evaluation, as an integration test, for the order agent of an online shop. The test runs against the model the agent uses in production.

The agent under evaluation

The OrderAgent answers questions about orders. It has two tools: one looks for an order, the other issues a refund. Both delegate to an OrderService, which the agent receives through its constructor.

@Component(id = "order-agent")
public class OrderAgent extends Agent {

  public static final String GET_ORDER = "getOrder";
  public static final String ISSUE_REFUND = "issueRefund";

  private static final String SYSTEM_MESSAGE =
    """
    You are the support assistant of an online shop.
    Look an order up with getOrder before saying anything about it.
    Issue a refund with issueRefund only when the customer asks for one and the order
    has been delivered. Refund the full order total unless the customer names a smaller
    amount. Never invent an order, a status or an amount. Answer in one or two sentences.
    """;

  private final OrderService orders;

  public OrderAgent(OrderService orders) { (1)
    this.orders = orders;
  }

  public Effect<String> ask(String question) { (2)
    return effects().systemMessage(SYSTEM_MESSAGE).userMessage(question).thenReply();
  }

  @FunctionTool(
    name = GET_ORDER,
    description = "Look up an order by its id, for example o_42."
  )
  Order getOrder(String orderId) { (3)
    return orders.getOrder(orderId);
  }

  @FunctionTool(
    name = ISSUE_REFUND,
    description = "Refund an amount in cents to the customer of an order."
  )
  Refund issueRefund(String orderId, int amountCents) {
    return orders.issueRefund(orderId, amountCents);
  }
}
1 The OrderService is injected. Production provides a client for the real service through a DependencyProvider, the integration test provides a stub.
2 The command handler the evaluation calls. It takes the case’s command, here a String, and replies with a String. A handler may take its own type instead, such as a record.
3 The tools. Each tool sets its name from a constant, and the evaluators look tool calls up by the same constant.
/**
 * The order system the agent's tools call. Production provides a client for the real system, a
 * test provides a stub.
 */
public interface OrderService {
  /** The order, or a thrown {@link java.util.NoSuchElementException} when the id is unknown. */
  Order getOrder(String orderId);

  Refund issueRefund(String orderId, int amountCents);
}

Under test, a stub takes the place of the real order system. The sample’s StubOrderService keeps a map of orders that the test fills before the cases run, and throws for an unknown order id the way the real client would. The test registers the stub through a test specific DependencyProvider, as described in Custom dependency injection in tests.

The evaluators

An evaluator is a component that judges one interaction of an agent. Evaluators are part of the production code. You can also place an evaluator in the test sources and bind it to the agent in the test setup. The first one checks tools called by the agent. A message that names an order must lead to a getOrder call. A message without an order id must lead to no tool call at all.

/** The agent looks an order up when the message names one, and calls no tool otherwise. */
@Component(id = "order-lookup") (1)
public class OrderLookupEvaluator extends Evaluator {

  private static final Pattern ORDER_ID = Pattern.compile("o_\\d+");

  private final LedgerClient ledger;

  public OrderLookupEvaluator(LedgerClient ledger) { (2)
    this.ledger = ledger;
  }

  @Override
  public Effect evaluate(EvaluationContext context) {
    var subject = (Subject.Interaction) context.subject();
    var interaction = ledger.getInteraction(subject.interactionId()); (3)
    if (interaction.failed() && interaction.toolCalls().isEmpty()) {
      return effects().inconclusive("the interaction failed before any tool call"); (4)
    }
    var namesAnOrder = ORDER_ID.matcher(interaction.inputText()).find();
    var lookedUp = !interaction.toolCalls(OrderAgent.GET_ORDER).isEmpty();
    if (namesAnOrder && !lookedUp) {
      return effects()
        .complete(Evaluation.failed("no getOrder call for a message that names an order")); (5)
    }
    if (!namesAnOrder && !interaction.toolCalls().isEmpty()) {
      return effects()
        .complete(
          Evaluation.failed(
            "called " + interaction.toolNames() + " for a message without an order id"
          )
        );
    }
    return effects()
      .complete(
        Evaluation.passed(
          namesAnOrder ? "looked the order up" : "no tool for a message without an order id"
        )
      ); (6)
  }
}
1 The component id. The test binds the evaluator under this id, and the report names its results by it.
2 The ledger client is injected.
3 The interaction under evaluation, read from the ledger.
4 The evaluator is also bound for failed interactions. An interaction that failed before any tool call, for example because the model was unavailable, gives it nothing to judge, so the result is inconclusive rather than a failure of the agent.
5 The reason of a verdict is the detail the report prints.
6 A passed verdict.

The second one checks that a refund goes to an order the agent looked up first. An interaction without a refund gives it nothing to check.

/** A refund goes to an order the agent looked up first. */
@Component(id = "refund-policy")
public class RefundPolicyEvaluator extends Evaluator {

  private final LedgerClient ledger;

  public RefundPolicyEvaluator(LedgerClient ledger) {
    this.ledger = ledger;
  }

  @Override
  public Effect evaluate(EvaluationContext context) {
    var subject = (Subject.Interaction) context.subject();
    var interaction = ledger.getInteraction(subject.interactionId());
    var issued = interaction
      .toolCalls(OrderAgent.ISSUE_REFUND)
      .stream()
      .anyMatch(call -> !call.response().isEmpty()); (1)
    if (!issued) {
      return effects().notApplicable("no refund was issued"); (2)
    }
    if (interaction.toolCalls(OrderAgent.GET_ORDER).isEmpty()) {
      return effects().complete(Evaluation.failed("refunded without looking the order up"));
    }
    return effects().complete(Evaluation.passed("refunded an order the agent looked up"));
  }
}
1 A tool call in the ledger is the request the model made. A call that a guardrail denied has no response, so only a call with a response counts as a refund.
2 A not applicable result does not count against the case.

The sample has two more evaluators, which the test below also binds: ReplyGroundingEvaluator compares the reply with the order the tool returned, and a judge scores the reply against the criterion of its binding, that the reply answers the question with what the tools returned.

The test class

The evaluation test registers the stub as the agent’s OrderService, binds the evaluators to the agent, and leaves the model as configured in application.conf, so the agent and the judge answer with the model they use in production.

@EnabledIfSystemProperty(named = "eval", matches = "true") (1)
public class OrderAgentQualityIntegrationTest extends TestKitSupport {

  private final StubOrderService orders = new StubOrderService(); (2)

  @Override
  protected TestKit.Settings testKitSettings() {
    return TestKit.Settings.DEFAULT.withDependencyProvider( (3)
      dependencies()
    ).withAdditionalConfig( (4)
      """
      akka.javasdk.evaluation.evaluators {
        order-lookup.agents.order-agent { trigger = interaction, trigger-on-failure = true }
        refund-policy.agents.order-agent { trigger = interaction }
        reply-grounding.agents.order-agent { trigger = interaction }
        judge {
          criterion = "The reply answers the question with what the tools returned."
          threshold = 0.7
          agents.order-agent { trigger = interaction }
        }
      }
      """
    );
  }

  private DependencyProvider dependencies() {
    return new DependencyProvider() {
      @SuppressWarnings("unchecked")
      @Override
      public <T> T getDependency(Class<T> type) {
        if (type == OrderService.class) return (T) orders;
        throw new IllegalArgumentException("no such dependency: " + type);
      }
    };
  }

  @BeforeEach
  public void theOrders() {
    orders.reset(); (5)
    orders.addOrder(new Order("o_42", "shipped", 2599, "leave it with a neighbour"));
    orders.addOrder(new Order("o_9", "delivered", 4999, ""));
  }
1 The class runs only when the build sets the eval system property. Without it JUnit skips the class.
2 The stub the agent’s tools call.
3 The DependencyProvider that serves the stub. It replaces the one the service’s ServiceSetup creates.
4 The bindings. Each key is the component id of an evaluator, and agents.order-agent binds it to the agent. The judge entry also carries the criterion and the threshold the judge evaluator reads.
5 The orders the cases ask about. The stub is refilled before each test, so every test starts from the same orders.

The bindings are the entries Binding evaluators to agents describes, and a binding in application.conf applies in the test as well. To keep a production evaluator out of the test, disable its binding in the test configuration with enabled = false, one entry per production evaluator. The bindings belong to the TestKit, so every experiment in the test class runs with the same evaluators. Put experiments that need a different set of evaluators in another test class with its own testKitSettings(). A gate can rate one evaluator of the set, see Gating a judged batch.

The runner reads the bindings of the agent from the configuration the TestKit runs with and waits for one evaluation per bound evaluator. At agent(…​) it refuses a binding with a sampling-ratio below 1.0, because a sampled evaluator leaves cases without a verdict. It also refuses a binding to an evaluator id that no evaluator component of the service has. With trigger-on-failure = true the evaluator also judges an interaction that failed, for example when a tool threw. Without it, the runner does not expect the evaluator on a failed interaction.

An evaluator that records no evaluation within the evaluation timeout, 10 seconds unless the experiment sets another with evaluationTimeout(Duration), is inconclusive on that attempt. Raise the timeout for a judge that calls a real model, or for a durable evaluator with slow steps.

Run it with the property set and the model’s API key in the environment:

mvn verify -Deval=true

@EnabledIfSystemProperty is one way to keep an expensive test out of the regular build. Other options are a JUnit @Tag that the Failsafe groups filter selects, a Maven profile, or a class name outside the Failsafe include pattern.

The first case

An EvalCase describes one turn with the agent. The bound evaluators state what the agent must do with the command. The case does not, unless it carries an expected reply (see Cases with an expected reply).

static final EvalCase<String, Object> ORDER_STATUS = EvalCase.of(
  "order-status", (1)
  "Where is order o_42?" (2)
);

static final EvalCase<String, Object> FULL_REFUND = EvalCase.of(
  "full-refund",
  "Order o_9 arrived broken. I want my money back."
);

static final EvalCase<String, Object> GREETING = EvalCase.of("greeting", "hello?");

static final List<EvalCase<String, Object>> CURATED = List.of(
  ORDER_STATUS,
  FULL_REFUND,
  GREETING
);
1 The id names the case in the report.
2 The command the agent receives.

An experiment is a set of cases bound to an agent and a gate, run once for one report.

@Test
public void looksTheOrderUpBeforeAnswering() {
  var report = new ExperimentRunner(testKit)
    .cases(OrderCases.ORDER_STATUS) (1)
    .agent(OrderAgent::ask) (2)
    .run(); (3)

  assertThat(report.passed()).withFailMessage(report::render).isTrue(); (4)
}
1 The cases. One or several.
2 The agent’s command handler. The runner calls it through the component client in a new session per case.
3 Runs the cases, waits for the verdicts of the bound evaluators, and returns an EvalReport.
4 Without a gate the report passes only when every case passes. The rendered report is the failure message, so a failed case prints its evidence.

A single case against a real model is not a reliable check. The model may word the reply differently on another run, or call a tool it did not call before, and the case fails on that run. The next step runs a set of cases and requires a minimum pass rate over all of them instead. Running every case several times names the cases that do not hold on every run.

A batch behind a gate

Several cases run as one batch. A Gate decides what the batch must satisfy over all case results.

@Test
public void qualityGate() {
  var report = new ExperimentRunner(testKit)
    .cases(OrderCases.CURATED)
    .agent(OrderAgent::ask)
    .gate(
      Gate.passRateShouldBeAtLeast(0.9) (1)
        .and(Gate.passRateShouldBeAtLeast(OrderLookupEvaluator.class, 1.0)) (2)
        .and(Gate.targetShouldNotFail()) (3)
    )
    .run();

  assertThat(report.passed()).withFailMessage(report::render).isTrue();
}
1 At least 90% of the cases must pass.
2 The order-lookup evaluator must pass in every case where it reached a verdict.
3 No case may fail in the agent call. An unavailable model fails the gate rather than lowering the pass rate.

The gates are combined with and, so all three must hold.

A rendered report of this batch:

evaluation of 3 cases, 1 run: 3/3 attempts passed (100%)
gate: passed — pass rate 1.00 over 3 attempts (3 cases, 1 run), required 0.90; order-lookup rate 1.00 over 3 judged attempts, required 1.00; no target failures
  judge 3/3
  order-lookup 3/3
  refund-policy 1/1 (2 not applicable)
  reply-grounding 2/2 (1 not applicable)
spend: 7 model responses, 4310 tokens in, 212 out, 6120 ms in total, slowest full-refund run 1 at 2890 ms, over 3/3 attempts with a recorded interaction

The second line is the gate’s verdict, with the detail of each of the three gates. The indented lines are the pass counts per evaluator, with the attempts where the evaluator had nothing to check in brackets. The last line sums what the run spent. Reading the report explains every line.

Cases in a file

EvalCases reads cases from a JSON Lines file: one JSON object per line, with the id and the command of one case.

{"id":"order-status","command":"Where is order o_42?"}
{"id":"full-refund","command":"Order o_9 arrived broken. I want my money back."}
{"id":"greeting","command":"hello?"}
@Test
public void casesFromAFile() {
  var cases = EvalCases.readJsonLinesResource("eval/cases.jsonl", String.class); (1)

  var report = new ExperimentRunner(testKit).cases(cases).agent(OrderAgent::ask).run();

  assertThat(report.passed()).withFailMessage(report::render).isTrue();
  assertThat(report.results()).hasSize(3);
}
1 readJsonLinesResource(resource, commandType) reads a classpath resource, readJsonLines(path, commandType) a file. The command type is String.class for a handler that takes the user message.

For a handler that takes its own type, write command as the JSON of that type and read the file with that class. A line that is not a case stops the read with an IllegalArgumentException that names the source and the line.

Cases with an expected reply

When you know the correct reply of a case, give the case an expected reply. The runner compares each attempt’s reply with it and records the comparison as the expected result. The test code decides how the two replies are compared. The agent and the evaluators do not change.

{"id":"order-status","command":"Where is order o_42?","expected":"shipped"}
{"id":"full-refund","command":"Order o_9 arrived broken. I want my money back.","expected":"refunded"}
@Test
public void theReplyIsComparedWithTheExpectedReply() {
  var cases = EvalCases.readJsonLinesResource(
    "eval/graded-cases.jsonl",
    String.class,
    String.class (1)
  );

  var report = new ExperimentRunner(testKit)
    .cases(cases)
    .agent(OrderAgent::ask)
    .grade((expected, reply) -> (2)
      reply.toLowerCase(Locale.ROOT).contains(expected)
        ? Evaluation.passed("the reply says " + expected)
        : Evaluation.failed("the reply does not say " + expected))
    .gate(Gate.expectedShouldPass()) (3)
    .run();

  assertThat(report.passed()).withFailMessage(report::render).isTrue();
  assertThat(report.results().getFirst().describe()).contains(
    "PASS expected: the reply says shipped" (4)
  );
}
1 The reply type of the command handler. The reader decodes expected into it, and the compiler rejects an agent whose handler replies with another type. The reader without a reply type rejects a file containing expected. This prevents running cases with expected replies without comparing them.
2 The Grader. It receives the expected reply and the attempt reply, then returns an Evaluation. The evaluation contains the explanation printed in the report and an optional score. A grader that throws fails the result with the exception as the detail.
3 The gate on the comparison. See Gates.
4 The comparison is the expected result of the attempt, listed alongside verdicts from bound evaluators.

Without grade(…​) the runner compares the two replies with the Java equals method. A record defines it. A reply class without equals, or a record with an array component, never compares equal. Define equals on the reply type, or compare replies using a Grader.

When the command handler replies with a sealed interface and the expected reply is a subtype, pass type arguments to cases(…​). This sets the experiment reply type to the interface rather than the subtype: experimentRunner.<String, Reply>cases(EvalCase.of("refund", "I want my money back", new OpenRefund())).agent(Router::route).

Running the cases with a mocked model

The same cases run without an API key when a TestModelProvider takes the place of the model, see Testing agents. The replies are then deterministic, so such a run checks that the agent, the tools and the evaluators fit together, not how good the model is. Run it on every build, to catch a broken tool or evaluator before the real model is involved, and to test how the evaluators react to a known bad reply. The sample’s OrderAgentEvalIntegrationTest is the mocked variant of OrderAgentQualityIntegrationTest, with the same bindings:

@Override
protected TestKit.Settings testKitSettings() {
  return TestKit.Settings.DEFAULT.withDependencyProvider(dependencies())
    .withModelProvider(OrderAgent.class, orderModel) (1)
    .withModelProvider(OrderJudge.class, judgeModel)
    .withAdditionalConfig(
      """
      akka.javasdk.evaluation.evaluators {
        order-lookup.agents.order-agent { trigger = interaction, trigger-on-failure = true }
        refund-policy.agents.order-agent { trigger = interaction }
        reply-grounding.agents.order-agent { trigger = interaction }
        judge {
          criterion = "The reply answers the question with what the tools returned."
          threshold = 0.7
          agents.order-agent { trigger = interaction }
        }
      }
      """
    );
}

@BeforeEach
public void theModels() {
  MockedModels.scriptOrderAgent(orderModel); (2)
  MockedModels.scriptJudge(judgeModel);
}
1 A TestModelProvider per agent. The judge agent gets its own, so the judge evaluator runs without a key too.
2 The scripts are loaded before each test, because a test can override a script to produce a known bad reply.

The script of the order agent’s model behaves like a competent model: it looks an order up when the message names one, refunds a delivered order when asked for a refund, and refuses a message that is not about an order.

/** The order agent's model. The last matching script wins, so the general ones come first. */
static void scriptOrderAgent(TestModelProvider model) {
  model.reset();

  model.whenUserMessage(message -> true).reply(REFUSAL);

  model
    .whenUserMessage(message -> ORDER_ID.matcher(message.content()).find())
    .reply(message -> {
      var orderId = group(ORDER_ID, message.content(), 0);
      return new AiResponse(
        new ToolInvocationRequest(OrderAgent.GET_ORDER, "{\"orderId\":\"" + orderId + "\"}")
      );
    });

  // A tool result arrives without the question, so the script decides from the record it read:
  // a delivered order is refunded, any other order is reported.
  model
    .whenToolResult(result -> result.name().equals(OrderAgent.GET_ORDER))
    .thenReply(result -> {
      var orderId = group(RESULT_ID, result.content(), 1);
      var status = group(RESULT_STATUS, result.content(), 1);
      if (status.equals("delivered")) {
        var total = group(RESULT_TOTAL, result.content(), 1);
        return new AiResponse(
          new ToolInvocationRequest(
            OrderAgent.ISSUE_REFUND,
            "{\"orderId\":\"" + orderId + "\",\"amountCents\":" + total + "}"
          )
        );
      }
      return new AiResponse("Order " + orderId + " is " + status + ".");
    });

  model
    .whenToolResult(result -> result.name().equals(OrderAgent.ISSUE_REFUND))
    .thenReply(result -> {
      var cents = Integer.parseInt(group(REFUND_AMOUNT, result.content(), 1));
      return new AiResponse(
        String.format(
          Locale.ROOT,
          "I am sorry the order arrived broken. I have refunded %d.%02d to your card.",
          cents / 100,
          cents % 100
        )
      );
    });
}

The judge’s model answers with the JSON of the verdict record the judge agent returns, with a high score when the transcript shows a reply about an order:

/** The judge's model: a high score when the transcript shows a reply about an order. */
static void scriptJudge(TestModelProvider model) {
  model.reset();
  model
    .whenUserMessage(message -> true)
    .reply("{\"score\":0.3,\"reason\":\"does not answer the question\"}");
  model
    .whenUserMessage(message -> {
      var transcript = message.content();
      return (
        transcript.contains("Response: Order o_") ||
        transcript.contains("refunded") ||
        transcript.contains(REFUSAL)
      );
    })
    .reply("{\"score\":0.9,\"reason\":\"answers from what the tools returned\"}");
}

The cases and the experiments are the ones of the real model variant. Without a gate every case must pass, which fits a scripted model. Reading an attempt that did not pass shows a test of this class that scripts a bad reply and reads the failed case.

See also