Skip to content

    Agentic AI for Java

    Chain, route, parallelise, evaluate: workflows before agents

    Build four LLM workflow patterns in plain Java (chain, route, parallelise, evaluate), count their model calls, and know when you need an agent at all.

    By Published 22 min read

    Share

    This lesson is part of Agentic AI for Java Developers: Build and Ship Agents. Enroll for free, then sign in, to read it in full.

    What you'll learn: how to build four fixed-path LLM workflows (prompt chaining, routing, parallelisation, evaluator-optimizer) as small, testable Java classes, what each one costs in model calls, and the rule for choosing between them and an open agent loop.

    The job you can write down

    It is 02:47 and Parcelo's checkout is slow. Last lesson you built a loop that lets a model decide which tool to open next. But look at what the on-call engineer writes after the page: a status-page sentence for customers. That job has the same steps every night: collect the evidence, name the likely cause, write a calm sentence, check it for internal names. Nobody needs a model to decide what the steps are. You can write them down.

    When you can write the steps down, write them in Java. Java gives you a path that is testable, a bill you can predict and failures you can name. The model still does the part Java cannot do, which is turning messy text into good text, but Java decides what happens next. This lesson builds the four classic ways to do that, runs each on the Parcelo incident, and counts the model calls.

    NOTE

    Invented example. Parcelo is a made-up delivery company. Its services, alerts, tickets and status-page wording are invented for this course. Every model in this lesson's lab is a script: it plays fixed replies, so the output is reproducible. A real model would word things differently and sometimes break a rule that a script never breaks. That is exactly why the checks in the code exist.

    The idea in one picture

    Figure 1. Two ways to run a model: Java picks the path, or the model picks the path

    A workflow, where Java picks the path, next to an agent loop, where the model picks itTask to Workflow code (known steps); Task to Agent loop (unknown steps); Workflow code to Model (step 1 to n); Agent loop to Model (whatever it asks); Model to Java gates (output); Model to Step budget (output)Task: what you askTaskwhat you askWorkflow code: Java picks the pathWorkflow codeJava picks thepathAgent loop: model picks the pathAgent loopmodel picks thepathModel: text in, text outModeltext in, text outJava gates: check each stepJava gatescheck each stepStep budget: the only brakeStep budgetthe only brakeknown stepsunknown stepsstep 1 to nwhatever it asksoutputoutput

    How to read this: follow the packets. In the top lane every model output meets a Java gate before anything else happens. In the bottom lane the model's output decides the next move, and only the step budget stops it.

    Anthropic's engineering article "Building effective agents", which I fetched while writing this lesson, draws the same line. It calls systems where code decides the path workflows and systems where the model can "dynamically direct their own processes and tool usage" agents, and it recommends "finding the simplest solution possible, and only increasing complexity when needed." The workflow patterns below are the ones that article names; the lab code is my own, written for this course.

    Workflow or agent: who chooses the next step?

    The whole decision is one question: can you list the steps before the request arrives? If yes, you have a workflow, and the next question is only which shape the steps take. If no, you need the open loop from the last lesson, with its budget, its trace and (in later lessons) its guardrails.

    Figure 2. How to choose: from a new task to a pattern or an agent

    flowchart TD accTitle: Choosing between one call, a workflow pattern and an agent loop accDescr: A chain of questions starts at a new task. If the steps cannot be listed in advance the answer is an open agent loop. If they can, one model call is used when one call is enough. Otherwise several kinds of input lead to routing, steps that depend on earlier output lead to a prompt chain, and independent parts or repeated attempts lead to parallelisation. Any of these can be wrapped in an evaluator-optimizer loop when there is a clear check on the result. Start(["New task"]) Q1{"Can you list the steps in advance?"} AG["Open agent loop: budget, tools, trace"] Q2{"Is one model call enough?"} ONE["One model call"] Q3{"Several kinds of input, handled differently?"} ROU["Routing"] Q4{"Does a later step need an earlier output?"} CH["Prompt chain with gates"] PAR["Parallelise: sections or votes"] Q5{"Is there a clear check on the result?"} EV["Wrap it in a bounded evaluator-optimizer"] Start --> Q1 Q1 -- "no" --> AG Q1 -- "yes" --> Q2 Q2 -- "yes" --> ONE Q2 -- "no" --> Q3 Q3 -- "yes" --> ROU Q3 -- "no" --> Q4 Q4 -- "yes" --> CH Q4 -- "no" --> PAR CH --> Q5 PAR --> Q5 Q5 -- "yes" --> EV

    How to read this: start at the top and answer honestly. Most real tasks leave the diagram at "yes" on the first question, and that is the point.

    TIP

    Picture it: a train and a taxi. A train runs on rails: you know the stops, the timetable and roughly what the ticket costs, and when it breaks you know which section of track to look at. A taxi goes wherever the passenger's story leads it, so it can reach places no timetable lists, and you pay by the kilometre it chose. Use the train whenever the route is known. Where the picture stops: a workflow can still have a smart stop in the middle (a model call), it just cannot change the rails.

    Pattern 1: prompt chaining, with a gate between the steps

    A prompt chain is a fixed list of model calls where each call reads the previous call's output. Anthropic's article puts it as decomposing a task "into a sequence of steps, where each LLM call processes the output of the previous one", and says it suits tasks that "can be easily and cleanly decomposed into fixed subtasks."

    What makes a chain safe in Java is the gate: a plain function that looks at a step's output and either lets it through or refuses it with a reason. A gate costs nothing (no model call) and cannot be talked out of its answer. When a gate refuses, the chain stops, and the later steps, which cost money, never run.

    TIP

    Picture it: an assembly line with an inspector after each station. A bad part is pulled off at station two, so stations three to five never spend time on it. The inspector is a person with a checklist, not another worker who might get tired of arguing. Where the picture stops: our inspector can only check what a Java function can check, such as length or a banned word. It cannot judge whether a sentence is kind.

    Figure 3. A three-step chain, with a gate after each step and a stop when one refuses

    A prompt chain with gates: evidence, cause, status update, and a stop if a gate refusesEvidence to 1. Evidence; 1. Evidence to 2. Cause (gate passes); 2. Cause to 3. Status (gate passes); 2. Cause to Stop (gate refuses); 3. Status to Status update (gate passes)Evidence: fetched by JavaEvidencefetched by Java1. Evidence: gate: service1. Evidencegate: service2. Cause: gate: length2. Causegate: length3. Status: gate: no names3. Statusgate: no namesStop: step 3 never paidStopstep 3 never paidStatus update: for customersStatus updatefor customersgate passesgate passesgate refusesgate passes

    How to read this: the moving packets are the happy path. The red dashed arrow is what Run B below does: step 2's output is too long, the gate refuses it and step 3 is never called.

    Build it: the chain

    Every workflow step in the lab goes through one tiny helper. It sends two messages, an instruction and an input, offers no tools, and expects text back. If a model asks for a tool anyway, that is a bug in the workflow and it fails loudly.

    Verified: examples/backend/labs/agent-patterns/src/main/java/buildingai/labs/patterns/Llm.java

    static String ask(ChatModel model, String instruction, String input) {
        ModelReply reply = model.reply(List.of(new Message.Instruction(instruction), new Message.User(input)), List.of());
        return switch (reply) {
            case ModelReply.FinalAnswer done -> done.text();
            case ModelReply.ToolRequest ignored -> throw new IllegalStateException("a workflow step expects text, but the model asked for a tool");
        };
    }

    ChatModel is the one-method interface from the agent loop lesson: it takes the conversation and the tools on offer, and returns either a final answer or a tool request. Here we pass an empty tool list. A step is just "text in, text out".

    The chain itself is a loop over a list of steps. Each step has a name, an instruction and a gate that returns the problem as a sentence, or empty when the output may go on.

    Verified: examples/backend/labs/agent-patterns/src/main/java/buildingai/labs/patterns/PromptChain.java

    /** A gate returns the problem as a sentence, or empty when the output may go on to the next step. */
    public record Step(String name, String instruction, Function<String, Optional<String>> gate) {}
    
    public record ChainResult(boolean completed, String output, int failedStep, List<String> trace) {}
    // ...
    public ChainResult run(String input) {
        List<String> trace = new ArrayList<>();
        String current = input;
        for (int i = 0; i < steps.size(); i++) {
            Step step = steps.get(i);
            current = Llm.ask(model, step.instruction(), current);
            trace.add("step " + (i + 1) + "  " + step.name() + " -> " + current);
            Optional<String> problem = step.gate().apply(current);
            if (problem.isPresent()) {
                trace.add("gate  " + step.name() + " REFUSED: " + problem.get());
                return new ChainResult(false, current, i + 1, trace);
            }
            trace.add("gate  " + step.name() + " passed");
        }
        return new ChainResult(true, current, 0, trace);
    }

    Read it as three sentences. Ask the model with the previous output. Ask the gate. If the gate objects, return at once and say which step failed; otherwise carry the output into the next step. There is no model-chosen branch anywhere: the number of calls is at most the number of steps.

    The Parcelo chain has three steps with three gates, written as Java lambdas.

    Verified: examples/backend/labs/agent-patterns/src/main/java/buildingai/labs/patterns/Demo.java

    private static List<Step> statusUpdateSteps() {
        return List.of(
                new Step("evidence", "Summarise the evidence in one line: the failing service, the symptom and what changed.",
                        out -> KNOWN_SERVICES.stream().anyMatch(out::contains) ? Optional.empty() : Optional.of("the summary names no known service")),
                new Step("cause", "In one sentence, state the likely cause.",
                        out -> out.length() <= 160 ? Optional.empty() : Optional.of("the cause is " + out.length() + " characters, the limit is 160")),
                new Step("status", "Write one customer-facing sentence for the status page. No internal names.",
                        out -> out.contains("payments-gateway") ? Optional.of("the update leaks an internal service name") : Optional.empty()));
    }

    Notice that the input of the chain was not fetched by a model. Plain Java called the alert, metric and log tools (the same Parcelo tools an agent would be handed) and glued the three lines together. That is the first saving of a workflow: data you can fetch in code never needs a model call to fetch it.

    Pattern 2: routing, one classifier call and a plain switch

    Routing classifies the input, then sends it to the handler for that class. Anthropic's article describes it as classifying "an input and directs it to a specialized followup task." In Java it is one model call that produces a label, followed by a Map lookup. The label is generated text, so you never trust it: you check it against the routes you know, and anything else goes to a fallback.

    TIP

    Picture it: the reception desk of a hospital. Reception does not treat anyone; it asks two questions and sends you to the right door. If your problem fits no door, reception does not invent one: you are sent to a person. Where the picture stops: here the receptionist is a language model, so it can misread a patient, which is why the fallback and the label check exist.

    Figure 4. Routing: one classifier call, then ordinary Java picks the handler

    Routing: a classifier call picks one handler, an unknown label goes to a humanTicket to Classifier; Classifier to incident (incident); Classifier to howto (howto); Classifier to billing (billing); Classifier to Fallback (unknown label)Ticket: free textTicketfree textClassifier: one model callClassifierone model callincident: a model callincidenta model callhowto: a model callhowtoa model callbilling: plain Javabillingplain JavaFallback: a human reads itFallbacka human reads itincidenthowtobillingunknown label

    How to read this: only one handler ever runs. The billing handler is plain Java, so that ticket costs one model call, not two. The red dashed arrow is the label no route knows.

    Build it: the router

    Verified: examples/backend/labs/agent-patterns/src/main/java/buildingai/labs/patterns/Router.java

    public Routed route(String input) {
        List<String> trace = new ArrayList<>();
        String label = Llm.ask(classifier, instruction + " Answer with one word: " + String.join(", ", handlers.keySet()) + ".", input)
                .trim()
                .toLowerCase(Locale.ROOT);
        trace.add("classifier says '" + label + "'");
        UnaryOperator<String> handler = handlers.get(label);
        if (handler == null) {
            trace.add("'" + label + "' is not a known route: using the fallback");
            return new Routed("fallback", fallback.apply(input), trace);
        }
        trace.add("handler '" + label + "' runs");
        return new Routed(label, handler.apply(input), trace);
    }

    The instruction lists the allowed words, the label is trimmed and lower-cased, and the lookup decides. A handler is any function from the ticket text to a result: it may call a model, call a service, or just put the ticket in a queue. In the Demo the billing handler is ticket -> "queued for the billing team (no model call): " + ticket.

    Pattern 3: parallelisation, by sectioning or by voting

    Some jobs split into parts that do not need each other. Anthropic's article calls this parallelization and names two variations: sectioning, "breaking a task into independent subtasks run in parallel", and voting, "running the same task multiple times to get diverse outputs." In both, the outputs are combined by plain code.

    The word independent carries the weight. If part B needs part A's output, you do not have sections, you have a chain, and running B early is a bug. The lab runs the parts on virtual threads (cheap threads in Java 21 and later), one task per part, and returns the results in the order the tasks were given, so the output does not depend on which part finished first.

    Figure 5. Sectioning splits one job; voting repeats one question. Java merges both

    Parallelisation: sectioning workers merged by Java, and voters merged by majorityJob to Section calls (3 subtasks); Section calls to Merge in Java (3 answers); Question to Voter calls (N copies); Voter calls to Majority (N answers); Majority to Escalate (no majority)Job: logs, metrics, runbookJoblogs, metrics,runbookSection calls: same timeSection callssame timeMerge in Java: fixed orderMerge in Javafixed orderQuestion: one yes or noQuestionone yes or noVoter calls: same timeVoter callssame timeMajority: more than halfMajoritymore than halfEscalate: no winnerEscalateno winner3 subtasks3 answersN copiesN answersno majority

    How to read this: the stacked boxes are calls running at the same time. The top lane always produces a merged result; the bottom lane may produce no winner, and then a person decides.

    TIP

    Picture it: a restaurant kitchen with a grill station, a salad station and a dessert station. Three cooks work at once and the plate is assembled at the pass. Voting is different: it is three doctors giving a second opinion on the same scan. You act on the answer two of them share, and if they split you do not flip a coin, you ask a specialist. Where the picture stops: three calls to the same model are not three independent doctors.

    Build it: sections that fail alone

    Verified: examples/backend/labs/agent-patterns/src/main/java/buildingai/labs/patterns/Parallel.java

    static List<String> all(List<Callable<String>> tasks) {
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            List<Future<String>> futures = executor.invokeAll(tasks);
            List<String> results = new ArrayList<>();
            for (Future<String> future : futures) {
                results.add(resultOf(future));
            }
            return results;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException("interrupted while waiting for the tasks", e);
        }
    }
    
    private static String resultOf(Future<String> future) throws InterruptedException {
        try {
            return future.get();
        } catch (ExecutionException e) {
            return "unavailable: " + e.getCause().getMessage();
        }
    }

    invokeAll starts every task and waits for all of them; the futures come back in the order of the list. A task that throws becomes the text unavailable: ... instead of failing its neighbours. That is a design choice, and it is the right one for a report where two of three sections are still useful. The concurrency lesson goes deeper: timeouts, cancellation and limits.

    Sectioning is then a few lines on top.

    Verified: examples/backend/labs/agent-patterns/src/main/java/buildingai/labs/patterns/Sectioning.java

    public Merged run(List<Section> sections) {
        List<Callable<String>> tasks = new ArrayList<>();
        for (Section section : sections) {
            tasks.add(() -> Llm.ask(model, section.instruction(), section.input()));
        }
        List<String> answers = Parallel.all(tasks);
    
        List<String> lines = new ArrayList<>();
        List<String> trace = new ArrayList<>();
        for (int i = 0; i < sections.size(); i++) {
            lines.add(sections.get(i).title() + ": " + answers.get(i));
            trace.add("section '" + sections.get(i).title() + "' -> " + answers.get(i));
        }
        return new Merged(String.join("\n", lines), trace);
    }

    Voting needs one more rule, and it is the rule people get wrong: the winner must have more than half of all the votes, and a tie is not a win.

    Verified: examples/backend/labs/agent-patterns/src/main/java/buildingai/labs/patterns/Voting.java

    static Optional<String> majority(List<String> answers) {
        Map<String, Integer> counts = new HashMap<>();
        for (String answer : answers) {
            counts.merge(answer, 1, Integer::sum);
        }
        return counts.entrySet().stream()
                .filter(e -> e.getValue() * 2 > answers.size())
                .map(Map.Entry::getKey)
                .findFirst();
    }

    e.getValue() * 2 > answers.size() is "more than half". Two voters who disagree give no majority, so the caller gets an empty Optional and must escalate. A voter whose call failed is just another answer that nobody shares, so it counts against every winner.

    NOTE

    On call, 3 a.m.: Dara, an engineer at an invented shop, added a "second opinion" step to her alert triage: two model calls vote on whether a deploy is the cause. The first night they split one to one, and her code picked the first answer in the list. For a week "the deploy" won every tie, and two rollbacks later nobody had checked why. She changed one line so that a tie returns "no decision, ask a human". The rollbacks stopped; the pages about "no decision" were cheap. Invented example.

    Pattern 4: evaluator-optimizer, a loop with a bound

    The fourth pattern has a loop in it, but the loop is yours. A generator writes a draft, an evaluator judges it, and the judge's feedback goes back to the generator for another try. Anthropic's article describes it as one call that "generates a response while another provides evaluation and feedback in a loop", and says it works when there are "clear evaluation criteria" and refinement "provides measurable value."

    The danger is the word loop. A judge that is never satisfied makes a loop that never ends, and each round is two paid calls. So the loop is bounded by maxRounds, and when the bound is hit the code returns the last draft marked as not accepted. The caller can then escalate instead of shipping something nobody approved.

    Figure 6. Evaluator-optimizer: draft, judge, retry with the feedback, stop at the round limit

    Evaluator-optimizer: a generator and an evaluator in a bounded loopTask to Generator; Generator to Evaluator (draft); Evaluator to Accepted (PASS); Evaluator to Generator (FAIL, feedback); Evaluator to Round limit (no more rounds)Task: plus feedbackTaskplus feedbackGenerator: writes a draftGeneratorwrites a draftEvaluator: PASS or FAILEvaluatorPASS or FAILAccepted: ship itAcceptedship itRound limit: not acceptedRound limitnot accepteddraftPASSFAIL, feedbackno more rounds

    How to read this: the packet goes forward on PASS; on FAIL the feedback travels back to the generator. The red dashed arrow is the bound. Without it the loop has no exit.

    Build it: the bounded loop

    Verified: examples/backend/labs/agent-patterns/src/main/java/buildingai/labs/patterns/EvaluatorOptimizer.java

    public Outcome run(String task) {
        List<String> trace = new ArrayList<>();
        String input = task;
        String draft = "";
        for (int round = 1; round <= maxRounds; round++) {
            draft = Llm.ask(generator, generatorInstruction, input);
            trace.add("round " + round + "  draft    -> " + draft);
            String verdict = Llm.ask(evaluator, evaluatorInstruction, draft).trim();
            if (verdict.equals("PASS")) {
                trace.add("round " + round + "  verdict  -> PASS");
                return new Outcome(true, draft, round, trace);
            }
            String feedback = verdict.startsWith("FAIL:")
                    ? verdict.substring("FAIL:".length()).trim()
                    : "the evaluator gave an unreadable verdict: " + verdict;
            trace.add("round " + round + "  verdict  -> FAIL: " + feedback);
            input = task + "\nPrevious draft: " + draft + "\nFeedback: " + feedback;
        }
        trace.add("stop    round limit of " + maxRounds + " reached, the last draft was never approved");
        return new Outcome(false, draft, maxRounds, trace);
    }

    Three details are the lesson. The verdict must be exactly PASS or start with FAIL:; anything else counts as a failure, never as approval, because a judge that rambles ("I think it is fine") has not said yes. The feedback is added to the next generator input, so a retry is informed, not a re-roll. And the for bound is the only thing between you and an endless bill.

    Run it

    From examples/backend:

    ./gradlew :labs:agent-patterns:test       # 15 tests
    ./gradlew -q :labs:agent-patterns:run     # every pattern, its trace and its model-call count

    Expected output, captured from a real run (the first pattern; the full file is examples/golden/agent-patterns.txt):

    Parcelo is an invented company; the model in every run below is a script.
    
    Pattern 1. Prompt chaining: three steps, a gate after each
      input, fetched by Java with 3 tool calls and 0 model calls:
        alert A-1042: checkout-api p99 latency 4200 ms (SLO 800 ms), error rate 6.1%, firing since 02:47 UTC
        db pool in use 50 of 50 since 02:44, 14 of 50 at 02:30
        02:41:05 INFO deploy v412 started (previous version v411) | 02:41:40 INFO deploy v412 reported healthy
      Run A. Every gate passes
        step 1  evidence -> checkout-api is slow (p99 4200 ms, SLO 800 ms); payments-gateway deployed v412 at 02:41 and its pool is full (50 of 50).
        gate  evidence passed
        step 2  cause -> The payments-gateway deploy v412 exhausted the database connection pool.
        gate  cause passed
        step 3  status -> Some customers may see slow or failed checkouts. We are working on a fix.
        gate  status passed
        model calls: 3
      Run B. A gate refuses step 2, so step 3 is never paid for
        step 1  evidence -> checkout-api is slow (p99 4200 ms, SLO 800 ms); payments-gateway deployed v412 at 02:41 and its pool is full (50 of 50).
        gate  evidence passed
        step 2  cause -> It may be the deploy of v412, or possibly a network problem, or perhaps a noisy neighbour, or a slow database, or an upstream timeout; more investigation is needed before any conclusion can be drawn about the cause.
        gate  cause REFUSED: the cause is 215 characters, the limit is 160
        completed: false, model calls: 2 of 3

    Read it top to bottom. The three lines of input cost zero model calls: Java fetched them. In Run A every gate passes and the chain uses all three calls.

    In Run B step 2's script returns a long, hedging paragraph; the gate counts 215 characters against a limit of 160, refuses, and the chain stops with two calls spent and the third saved. The model here is a script, so the long paragraph appears on purpose; a real model might or might not ramble, and the gate is how you find out cheaply.

    Figure 7. Run B as a sequence: the gate refuses and the third call never happens

    sequenceDiagram accTitle: Prompt chain run where a gate refuses step two accDescr: The chain code asks the model for step one, the evidence summary, and the gate passes it. It then asks for step two, the cause. The model returns a long paragraph of 215 characters, the gate refuses it because the limit is 160, and the chain returns without ever asking for step three. autonumber participant C as Chain code (Java) participant G as Gate (Java) participant M as Model (script) C->>M: step 1, evidence M-->>C: one line of evidence C->>G: check step 1 output G-->>C: passed C->>M: step 2, cause M-->>C: long paragraph, 215 characters C->>G: check step 2 output G-->>C: REFUSED, limit is 160 Note over C: stop, step 3 is never called

    How to read this: follow the numbers down. The only thing that ends the run early is a Java gate, and the model is never asked a third time.

    The other patterns print in the same way. The rest of the file shows routing (four tickets, one of them with an unknown label), sectioning (including a run where the runbook call times out and the other two sections still arrive), voting (three voters win, two voters tie) and evaluator-optimizer (a second draft passes, then a judge that never approves and the round limit ends the loop). The decisive lines are these.

    Expected output, captured from a real run (routing, the last two tickets):

      ticket: Refund order 9-7731
        classifier says 'billing'
        handler 'billing' runs
        -> queued for the billing team (no model call): Refund order 9-7731
        model calls for this ticket: 1
      ticket: What is the weather in Pune?
        classifier says 'weather'
        'weather' is not a known route: using the fallback
        -> sent to a human to read: What is the weather in Pune?
        model calls for this ticket: 1

    Expected output, captured from a real run (sectioning, with a failing section):

      Run B. The runbook model call times out; the other sections still arrive
        section 'logs' -> payments-gateway deployed v412 at 02:41:05 (previous v411) and reported healthy at 02:41:40.
        section 'metrics' -> the database pool of payments-gateway has been 50 of 50 in use since 02:44 (14 of 50 at 02:30).
        section 'runbook' -> unavailable: model call timed out

    Expected output, captured from a real run (voting, with a tie):

      Run B. Two voters that disagree: no majority, so nothing is decided
        voter 1 says YES
        voter 2 says NO
        winner: none, escalate to a human

    Expected output, captured from a real run (evaluator-optimizer, never approved):

      Run B. The judge never approves: the round limit ends it
        round 1  draft    -> Checkouts are slow because of a database issue.
        round 1  verdict  -> FAIL: do not mention the database
        round 2  draft    -> Checkouts are slow because of a database problem we caused.
        round 2  verdict  -> FAIL: do not mention the database or blame anyone
        round 3  draft    -> Some checkouts are slow, and the cause is a database problem.
        round 3  verdict  -> FAIL: the evaluator gave an unreadable verdict: I think it is fine.
        stop    round limit of 3 reached, the last draft was never approved
        accepted: false, model calls: 6

    Look at the last block closely. Round 3's judge said "I think it is fine." That is not PASS, so the loop treats it as a failure and the run ends unaccepted after six calls, the most this loop can ever spend. Remember that these replies are scripted; the point is what your code does when a judge answers in a way you did not plan for.

    NOTE

    On call, 3 a.m.: Tomas, at an invented logistics start-up, built a writer-and-reviewer loop for customer emails with no round limit, because "it always passes in two rounds". One night the reviewer's instruction was edited to require "no apologies", and the writer's prompt still said "always apologise". The loop ran until a billing alert fired in the morning. The fix was five lines: a round counter, a return value that says "not accepted", and a test with a judge that always says no. Invented example.

    Three runs from the lab, step by step (interactive when JavaScript is on)

    Chain, every gate passes

    1. 1. Java fetches. Plain Java calls the alert, pool metric and deploy log tools: 3 tool calls and 0 model calls.
    2. 2. Evidence. Model call 1 returns: checkout-api is slow (p99 4200 ms, SLO 800 ms); payments-gateway deployed v412 at 02:41 and its pool is full (50 of 50). The gate passes: a known service is named.
    3. 3. Cause. Model call 2 returns: The payments-gateway deploy v412 exhausted the database connection pool. The gate passes.
    4. 4. Status. Model call 3 returns: Some customers may see slow or failed checkouts. We are working on a fix. The gate passes: no internal service name.
    5. 5. Done. The chain completed with 3 model calls.

    Chain, a gate refuses

    1. 1. Evidence passes. Step 1 returns the same evidence line and its gate passes.
    2. 2. A rambling cause. Step 2 returns a long paragraph that hedges between a deploy, a network problem and a noisy neighbour.
    3. 3. The gate refuses. The gate counts 215 characters against a limit of 160 and refuses: the cause is 215 characters, the limit is 160.
    4. 4. Stop. The chain returns completed false after 2 model calls of 3. Step 3 was never paid for.

    Evaluator-optimizer, second draft passes

    1. 1. Draft 1. The generator writes: The payments-gateway database pool is full after deploy v412, so checkouts are slow.
    2. 2. Verdict 1. The evaluator answers FAIL: uses internal names (payments-gateway, v412).
    3. 3. Draft 2. With that feedback the generator writes: Checkouts are slow for some customers. We are fixing it.
    4. 4. Verdict 2. The evaluator answers PASS in round 2.
    5. 5. Cost. The loop was accepted after 4 model calls: 2 per round, 2 rounds.

    Comparing the patterns, with the numbers from the lab

    The Demo ends with a table of its own counts, from the runs above. One extra row runs the investigation as the open agent loop of the previous lab (with that lab's script), so you can see all six side by side.

    Expected output, captured from a real run:

    Comparison (counts from the runs above)
      pattern                model calls  calls in a row     most calls allowed
      prompt chain           3            3                  3 (one per step)
      routing                2            2                  2 (classifier + one handler)
      sectioning             3            1                  3 (one per section)
      voting (3 voters)      3            1                  3 (one per voter)
      evaluator-optimizer    4            4                  6 (2 per round, 3 rounds)
      open agent loop        4            4                  6 (maxSteps; no other bound)

    "Calls in a row" is the number of model calls that must finish one after another, which is what decides how long a user waits when the calls themselves take the same time. Here is the same data as a table to compare on four axes.

    Pattern Who picks the next step Model calls (this lab) Calls in a row What goes wrong
    Prompt chain Java: the fixed list 3 3 A gate refuses (Run B), or a weak gate lets a wrong output through
    Routing Java, after one label 2 (an incident ticket) 2 An unknown or wrong label (the weather ticket went to the fallback)
    Sectioning Java: the fixed sections 3 1 One section fails alone (the runbook call timed out)
    Voting Java: majority rule 3 1 No majority, so a human decides (the two-voter run)
    Evaluator-optimizer Java loop, judge's verdict 4 4 Never approved, or an unreadable verdict (6 calls, then the limit)
    Open agent loop The model 4 4 Repeats or wanders until the step budget ends it

    Two things to take from it. First, the workflow patterns have a ceiling you can read off the code: the chain can never exceed its step count, a router never exceeds two calls, the evaluator loop never exceeds twice its round limit. The open loop's ceiling is whatever maxSteps you set, and its path is chosen by the model, so you test the budget rather than the route.

    Second, the only pattern that is faster than a chain is the parallel one, and it is faster because its calls do not depend on each other, not because the model is quicker.

    TIP

    Picture it: a recipe versus an improvised dinner. A recipe tells you the shopping list before you leave home, so the bill is no surprise and two cooks produce the same dish. An improvised dinner might be better on a day you do not know what is in the fridge, and you will not know the cost until you check out. Where the picture stops: you can put a small improvised step (a model call) inside every recipe line.

    Under the hood: a step is a stateless request

    Every workflow step is a separate request that sends only what that step needs. The chain's three calls each carry exactly two messages, an instruction and an input, and nothing else. The agent loop of the previous lab is different: the golden file of that lab shows its first run sending conversations of 2, 4, 7 and 9 messages, because every call re-sends the whole conversation so far.

    That difference is why the workflow patterns are cheap to reason about. A chain step cannot be confused by earlier steps' tool results because it never sees them; it sees one input you chose.

    Parallel calls are just several independent requests started at the same time (the lab starts them on virtual threads and waits for all). And the evaluator in the last pattern is nothing special: it is one more request whose prompt says "reply PASS or FAIL: reason". Making its reply parseable is your job, which is why the lab accepts only an exact PASS.

    TIP

    Picture it: postcards, not a phone call. Each workflow step is a postcard with the one thing the next person needs written on it. An agent loop is a long phone call where everything said earlier is read out again before every new sentence. Where the picture stops: a real API may let you reuse part of a long conversation more cheaply, so check your provider's documentation before assuming the full price.

    Break it

    I ran each of these changes against the lab's tests and restored the code afterwards.

    • In Voting.majority change * 2 > to * 2 >=. A one-to-one tie now "wins": theMajorityNeedsMoreThanHalfOfAllVoters fails (it got Optional[NO], not empty). This is Dara's bug.
    • In EvaluatorOptimizer.run replace verdict.equals("PASS") with !verdict.startsWith("FAIL"). A rambling verdict is now approval and anUnreadableVerdictIsNeverTreatedAsApproval fails.
    • In Parallel.all run the tasks one after another. sectionsRunAtTheSameTimeAndMergeInTheOrderGiven fails: its model waits at a barrier of three threads, which a sequential run can never fill.

    Then try one that is not in the tests: give PromptChain a gate that always returns Optional.empty() and rerun Run B. Step 3 now runs on the rambling paragraph. The chain is only as strict as its gates.

    In practice: Parcelo

    Put the patterns together and TriageDesk, Parcelo's on-call assistant, looks like this. A router sends the alert to a handler. The common incident handler is a sectioning step (logs, metrics and runbook summaries at the same time) followed by a gated chain that writes the status update. Only an alert that matches no known route reaches the open agent loop, and that loop hands a proposal to a human instead of acting.

    Figure 8. TriageDesk built from the patterns: the agent loop is the exception, not the rule

    TriageDesk built from workflow patterns, with the agent loop kept for unknown alertsAlert to Router; Router to Sectioning (known incident); Sectioning to Status chain (evidence); Router to Agent loop (no known route); Agent loop to On-call human (proposal)Alert: A-1042AlertA-1042Router: classifier callRouterclassifier callSectioning: logs metrics runbookSectioninglogs metricsrunbookStatus chain: three gated stepsStatus chainthree gated stepsAgent loop: unseen alerts onlyAgent loopunseen alertsonlyOn-call human: decidesOn-call humandecidesknown incidentevidenceno known routeproposal

    How to read this: the green path is the everyday route and is made only of Java and bounded model calls. The yellow box is the one place where the model chooses its own steps, and a person receives its proposal.

    This is a design sketch of how the lesson's parts combine, not a lab: the course's capstone builds the real TriageDesk. What you can already say about it is concrete.

    The everyday path has a worst-case cost you can count (one classifier call, three section calls, three chain calls), a test for each gate, and a clear owner for every failure. The agent loop's cost is bounded by its step budget and its path is not predictable, which is exactly why it sits at the edge.

    Architect's notes

    • Start with the workflow and promote to an agent only when a fixed path fails. A workflow you outgrow is a cheap lesson. An agent you did not need is a permanent cost, a harder test and a wider attack surface.
    • A gate is the cheapest quality control you own. It costs no model call, cannot be argued with and is trivial to unit-test. Put one after every step whose output feeds money, customers or another model.
    • Count the worst case from the code. Chain: its step count. Router: two. Evaluator-optimizer: twice its round limit. If you cannot state the ceiling in a sentence, the pattern has no bound yet.
    • Routing is only as good as its fallback. A classifier label is generated text. Every unknown label needs a safe destination, and a test that sends one there.
    • Parallel is for independent work. If a section needs another section's output, run a chain. Failures should be local: a missing section is better than a failed report, if you label it.
    • Voting needs a majority rule and an escalation path. A tie must produce "no decision". Also note that votes from one model are not independent opinions, so keep the vote small and the stakes low.
    • Keep the pieces separate. The lab's PromptChain, Router, Sectioning and EvaluatorOptimizer do not know about each other. That is why TriageDesk can nest a chain inside a route inside an evaluator loop.

    Common mistakes

    • No gate between chain steps. A bad step-one output flows into three more paid calls. Fix: a Java check after every step, and a test where the gate refuses.
    • Trusting the classifier label. A routed switch with a default that throws, or no default at all. Fix: look the label up in a map of known routes and send misses to a fallback.
    • Parallelising dependent work. Starting the summary section before the evidence section finishes. Fix: draw the dependency; if there is an arrow between two parts, they are a chain.
    • Letting a tie win. findFirst() on a sorted vote count, or "the first answer wins". Fix: require strictly more than half and return Optional.empty() otherwise.
    • An evaluator loop with no round limit. It works until the day the judge and the writer disagree. Fix: a bound, a return value that says "not accepted", and a test with a judge that always says no.
    • Parsing the judge loosely. Treating anything that is not "FAIL" as a pass. Fix: accept only the exact token you asked for; everything else is a failure with the raw text in the message.
    • Fetching with a model what Java can fetch. An agent step that "looks up" the alert text. Fix: call the tool in plain Java and pass the text in; save the call and the variance.
    IMPORTANT

    Remember this:

    • If you can write the steps as Java, write them as Java.
    • A gate is a Java check after a model step; it costs nothing and it stops waste.
    • Every loop needs a bound, and every vote needs a majority rule.
    • A model's label or verdict is untrusted text: check it before you act on it.
    • Count the calls from the code, and use an agent only where the path cannot be planned.

    Key takeaways

    • A workflow is code deciding the path; an agent is a model deciding the path. Choose by asking whether you can list the steps in advance.
    • The four patterns are prompt chaining (steps with gates), routing (a label, then a handler), parallelisation (sectioning or voting) and evaluator-optimizer (a bounded loop).
    • In this lab the chain uses 3 calls, a routed incident ticket 2, sectioning 3 (one in a row), voting 3 (one in a row), and the evaluator loop 4 here and 6 at most; the agent loop used 4 with a cap of 6 steps. These come from scripted runs and show structure, not the behaviour of a real model.
    • Data Java can fetch should be fetched by Java: it saves a model call and removes a source of variation.
    • Every pattern needs its failure path in code: a refused gate, an unknown route, an unavailable section, no majority, an unaccepted draft.

    Practice exercises

    1. Starter. In Demo.java change the limit in the cause gate from 160 to 100 and run ./gradlew -q :labs:agent-patterns:run. Which run now stops, and after how many model calls? Then write a PatternsTest test that builds a two-step chain where the second step must never be called.
    2. Intermediate. Add a fourth route, security, to the router in Demo.java whose handler is plain Java (no model call), and add a ticket for it. Predict the model-call count for that ticket before you run it, then check the Demo's line model calls for this ticket.
    3. Advanced. Combine two patterns: run the three Sectioning summaries, then pass the merged text into a PromptChain whose last gate rejects any sentence containing payments-gateway. Count the calls from the code first (three plus the chain's steps), run it, and add a test that asserts the count with a CountingModel.

    Enroll to keep reading

    Lesson 8 of 15 · Agentic AI for Java Developers: Build and Ship Agents

    Build four LLM workflow patterns in plain Java (chain, route, parallelise, evaluate), count their model calls, and know when you need an agent at all.

    In the rest of this lesson

    • Pattern 3: parallelisation, by sectioning or by voting
    • Pattern 4: evaluator-optimizer, a loop with a bound
    • Run it
    • Comparing the patterns, with the numbers from the lab
    • Under the hood: a step is a stateless request
    • Break it

    Enrolling is free. It unlocks every lesson in Agentic AI for Java Developers: Build and Ship Agents, tracks your progress across devices and keeps your quiz scores. The newsletter is optional.

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments