Evaluator-Optimizer with Spring AI: One Model Writes, Another Critiques
Anyone who writes for a living knows the rhythm of revision. You draft something, reread it with fresh eyes, notice what is weak, and rewrite. The second draft is almost always better than the first, and the reason is not talent. It is the separation between producing a text and judging it. When the same mind does both at once, it tends to accept its own first answer.
The evaluator-optimizer pattern applies that rhythm to LLM systems. One model generates a solution. A second evaluation step judges it against explicit criteria and returns feedback. If the solution does not pass, the feedback goes back to the generator, and the loop continues until the evaluator accepts the result. Anthropic describes this workflow in its research on building effective agents, and the sample in the spring-ai-examples repository implements it with Spring AI.
This article walks through that sample: how the loop is built, what the prompts ask each model to do, and where the code needs guardrails before it is safe to run unattended. Some of those guardrails are missing from the sample, and I point them out, because the loop as written has no stopping limit.
Where the pattern fits
Anthropic's taxonomy separates workflows, where code decides the control flow, from agents, where the model decides its next action. Evaluator-optimizer is a workflow. The loop structure is fixed: generate, evaluate, and either return or retry. What changes from run to run is the content, and how many times the loop turns.
The pattern earns its cost when three conditions hold. First, you have criteria for what a good answer looks like, and you can state them in a prompt. Second, a critique can make the next attempt measurably better. Third, the first attempt is often close but not quite right. Translation with nuance, code that must meet a specification, and drafts that must follow a style guide all fit that profile. A simple factual question does not, because there is nothing for a critic to improve.
It is also a different shape from the other patterns in this series. Parallelization splits independent work and merges it. Routing picks one specialist. Orchestrator-workers plans subtasks at runtime. Evaluator-optimizer repeats the same work with feedback, which makes it the only one of the five that revisits its own output.
The sample task
The sample asks the model to implement a stack in Java with three operations: push, pop, and getMin, where all operations must run in O(1) time. The task also sets two style rules: inner fields must be private, and any use of a field must be prefixed with this..
The task is small, but it has the properties that make the pattern interesting. The O(1) requirement is easy to violate by accident: a naive getMin that scans the stack is correct but too slow. The style rules are easy to forget on a second draft. A critic that checks both is more useful than one that only checks that the code compiles.
The records
The pattern is described by three records in EvaluatorOptimizer:
public static record Generation(String thoughts, String response) { } public static record EvaluationResponse(Evaluation evaluation, String feedback) { public enum Evaluation { PASS, NEEDS_IMPROVEMENT, FAIL } } public static record RefinedResponse(String solution, List<Generation> chainOfThought) { } Generation is what the generator returns: a short statement of its approach and the proposed solution. EvaluationResponse is what the evaluator returns: a verdict from a fixed set of three values, and feedback in prose. RefinedResponse is what the caller receives: the final solution and the full history of generations, so you can see how the solution evolved.
The enum matters more than it looks. Because the verdict is a closed set, the code can branch on it. The loop in this sample only stops on PASS. NEEDS_IMPROVEMENT and FAIL both send the work back for another round, which is a reasonable choice for a demo but one you should revisit in production, since a FAIL often means the approach itself is wrong, not that it needs polishing.
The generator prompt
The generator prompt is unusual because it is almost entirely about format. Before it describes the task, it asks for a single line of valid JSON, with every newline and quote escaped:
Your response must be a SINGLE LINE of valid JSON with NO LINE BREAKS except those explicitly escaped with \n. {"thoughts":"Brief description here","response":"public class Example {\n // Code here\n}"} This is a practical lesson. Code contains quotes, backslashes, and line breaks, and asking a model to put it inside a JSON string is a reliable source of malformed output. The prompt tries to prevent that with rules and an example. The rules help, but they are not a guarantee. The sample depends on Spring AI's structured output to parse the result, so a malformed response fails the whole run. The fix is not a better prompt alone. It is a retry on parse failure, which the sample does not have.
The generator prompt also tells the model to reflect on feedback from earlier rounds. That instruction is what turns a single call into a refinement step. Without it, each round would be a fresh attempt that ignores what went wrong before.
The evaluator prompt
The evaluator prompt is shorter, and it sets the criteria explicitly:
Evaluate this code implementation for correctness, time complexity, and best practices. Ensure the code have proper javadoc documentation. Respond with EXACTLY this JSON format on a single line: {"evaluation":"PASS, NEEDS_IMPROVEMENT, or FAIL", "feedback":"Your feedback here"} Use "PASS" only if all criteria are met with no improvements needed. The criteria are concrete: correctness, time complexity, best practices, and Javadoc. A vague instruction such as "make sure it's good" gives the critic nothing to check, and its feedback becomes generic. The line "Use PASS only if all criteria are met" pushes the evaluator toward strictness, which matters because a lenient critic ends the loop too early.
This prompt is written for code. Change the criteria and you change the pattern's application. For a translation, the criteria would be fidelity, register, and idiom. For a summary, they would be coverage and length. The structure of the loop does not change; the evaluator's checklist does.
The loop
The core of the pattern is a short recursive method:
private RefinedResponse loop(String task, String context, List<String> memory, List<Generation> chainOfThought) { Generation generation = generate(task, context); memory.add(generation.response()); chainOfThought.add(generation); EvaluationResponse evaluationResponse = evalute(generation.response(), task); if (evaluationResponse.evaluation().equals(EvaluationResponse.Evaluation.PASS)) { return new RefinedResponse(generation.response(), chainOfThought); } StringBuilder newContext = new StringBuilder(); newContext.append("Previous attempts:"); for (String m : memory) { newContext.append("\n- ").append(m); } newContext.append("\nFeedback: ").append(evaluationResponse.feedback()); return loop(task, newContext.toString(), memory, chainOfThought); } Read it step by step. The generator produces a solution, which is recorded in memory and chainOfThought. The evaluator judges it. If the verdict is PASS, the method returns. Otherwise it builds a new context that lists every previous attempt and the latest feedback, and calls itself with that context.
The design choice to keep every previous attempt in the context is worth thinking about. It lets the generator see what it already tried, which helps it avoid repeating a mistake. It also means the prompt grows on every round. A third attempt carries two previous solutions and two rounds of feedback. For code, that growth is manageable. For a long document, it can become expensive quickly.
The missing stopping rule
This is the most important gap in the sample, and I would not run it without fixing it. The loop has no iteration limit. It only stops when the evaluator returns PASS. If the evaluator never passes the solution, because the criteria are too strict, or the generator cannot satisfy them, or the evaluator keeps finding something new to criticize, the recursion never ends. The most likely outcome is either an unbounded number of model calls or a StackOverflowError when the recursion gets deep enough.
A fix is simple. Pass a round counter, and stop after a fixed number of rounds:
private static final int MAX_ROUNDS = 4; public RefinedResponse loop(String task) { List<String> memory = new ArrayList<>(); List<Generation> chainOfThought = new ArrayList<>(); String context = ""; for (int round = 1; round <= MAX_ROUNDS; round++) { Generation generation = generate(task, context); memory.add(generation.response()); chainOfThought.add(generation); EvaluationResponse evaluation = evalute(generation.response(), task); if (evaluation.evaluation() == EvaluationResponse.Evaluation.PASS) { return new RefinedResponse(generation.response(), chainOfThought); } context = buildContext(memory, evaluation.feedback()); } throw new IllegalStateException("No passing solution after " + MAX_ROUNDS + " rounds"); } A loop also makes the control flow easier to read and easier to test than recursion. Whether you return the best attempt so far or throw an error when the budget runs out is a product decision. The important part is that the decision exists.
Other gaps
Three more issues are worth knowing about before you build on the sample.
The generator and the evaluator use the same ChatClient, so they are the same model. A model judging its own output shares its blind spots, and it may approve a solution it would have rejected from a different viewpoint. For high-stakes work, use a different model or a different prompt persona for the evaluator, and test whether the critic catches what the generator misses.
The FAIL verdict is treated like NEEDS_IMPROVEMENT. The evaluator is asked to say FAIL, but the code never uses that signal. In practice, FAIL should mean the approach is unsalvageable: stop, or switch strategy, instead of asking for polish.
The sample has no protection against a parse failure. Both entity(Generation.class) and entity(EvaluationResponse.class) throw if the model returns malformed JSON. Add a retry for those calls, separate from the refinement loop, so one bad response does not end the run.
The sample prints every generation and every evaluation to standard output. That is useful while you learn the loop and noisy in production. Replace the prints with a logger that records the round number, the verdict, and the length of the feedback. Log the full code only in a debug mode.
Testing the loop
The loop is straightforward to test, because EvaluatorOptimizer takes a ChatClient in its constructor. Use a stub client that returns a sequence of canned generations and evaluations. A good test set covers four cases:
- The first generation passes, so the loop returns after one round.
- The first evaluation fails and the second passes, so the final solution is the second generation and the chain of thought has two entries.
- The evaluator never passes, so the loop stops at the round limit and does not recurse forever.
- The evaluator returns malformed JSON, so the retry logic is exercised.
Testing the prompts is harder, and it is where most of the quality comes from. Keep a small set of tasks with clear acceptance criteria. Run the loop on each task, read the feedback the evaluator gives, and check whether the feedback is specific enough to act on. If the feedback is vague, tighten the evaluator's criteria before changing anything else.
When to choose this pattern
I use three questions. Can I write down what a good result looks like, in terms a critic can check? If not, the evaluator will be guessing. Does a second pass measurably improve the result? If the first answer is usually good enough, the extra calls are waste. Can I afford several rounds of latency and tokens, and can I bound them? If the answer to the last question is no, use a single well-written prompt and a cheaper check.
The pattern is also a good place to add a human. The evaluator can flag a solution for review when it reaches the round limit, instead of failing silently. That combines automated refinement with a person's judgment on the cases the loop cannot settle.
Running the sample
To run the sample you need Java 17 or later and a configured model. The project includes properties for OpenAI, Anthropic, and Ollama. The sample configures gpt-4o for OpenAI, so set that key, or change the properties to the provider you use. Start the application with the Maven wrapper. The console shows each generation and each evaluation, and the final output prints the solution and the chain of thought.
Watch the first few rounds closely. You will see the evaluator's feedback become more specific as the generator fixes earlier problems, and you will also see the prompt size grow. Both observations are the pattern working as intended, and both are the reason the round limit matters.
Key takeaways
- Evaluator-optimizer separates generating from judging, and loops feedback back into the generator until the evaluator accepts the result.
- The pattern is worth its cost when criteria are explicit, a critique measurably improves the output, and the first attempt is often close.
- The sample's loop has no stopping limit, so an evaluator that never passes can run forever. Add a round budget before you use it.
- Use a closed set of verdicts, and decide what
FAILmeans in your system instead of treating it like a polish request. - Add retries for malformed structured output, and consider a different model for the evaluator when the stakes are high.
The full sample is in the spring-ai-examples repository under agentic-patterns/evaluator-optimizer. The pattern is described in Anthropic's research on building effective agents, alongside the other workflows covered in this series.

