Evaluating task results

New to Akka? Start here:

Use the Spec-first hello agent guide to use your AI assistant for implementing a simple agentic service, running it locally and interacting with it.

Overview

When a coordinator task completes, the answer should be checked. This part adds an evaluator that the runtime triggers after each interaction of the coordinator. When the interaction completed the task, the evaluator asks a judge agent whether the answer addresses the original request and respects the user’s preferences, and records the verdict in the ledger.

In this part of the guide you will:

  • Add a judge agent.

  • Add an evaluator component that calls the judge, and bind it to the coordinator.

Prerequisites

Use your AI harness to set up your env, or install the following yourself:

Judge agent

The judge follows the pattern called "LLM as judge": an agent (AI model) evaluates the result produced by other agents. The judge looks at the original request, the user’s preferences and the produced answer, and returns a typed verdict. The judge keeps no session memory, so each evaluation starts from a clean context.

Add a new file EvaluatorAgent.java to src/main/java/com/example/application/

import akka.javasdk.agent.Agent;
import akka.javasdk.agent.MemoryProvider;
import akka.javasdk.annotations.Component;
import java.util.List;

@Component(
  id = "evaluator-agent",
  name = "Evaluator Agent",
  description = """
  An agent that acts as a judge of the quality of AI responses. \
  It assesses whether the final answer appropriately addresses the original request \
  and respects the user's preferences.\
  """
)
public class EvaluatorAgent extends Agent {

  public record EvaluationRequest(
    String originalRequest,
    List<String> preferences,
    String finalAnswer
  ) {}

  public record Result(String explanation, String label) {}

  private static final String SYSTEM_MESSAGE =
    """
    You are an evaluator agent that acts as a judge. Your job is to evaluate
    the quality and appropriateness of AI-generated responses.

    The request comes with the user's preferences. Your evaluation should focus on:
    1. Whether the final answer appropriately addresses the original question
    2. Whether the answer respects and aligns with the user's preferences
    3. The overall quality, relevance, and helpfulness of the response

    A response is "Incorrect" if it meets ANY of the following failure conditions:
    - poor response with significant issues or minor preference violations
    - unacceptable response that fails to address the question or violates preferences

    A response is "Correct" if it:
    - fully addresses the question and respects all stated preferences
    - good response with minor issues but respects preferences

    IMPORTANT:
    - Any violations of user preferences should result in an Incorrect evaluation since
      respecting user preferences is the most important criteria

    Your response must be a single JSON object with the following fields:
    - "explanation": Specific feedback on what works well or deviations from preferences.
    - "label": A string, either "Correct" or "Incorrect".
    """.stripIndent();

  public Effect<Result> evaluate(EvaluationRequest request) {
    var preferences = request.preferences().isEmpty()
      ? "(none)"
      : String.join("\n", request.preferences().stream().map(p -> "- " + p).toList());
    var prompt =
      """
      ORIGINAL REQUEST:
      %s

      USER PREFERENCES:
      %s

      FINAL ANSWER TO EVALUATE:
      %s

      Please evaluate the final answer against the original request and the preferences.
      """.formatted(request.originalRequest(), preferences, request.finalAnswer());

    return effects()
      .systemMessage(SYSTEM_MESSAGE)
      .memory(MemoryProvider.none())
      .userMessage(prompt)
      .responseConformsTo(Result.class)
      .thenReply();
  }
}

The judge is a request-based Agent, not an AutonomousAgent: it does a single model call per evaluation and returns a typed result. There is no iteration loop and no multi-agent coordination, so an ordinary agent is the lighter choice.

Evaluator

An Evaluator is a component that the runtime triggers for the interactions of the agents it is bound to. The coordinator records one interaction per model call, and the interaction that completes the task carries a complete_task tool call. The evaluator reads the interaction from the ledger. When the interaction completed the task, the evaluator fetches the task result and the user’s preferences, and asks the judge.

Add a new file ActivityEvaluator.java to src/main/java/com/example/application/

import akka.javasdk.agent.task.TaskStatus;
import akka.javasdk.annotations.Component;
import akka.javasdk.client.ComponentClient;
import akka.javasdk.evaluation.Evaluation;
import akka.javasdk.evaluation.EvaluationContext;
import akka.javasdk.evaluation.Evaluator;
import akka.javasdk.evaluation.Subject;
import akka.javasdk.ledger.LedgerClient;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Judges the answer of a completed activity task against the task instructions and the user's
 * preferences, with the {@link EvaluatorAgent} as the judge.
 */
@Component(id = "activity-evaluator") (1)
public class ActivityEvaluator extends Evaluator {

  private static final Logger logger = LoggerFactory.getLogger(ActivityEvaluator.class);

  private final ComponentClient componentClient;
  private final LedgerClient ledger;

  public ActivityEvaluator(ComponentClient componentClient, LedgerClient ledger) {
    this.componentClient = componentClient;
    this.ledger = ledger;
  }

  @Override
  public Effect evaluate(EvaluationContext context) {
    var subject = (Subject.Interaction) context.subject();
    var interaction = ledger.getInteraction(subject.interactionId()); (2)
    if (
      interaction.taskContext().isEmpty() || interaction.toolCalls("complete_task").isEmpty()
    ) {
      return effects()
        .notApplicable("the coordinator did not complete the task in this interaction"); (3)
    }

    var taskId = interaction.taskContext().get().taskId();
    var task = componentClient.forTask(taskId).get(ActivityTasks.SUGGEST_ACTIVITIES); (4)
    if (task.status() != TaskStatus.COMPLETED || task.result().isEmpty()) {
      return effects()
        .inconclusive("task [" + taskId + "] is " + task.status() + " without a result");
    }

    var userId = task
      .instructions()
      .lines()
      .findFirst()
      .orElse("")
      .replace("User:", "")
      .trim();
    var preferences = componentClient
      .forEventSourcedEntity(userId)
      .method(PreferencesEntity::getPreferences)
      .invoke(); (5)

    var judgement = componentClient
      .forAgent()
      .inSession(context.evaluationId()) (6)
      .method(EvaluatorAgent::evaluate)
      .invoke(
        new EvaluatorAgent.EvaluationRequest(
          task.instructions(),
          preferences.entries(),
          task.result().get()
        )
      );

    logger.info(
      "Judge says [{}] for task [{}]: {}",
      judgement.label(),
      taskId,
      judgement.explanation()
    );
    return switch (judgement.label().toLowerCase(Locale.ROOT)) { (7)
      case "correct" -> effects().complete(verdict(true, judgement, taskId));
      case "incorrect" -> effects().complete(verdict(false, judgement, taskId));
      default -> effects().inconclusive("unknown judge label [" + judgement.label() + "]");
    };
  }

  private static Evaluation verdict(
    boolean passed,
    EvaluatorAgent.Result judgement,
    String taskId
  ) {
    return Evaluation.of(passed, judgement.explanation())
      .withLabel(judgement.label())
      .withAttribute("taskId", taskId);
  }
}
1 An evaluator is a component with a @Component id. The id is how the configuration refers to it.
2 The interaction under evaluation, read from the ledger with the injected LedgerClient.
3 An interaction that did not complete the task, for example one that delegated to a worker, gives the evaluator nothing to judge. The evaluation ends as not applicable.
4 The task snapshot, for the instructions and the accepted result. A task that is not completed, for example because a task rule rejected the result, leaves the evaluation inconclusive.
5 The user’s preferences, read from the PreferencesEntity with the user id from the User: <userId> header of the instructions.
6 The judge runs in a session of its own, named after the evaluation.
7 The label of the judge decides the recorded Evaluation. A label the evaluator does not know leaves the evaluation inconclusive.

Bind the evaluator to the coordinator in src/main/resources/application.conf:

evaluation.evaluators {
  activity-evaluator.agents.activity-coordinator { trigger = interaction }
}

The runtime runs the evaluator in the background after each interaction of the coordinator, so it does not delay the answer. The verdicts are recorded in the ledger and flow into the metrics and traces produced by the runtime, so dashboards and alerting can pick them up without any further wiring.

Do not bind the evaluator to the judge agent, and give the judge no @AgentRole that a * binding matches. The evaluator’s call to the judge is an interaction of the judge, which would trigger the evaluator again, without end.

Running the service

Start your service locally:

mvn compile exec:java

Ask for activities:

curl -i -XPOST --location "http://localhost:9000/activities/alice" \
  --header "Content-Type: application/json" \
  --data '{"message": "I am in Madrid. What should I do? Beware of the weather."}'

Retrieve the suggestion (use the task id from the response):

curl http://localhost:9000/activities/alice/{taskId}

Add a preference that creates a tension with the suggestion:

curl -i localhost:9000/preferences/alice \
  --header "Content-Type: application/json" \
  -XPOST \
  --data '{
    "preference": "I dislike outdoor activities."
  }'

Submit the same request again. The ActivityAgent reads the preference, so the coordinator now produces a different answer. The evaluator reads the same preference and asks the judge whether the answer respects it. The evaluator logs each verdict, so the verdict shows up in the service log. The evaluations of the coordinator’s interactions are also in the ledger, see The ledger client.

Next steps

Congratulations, you have completed the tour of building a multi-agent system. Now you can take your Akka skills to the next level: