Building Iterative AI Agents with LangChain4j Loop Workflow

8 hours ago 2
Club.noww.in

  

1. Introduction

A single LLM call is often not enough to produce a high-quality result. Whether we are generating a story, writing code, creating documentation, generating SQL, or producing an analysis, the first response may contain mistakes or areas that can be improved.

 

A common approach to address this is to introduce an iterative workflow: Generate → Evaluate → Improve → Evaluate → Improve → ... → Finish

 

Instead of accepting the first output, we allow an AI agent to review its own work through another agent and iteratively improve the result until it satisfies a defined quality condition.

 

This is where the Loop Workflow pattern becomes useful. In this post, we'll explore how to build iterative AI agents using the Loop Workflow pattern in LangChain4j.

 

2. What is a Loop Workflow?

A Loop Workflow is an agentic workflow where a set of agents is executed repeatedly until a specific exit condition is satisfied or a maximum number of iterations is reached.

 

At a high level, the workflow looks like this:


The important part is the loop between evaluation and improvement.  The evaluator determines whether the current output is good enough. If it isn't, its feedback is passed to an improvement agent, which produces a better version. The improved output is then evaluated again. This process continues until the output reaches the required quality level.

 

2.1 Why Do We Need Iterative AI Agents?

LLMs are probabilistic systems. Even when given a good prompt, there is no guarantee that the first response will be perfect.

 

For example, an LLM generating a children's story might produce a story that:

 

·      Contains grammatical issues

·      Has inconsistent characters

·      Has unnecessary repetition

·      Has poor pacing

·      Is not appropriate for the target age group

·      Does not communicate the intended lesson clearly

 

A traditional one-shot workflow would simply return that response.

 

An iterative workflow takes a different approach.

 

Instead of: Prompt → LLM → Final Output

 

we can build:

Prompt ↓ LLM generates output ↓ Another agent evaluates the output ↓ Feedback ↓ LLM improves the output ↓ Evaluate again ↓ ...

   

This gives the system an opportunity to critically evaluate and improve its own output.

 

2.2 The Core Pattern

The Loop Workflow pattern can be broken down into three primary stages:

 

a. Generate

An agent generates the initial output based on the user's input.

 

For example:

 

User Input ↓ Story Writer ↓ Story v1

The first version doesn't necessarily need to be perfect. Its purpose is to provide an initial result that can be evaluated.

 

b. Evaluate

A reviewer or evaluator agent examines the generated output. It can evaluate the result against predefined criteria and produce:

 

·      A quality score

·      Feedback

·      Identified problems

·      Suggested improvements

 

For example:

Story v1 ↓ Story Reviewer ↓ Rating: 6/10, Feedback: "The ending needs more emotional impact......"

   

c. Improve

An improvement agent takes the current output and the evaluator's feedback and generates an improved version.

 

Story v1 + Reviewer Feedback ↓ Story Improver ↓ Story v2

The new version goes back to the evaluator. This creates the iterative loop:

Generate ↓ Evaluate ↓ Improve ↓ Evaluate ↓ Improve ↓ ...

   

2.3 When Does the Loop Stop?

An iterative workflow needs a clear stopping condition. Otherwise, the agents could continue running indefinitely.

 

A common approach is to define a quality threshold, Maximum iterations.

 

For example:

Quality threshold = 8/10

Maximum iterations = 5

 

The workflow can then behave like this:

 

·      Iteration 1 → Rating: 6 → Improve

·      Iteration 2 → Rating: 7 → Improve

·      Iteration 3 → Rating: 8 → Finish

 

The workflow can also have a maximum iteration limit: (Maximum iterations = 5). This provides a safety mechanism even if the quality threshold is never reached.

 

Therefore, a practical Loop Workflow usually has two controls:

·      Exit Condition like rating >= 8

·      Maximum Iterations like max_iterations = 5

 


   

The loop stops when the desired quality is achieved or the maximum number of attempts is reached.

 

3. Loop Workflow in LangChain4j

LangChain4j provides agentic workflow capabilities that allow us to compose multiple agents into workflows. For a Loop Workflow, we define the agents participating in the loop and configure:

 

·      The agents that should be executed

·      The maximum number of iterations

·      The condition for exiting the loop

·      How intermediate results are stored and shared

 

One important concept here is the AgenticScope. The scope provides a shared context in which the workflow can maintain state and make outputs available to other agents and to the workflow itself. This allows the workflow to inspect the current state and determine whether it should continue or terminate.

 

3.1 Why Separate the Reviewer and Improver?

An interesting aspect of this pattern is that the evaluator and the improver can have different responsibilities.

 

The Reviewer should focus on criticism like "What's wrong with the current output?"

The Improver should focus on refinement like "How can I fix those problems while preserving what is already good?"

 

This separation is useful because asking a single agent to both generate and evaluate its own output can make it less critical of its own response. With separate agents, we can create a more explicit pipeline. This creates a clear separation of responsibilities between the agents.

 

3.2 Designing a Good Exit Condition

The quality of the exit condition is particularly important. The exit condition determines when the agent should stop improving the output. A poorly designed condition can either stop the workflow too early or cause it to run unnecessarily many times.

 

For example, suppose Story Reviewer Agent gives a rating between 1 and 10. A simple exit condition could be: rating >= 8. This is easy to understand, but it may not always be sufficient.

 

a. What Makes a Good Exit Condition?

A good exit condition should be:

 

·      Clear: We should know exactly when the workflow should stop.

·      Measurable: The condition should be based on something that can be reliably evaluated.

·      Aligned with the goal: The condition should represent the actual quality we care about.

·      Bounded: The workflow should have a maximum iteration limit as a safety mechanism.

 

b. Good Exit Condition

Suppose the Story Reviewer Agent returns a rating between 1 and 10. A simple exit condition could be:

rating >= 8

   

This means the workflow stops when the story reaches a quality rating of 8 or higher. However, we can make the condition more meaningful by also considering critical issues:

 

rating >= 8 AND no critical issues

   

and also we can restrict it to some maximum number of iterations.

 

(rating >= 8 AND no critical issues) OR (Maximum iterations <= 5)

This is a good exit condition because the workflow doesn't stop simply because the numerical score is high. It also verifies that there are no important problems remaining and also, we are restricting it from executing infinite loop.

 

c. Bad Exit Condition: Rating Alone

Now consider a simpler exit condition: rating >= 8

 

At first, this looks reasonable. But imagine the Story Reviewer returns: (Rating is 9). The workflow sees: (9 >= 8 → true) and immediately stops. The problem is that the story still might contains significant issues.

 

This is an example of premature termination. The problem isn't necessarily that the threshold of 8 is wrong. The problem is that the evaluator's rating alone doesn't capture all the conditions that are important to the workflow.

 

d. Bad Exit Condition: Too Strict

Now imagine we configure the workflow like this:

rating >= 9.5 AND no issues AND every evaluation criterion = 10

The Story Reviewer may continue finding small improvements:

 

·      Iteration 1 → Rating: 8.2 → Improve

·      Iteration 2 → Rating: 8.7 → Improve

·      Iteration 3 → Rating: 9.1 → Improve

·      Iteration 4 → Rating: 9.3 → Improve

·      Iteration 5 → Rating: 9.4 → Improve

 

Even though the story is already very good, the exit condition is never satisfied. The workflow reaches the maximum iteration limit.

 

This can result in:

·      Unnecessary LLM calls

·      Higher latency

·      Higher resource consumption

·      Repeated changes to an already good output

 

This is an example of an overly strict exit condition.

 

e. Bad Exit Condition — No Maximum Iteration

Consider another scenario. The Story Reviewer keeps giving scores below the threshold: (rating >= 8), but the workflow has no maximum iteration limit.

 

The workflow might continue like this:

 

Iteration 1 → 6.0

Iteration 2 → 6.5

Iteration 3 → 7.0

Iteration 4 → 7.0

Iteration 5 → 7.5

Iteration 6 → 7.5

Iteration 7 → 7.6

...

 

If the reviewer never returns a rating of 8 or higher, the workflow could continue indefinitely. Therefore, a Loop Workflow should generally have a maximum iteration limit as a safety boundary.

 

f. The General Principle

A good exit condition should answer one question: "What does good enough mean for this particular workflow?".

 

For example, for our Story Generation workflow, we might define:

 

(rating >= 8 AND no critical issues) OR maximum iterations reached

   

For a different workflow, the definition of "good enough" would be different.

 

For a Code Generation Agent:

A Code Generator creates code and a Code Reviewer evaluates it. A Code Improver fixes the issues identified by the reviewer.

 

A suitable exit condition could be:

 

All tests pass AND no critical issues

For Text-to-SQL Agent

A SQL Generator creates SQL, while a SQL Evaluator checks whether the SQL is syntactically valid and correctly answers the user's question. A SQL Improver fixes the query based on the feedback.

 

A suitable exit condition could be:

SQL executes successfully AND query satisfies the user's intent

   

For a Document Generation Agent:

A Document Writer generates a document, a Document Reviewer evaluates its quality and completeness, and a Document Improver addresses the identified issues. A suitable exit condition could be:

 

quality score >= 0.9 AND all mandatory sections are present

   

The important point is that there is no universal exit condition. The evaluator and exit condition should be designed together based on what success means for the particular agentic workflow.

 

3.3 Loop Workflow vs One-Shot Generation

One-shot

Loop Workflow

Generate once

Generate iteratively

No explicit evaluation

Evaluation after generation

First response is final

Response can be refined

Simple

More complex

Lower latency

Potentially higher latency

Lower LLM usage

More LLM calls

Suitable for simple tasks

Useful for quality-sensitive tasks

 

A Loop Workflow isn't always better. If the task is simple and the first response is generally sufficient, introducing a reviewer and improvement loop may add unnecessary complexity. The pattern becomes valuable when quality can be evaluated and improved systematically.

 

4. Sample Storyteller Workflow

To understand the pattern better, we'll use a simple children's story example. We create three agents:

 

·      The Story Writer creates the initial story.

·      The Story Reviewer evaluates the story and provides a rating and actionable feedback.

·      The Story Improver uses that feedback to create an improved version.

 

The Reviewer and Improver then continue working together until the story reaches the required quality level or the maximum number of iterations is reached.

 

Following diagram depicts the same.

 

First we need to define interfaces for the story writer, reviewer and improver agents.

 

StoryWriter.java

public interface StoryWriter { @UserMessage( """ You are the Story Writer in an iterative children's story creation workflow. Create a short, engaging children's story based on the user's story idea. Requirements: 1. Use simple language suitable for children ages 5 to 10. 2. Create interesting characters and a clear beginning, middle, and ending. 3. Include a positive message or lesson. 4. Make the story imaginative, warm, and engaging. 5. Give the story a suitable title. Important: - Return only the story. - Do not include explanations or editorial comments. - Keep the story concise. Story idea: {{storyIdea}} """) @Agent( name = "storyWriter", description = """ Creates an engaging children's story from a given story idea. Produces the initial story that will be evaluated and improved by subsequent agents in the iterative workflow. """) String writeStory(@V("storyIdea") String storyIdea); }

The StoryWriter interface takes a story idea as input and generates a draft story as output.

 

StoryReviewer.java

public interface StoryReviewer { @UserMessage( """ You are the Story Reviewer in an iterative children's story improvement workflow. Review the provided story carefully and evaluate its overall quality. Evaluate the story based on: 1. Grammar and language Is the language clear and grammatically correct? 2. Clarity Are the characters, events, and ideas easy for children to understand? 3. Consistency Are characters, events, and story details consistent? 4. Pacing Does the story flow naturally without unnecessary repetition? 5. Age appropriateness Is the vocabulary, theme, and content appropriate for children ages 5 to 10? 6. Story quality Is the story interesting, imaginative, and emotionally engaging? 7. Lesson Is the intended message or lesson clear? Give the story an overall quality rating from 1 to 10. Scoring guidelines: - 1-4: Major improvements required - 5-6: Several improvements required - 7: Good but needs improvement - 8: Very good - 9: Excellent - 10: Outstanding Also provide concise, actionable feedback that the Story Improver can use to improve the story. Important: - Do not rewrite the story. - Do not provide unnecessary explanations. - Identify the most important improvements. - Focus the feedback on actionable changes. - Return the rating and feedback in the requested structured format. Current story: {{story}} """) @Agent( name = "storyReviewer", description = """ Evaluates the current children's story for grammar, clarity, consistency, pacing, age appropriateness, creativity, and overall quality. Returns a quality rating and actionable feedback that can be used by the Story Improver. """) StoryReview reviewStory(@V("story") String story); }

StoryReview agent takes draft story as input and review it and return a StoryReview object as output.

public class StoryReview { @Description("Overall quality rating of the story, integer from 1 to 10") private int rating; @Description("Concise, actionable feedback for improving the story; use a single line with no embedded newlines") private String feedback; }

   

StoryImprover.java

 

public interface StoryImprover { @UserMessage( """ You are the Story Improver in an iterative children's story improvement workflow. The Story Reviewer has evaluated the current story and provided a quality rating and feedback. Your responsibility is to improve the story based on that feedback. Improve the story for: 1. Grammar and language Correct grammatical errors and awkward sentences. 2. Clarity Make characters, events, and ideas easier to understand. 3. Consistency Fix inconsistencies in character names, personalities, events, or story details. 4. Pacing Remove unnecessary repetition and improve the story flow. 5. Age appropriateness Ensure the vocabulary, themes, and writing style are suitable for children ages 5 to 10. 6. Story quality Make the story more engaging and imaginative while preserving its original intent. 7. Lesson Make the story's message clear without making it feel forced. Important: - Preserve the original story's core idea. - Do not introduce unrelated characters or events. - Use the review feedback to guide your improvements. - Do not make changes that are unrelated to the reviewer feedback. - Improve the existing story rather than completely replacing it. - Keep the title. - Return ONLY the improved story. - Do not include explanations, comments, or editorial notes. Current story: {{story}} Reviewer assessment: {{storyReview}} """) @Agent( name = "storyImprover", description = """ Improves an existing children's story using the quality rating and actionable feedback provided by the Story Reviewer. Preserves the original story's intent while addressing the identified quality issues and producing an improved version for the next review iteration. """) String improveStory(@V("story") String story, @V("storyReview") StoryReview review); }

   

StoryImprover agent takes the story and StoryReview comments as inout and outputs the updated story.

 

Let’s define agents using AgenticServices class.

 

StoryWriter storyWriter = AgenticServices.agentBuilder(StoryWriter.class) .chatModel(chatModel) .outputKey("story") .build(); StoryReviewer storyReviewer = AgenticServices.agentBuilder(StoryReviewer.class) .chatModel(structuredChatModel) .outputKey("storyReview") .build(); StoryImprover storyImprover = AgenticServices.agentBuilder(StoryImprover.class) .chatModel(chatModel) .outputKey("story") .build();

Now we need to build the workflow like below.

 

   

First, we need to define the looping workflow between the StoryReviewer and StoryImprover agents. The reviewer evaluates the current story and produces a StoryReview containing the rating and feedback. The improver then uses that feedback to create an improved version of the story. This process continues until the exit condition is satisfied or the maximum number of iterations is reached.

 

UntypedAgent storyImprovementLoop = AgenticServices.loopBuilder() .subAgents(storyReviewer, storyImprover) .maxIterations(5) .testExitAtLoopEnd(true) .exitCondition( (agenticScope, loopCounter) -> { StoryReview storyReview = agenticScope.readState("storyReview", null); double score = (storyReview != null) ? storyReview.getRating() : 0; return loopCounter <= 3 ? score >= 9 : score >= 7; }) .outputKey("story") .build();

   

What is happening here?

subAgents(storyReviewer, storyImprover): Defines the two agents that participate in the loop.

Story Reviewer → Story Improver → Story Reviewer → Story Improver → ...

        

        

The StoryReviewer evaluates the story, while the StoryImprover uses the review feedback to improve it.

 

maxIterations(5): Places an upper limit of 5 iterations on the loop. This prevents the workflow from running indefinitely.

 

testExitAtLoopEnd(true): Tells the workflow to evaluate the exit condition after the agents in the current iteration have completed. This is useful here because the reviewer needs to run first and produce the StoryReview before we can decide whether the story has reached the required quality.

 

exitCondition(...): Defines when the loop should stop. First, we retrieve the review produced by the StoryReviewer:

 

StoryReview storyReview = agenticScope.readState("storyReview", null);

   

Then we extract its rating:

 

double score = (storyReview != null) ? storyReview.getRating() : 0;

The example uses a slightly stricter quality threshold during the first few iterations:

return loopCounter <= 3 ? score >= 9 : score >= 7;

This means:

Iteration

Required Rating

1–3      

≥ 9

4–5      

≥ 7

 

So the workflow initially tries to achieve a very high-quality result. If it hasn't reached that level after three iterations, it becomes more lenient and accepts a rating of 7 or higher.

 

outputKey("story"): finally, the output of the loop is stored in the AgenticScope under the key "story".

 

So the workflow can ultimately expose the latest improved story as its output. The overall behavior is therefore:

 

The important point is that maxIterations and exitCondition work together: the quality condition allows the loop to finish early, while maxIterations provides an upper bound on how long the loop can run.

 

As we have looping workflow, now we need to connect this to storyWriter workflow using  AgenticServices.sequenceBuilder().

UntypedAgent storyWorkflow = AgenticServices.sequenceBuilder() .name("sequentialStoryWorkflow") .subAgents(storyWriter, storyImprovementLoop) .listener(new AgentWorkflowListener()) .outputKey("story") .build();

   

Now we can call the story workflow with input.

Map<String, Object> input = new LinkedHashMap<>(); input.put("storyIdea", "Story About a Cricketer"); ResultWithAgenticScope<String> result = storyWorkflow.invokeWithAgenticScope(input);

   

Follow below step-by-step procedure to build complete working application.

 

Step 1: Create new maven project 'loop-workflow-demo'

 

Update pom.xml with maven dependencies.

 

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.sample.app</groupId> <artifactId>loop-workflow-demo</artifactId> <version>1.0.0</version> <name>Sequential Handoff Pattern Demo</name> <description> Simple Java console application demonstrating a deterministic sequential handoff workflow with LangChain4j and Ollama. </description> <properties> <!-- Java --> <java.version>21</java.version> <maven.compiler.release>${java.version}</maven.compiler.release> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- LangChain4j --> <langchain4j.version>1.18.1</langchain4j.version> <langchain4j.agentic.version>1.18.1-beta28</langchain4j.agentic.version> <!-- Logging --> <slf4j.version>2.0.17</slf4j.version> <!-- Console --> <jline.version>3.30.6</jline.version> <!-- Application --> <main.class>com.sample.app.App</main.class> <!-- Maven Plugins --> <maven.compiler.plugin.version>3.14.1</maven.compiler.plugin.version> <maven.surefire.plugin.version>3.5.4</maven.surefire.plugin.version> <maven.shade.plugin.version>3.6.1</maven.shade.plugin.version> <spotless.maven.plugin.version>3.4.0</spotless.maven.plugin.version> </properties> <dependencies> <!-- LangChain4j Core --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-core</artifactId> <version>${langchain4j.version}</version> </dependency> <!-- LangChain4j Ollama Integration --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-ollama</artifactId> <version>${langchain4j.version}</version> </dependency> <!-- LangChain4j Agentic --> <dependency> <groupId>dev.langchain4j</groupId> <artifactId>langchain4j-agentic</artifactId> <version>${langchain4j.agentic.version}</version> </dependency> <!-- SLF4J --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-nop</artifactId> <version>${slf4j.version}</version> </dependency> <!-- JLine --> <dependency> <groupId>org.jline</groupId> <artifactId>jline</artifactId> <version>${jline.version}</version> </dependency> </dependencies> <build> <plugins> <!-- Java Compiler --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven.compiler.plugin.version}</version> <configuration> <release>${maven.compiler.release}</release> </configuration> </plugin> <!-- Unit Tests --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>${maven.surefire.plugin.version}</version> </plugin> <!-- Build Executable JAR --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>${maven.shade.plugin.version}</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <createDependencyReducedPom>false</createDependencyReducedPom> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>${main.class}</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> <!-- Code Formatting --> <plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>${spotless.maven.plugin.version}</version> <configuration> <java> <!-- Apply Google Java Format --> <googleJavaFormat /> <!-- General formatting and cleanup --> <trimTrailingWhitespace /> <endWithNewline /> <removeUnusedImports /> </java> </configuration> <executions> <execution> <id>spotless-check</id> <goals> <goal>check</goal> </goals> <phase>verify</phase> </execution> </executions> </plugin> </plugins> </build> </project>

  

Step 2: Define Chat Model Config.

 

OllamaConfig.java

 

package com.sample.app.config; import dev.langchain4j.model.chat.ChatModel; import dev.langchain4j.model.chat.request.ResponseFormat; import dev.langchain4j.model.ollama.OllamaChatModel; public final class OllamaConfig { public static final String DEFAULT_BASE_URL = "http://localhost:11434"; public static final String DEFAULT_MODEL_NAME = "llama3.2"; private OllamaConfig() {} public static ChatModel createChatModel() { String baseUrl = resolveBaseUrl(); String modelName = resolveModelName(); return OllamaChatModel.builder().baseUrl(baseUrl).modelName(modelName).temperature(0.7).build(); } public static ChatModel createStructuredChatModel() { String baseUrl = resolveBaseUrl(); String modelName = resolveModelName(); return OllamaChatModel.builder() .baseUrl(baseUrl) .modelName(modelName) .temperature(0.2) .responseFormat(ResponseFormat.JSON) .build(); } public static String resolveBaseUrl() { return readSetting("OLLAMA_BASE_URL", DEFAULT_BASE_URL); } public static String resolveModelName() { return readSetting("OLLAMA_MODEL", DEFAULT_MODEL_NAME); } private static String readSetting(String key, String defaultValue) { String systemValue = System.getProperty(key); if (systemValue != null && !systemValue.trim().isEmpty()) { return systemValue.trim(); } String environmentValue = System.getenv(key); if (environmentValue != null && !environmentValue.trim().isEmpty()) { return environmentValue.trim(); } return defaultValue; } }

  

Step 3: Define StoryReview model class.

 

StoryReview.java

 

package com.sample.app.model; import dev.langchain4j.model.output.structured.Description; import java.util.Objects; public class StoryReview { @Description("Overall quality rating of the story, integer from 1 to 10") private int rating; @Description( "Concise, actionable feedback for improving the story; use a single line with no embedded newlines") private String feedback; public StoryReview() {} public StoryReview(int rating, String feedback) { this.rating = rating; this.feedback = feedback; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public String getFeedback() { return feedback; } public void setFeedback(String feedback) { this.feedback = feedback; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof StoryReview)) return false; StoryReview that = (StoryReview) o; return rating == that.rating && Objects.equals(feedback, that.feedback); } @Override public int hashCode() { return Objects.hash(rating, feedback); } @Override public String toString() { return "Quality rating: " + rating + "/10\nFeedback: " + feedback; } }

  

Step 4: Define Console specific classes to print the console messages properly.

 

ConsoleColors.java

 

package com.sample.app.console; /** * JLine 3 colour index constants for use with {@link * org.jline.utils.AttributedStyle#foreground(int)}. * * <p>Indices 0–7 map to standard 4-bit ANSI colours ({@code \033[3Xm}). Adding {@code BRIGHT} (8) * gives the bright variant ({@code \033[9Xm}). Indices 16–255 use the 256-colour escape ({@code * \033[38;5;Xm}). */ public final class ConsoleColors { public static final int BLACK = 0; public static final int RED = 1; public static final int GREEN = 2; public static final int YELLOW = 3; public static final int BLUE = 4; public static final int MAGENTA = 5; public static final int CYAN = 6; public static final int WHITE = 7; /** Add to any colour index to get its bright/high-intensity variant. */ public static final int BRIGHT = 8; // Semantic aliases public static final int USER = CYAN | BRIGHT; // 14 public static final int AGENT = GREEN | BRIGHT; // 10 public static final int INFO = CYAN | BRIGHT; // 14 public static final int ERROR = RED | BRIGHT; // 9 public static final int STORY = WHITE; // 7 public static final int GRAY = BLACK | BRIGHT; // 8 (dark gray) public static final int ORANGE = 208; // 256-colour private ConsoleColors() {} }

ConsoleRenderer.java

package com.sample.app.console; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jline.utils.AttributedStringBuilder; import org.jline.utils.AttributedStyle; /** * Renders rich, coloured output to the terminal using JLine 3. * * <p>Supports a lightweight Markdown → ANSI subset: H1/H2/H3 headings, horizontal rules, * ordered/unordered lists, blockquotes, and inline <strong>bold</strong>, <em>italic</em>, and * {@code code} spans. Any unrecognised line is printed verbatim. */ public final class ConsoleRenderer { // ── JLine AttributedStyle palette ───────────────────────────────────────── // // JLine colour indices: 0-7 → standard \033[3Xm // 8-15 → bright \033[9(X-8)m // 16+ → 256-colour \033[38;5;Xm // // Convenience: BRIGHT (=8) | colour gives the bright variant. private static final AttributedStyle RESET = AttributedStyle.DEFAULT; // Banner / headers private static final AttributedStyle BANNER = bold(AttributedStyle.MAGENTA | AttributedStyle.BRIGHT); private static final AttributedStyle H1 = bold(AttributedStyle.YELLOW | AttributedStyle.BRIGHT); private static final AttributedStyle H2 = bold(AttributedStyle.CYAN | AttributedStyle.BRIGHT); private static final AttributedStyle H3 = bold(AttributedStyle.CYAN); // Structural chrome private static final AttributedStyle CHROME = AttributedStyle.DEFAULT.foreground( AttributedStyle.BLACK | AttributedStyle.BRIGHT); // dark gray private static final AttributedStyle AGENT_LABEL = bold(AttributedStyle.GREEN | AttributedStyle.BRIGHT); private static final AttributedStyle PROMPT_STYLE = bold(AttributedStyle.CYAN | AttributedStyle.BRIGHT); // Lists private static final AttributedStyle BULLET = bold(AttributedStyle.GREEN | AttributedStyle.BRIGHT); private static final AttributedStyle SUB_BULLET = AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN); // Inline private static final AttributedStyle BOLD_SPAN = AttributedStyle.DEFAULT.bold(); private static final AttributedStyle ITALIC_SPAN = AttributedStyle.DEFAULT.italic(); private static final AttributedStyle CODE_SPAN = AttributedStyle.DEFAULT.foreground(208).background(236); // orange // on // dark // Status private static final AttributedStyle INFO_STYLE = AttributedStyle.DEFAULT.foreground(AttributedStyle.CYAN | AttributedStyle.BRIGHT); private static final AttributedStyle THINK_STYLE = AttributedStyle.DEFAULT.italic().foreground(AttributedStyle.BLACK | AttributedStyle.BRIGHT); private static final AttributedStyle ERROR_STYLE = bold(AttributedStyle.RED | AttributedStyle.BRIGHT); private static final AttributedStyle FINAL_RESULT = bold(AttributedStyle.GREEN | AttributedStyle.BRIGHT); // Blockquote private static final AttributedStyle BQUOTE_STYLE = AttributedStyle.DEFAULT.italic().foreground(AttributedStyle.WHITE); // ── Widths ───────────────────────────────────────────────────────────────── private static final int BANNER_W = 52; private static final int RULE_W = 50; // ── Inline Markdown pattern (groups in declaration order) ───────────────── // 1: **bold** 2: __bold__ 3: *italic* 4: _italic_ 5: `code` private static final Pattern INLINE_PAT = Pattern.compile( "\\*\\*(.+?)\\*\\*" // 1 **bold** + "|__(.+?)__" // 2 __bold__ + "|(?<![*])\\*(?![*])(.+?)(?<![*])\\*(?![*])" // 3 *italic* + "|(?<![\\w_])_(?!_)(.+?)(?<!_)_(?![\\w_])" // 4 _italic_ + "|`(.+?)`" // 5 `code` ); private ConsoleRenderer() {} // ── Public API ───────────────────────────────────────────────────────────── /** Prints the application welcome banner. */ public static void printBanner() { String bar = "═".repeat(BANNER_W); String title = "✨ Story Teller Workflow ✨"; System.out.println(); System.out.println(s(BANNER, " ╔" + bar + "╗")); System.out.println(s(BANNER, " ║" + center(title, BANNER_W) + "║")); System.out.println(s(BANNER, " ╚" + bar + "╝")); System.out.println(); } /** Prints the "You ❯" input prompt (no trailing newline). */ public static void printPrompt() { System.out.print(s(PROMPT_STYLE, " You ❯ ")); } /** * Prints an agent reply, rendering any Markdown to coloured ANSI output. * * @param text raw text or Markdown returned by the AI agent */ public static void agent(String text) { System.out.println(); System.out.println(s(AGENT_LABEL, " 📖 Story Teller Workflow")); System.out.println(s(CHROME, " " + "─".repeat(RULE_W))); System.out.println(renderMarkdown(text)); } /** Prints an informational line. */ public static void info(String text) { System.out.println(s(INFO_STYLE, " ℹ " + text)); } /** Prints an informational line. */ public static void finalResult(String text) { System.out.println("\n"); System.out.println(s(FINAL_RESULT, text)); } /** Prints the "Thinking…" spinner line. */ public static void thinking() { System.out.println(); System.out.println(s(THINK_STYLE, " ⏳ Thinking…")); System.out.println(); } /** Prints an error line. */ public static void error(String text) { System.out.println(s(ERROR_STYLE, " ✖ " + text)); } // ── Markdown → ANSI ─────────────────────────────────────────────────────── /** * Converts Markdown text to ANSI-coloured terminal output. * * <p>Supported constructs: {@code #} H1–H3, {@code ---} rules, {@code -&#47;*&#47;+} bullets, * {@code 1.} ordered lists, {@code >} blockquotes, {@code **bold**}, {@code *italic*}, and {@code * `code`}. Unrecognised lines are printed verbatim. */ public static String renderMarkdown(String text) { if (text == null || text.isBlank()) return ""; StringBuilder out = new StringBuilder(); boolean prevBlank = false; for (String line : text.split("\n", -1)) { String rendered = renderLine(line); if (rendered.isEmpty()) { if (!prevBlank) out.append('\n'); prevBlank = true; } else { out.append(rendered).append('\n'); prevBlank = false; } } return out.toString(); } // ── Line rendering ───────────────────────────────────────────────────────── private static String renderLine(String line) { // ── Headings ────────────────────────────────────────────────────────── if (line.startsWith("# ")) { return s(H1, " " + line.substring(2).trim().toUpperCase()); } if (line.startsWith("## ")) { return s(H2, " ◆ " + line.substring(3).trim()); } if (line.startsWith("### ")) { return s(H3, " ▸ " + line.substring(4).trim()); } // ── Horizontal rule ─────────────────────────────────────────────────── if (line.matches("^[-─═*]{3,}\\s*$")) { return s(CHROME, " " + "─".repeat(RULE_W)); } // ── Lists ───────────────────────────────────────────────────────────── if (line.matches("^ [\\-*+] .+")) { // indented bullet return s(SUB_BULLET, " ◦ ") + inline(line.substring(4).trim()); } if (line.matches("^[\\-*+] .+")) { // top-level bullet return s(BULLET, " • ") + inline(line.substring(2).trim()); } if (line.matches("^\\d+\\.\\s.+")) { // ordered int dot = line.indexOf(". "); String num = line.substring(0, dot + 1); return s(BULLET, " " + num + " ") + inline(line.substring(dot + 2).trim()); } // ── Blockquote ──────────────────────────────────────────────────────── if (line.startsWith("> ")) { return s(CHROME, " │ ") + s(BQUOTE_STYLE, line.substring(2).trim()); } // ── Empty ───────────────────────────────────────────────────────────── if (line.isBlank()) return ""; // ── Normal text ─────────────────────────────────────────────────────── return " " + inline(line); } // ── Inline Markdown ──────────────────────────────────────────────────────── /** * Applies inline Markdown spans to a raw text string. Bold is matched before italic to avoid * partial `**` collisions. */ private static String inline(String text) { StringBuilder sb = new StringBuilder(); Matcher m = INLINE_PAT.matcher(text); int cursor = 0; while (m.find()) { sb.append(text, cursor, m.start()); // literal text before span if (m.group(1) != null) sb.append(s(BOLD_SPAN, m.group(1))); // **bold** else if (m.group(2) != null) sb.append(s(BOLD_SPAN, m.group(2))); // __bold__ else if (m.group(3) != null) sb.append(s(ITALIC_SPAN, m.group(3))); // *italic* else if (m.group(4) != null) sb.append(s(ITALIC_SPAN, m.group(4))); // _italic_ else if (m.group(5) != null) sb.append(s(CODE_SPAN, " " + m.group(5) + " ")); // `code` cursor = m.end(); } sb.append(text.substring(cursor)); // trailing literal text return sb.toString(); } // ── Helpers ──────────────────────────────────────────────────────────────── /** Builds a styled ANSI string: applies {@code style}, appends {@code text}, then resets. */ private static String s(AttributedStyle style, String text) { return new AttributedStringBuilder().style(style).append(text).style(RESET).toAnsi(); } /** Convenience: DEFAULT foreground + bold. */ private static AttributedStyle bold(int color) { return AttributedStyle.DEFAULT.bold().foreground(color); } /** Centers {@code text} within a field of {@code width} characters. */ private static String center(String text, int width) { int pad = width - text.length(); int left = Math.max(0, pad / 2); int right = Math.max(0, pad - left); return " ".repeat(left) + text + " ".repeat(right); } }

  

Step 5: Define agents and the listener class.

 

StoryWriter.java

 

package com.sample.app.agents; import dev.langchain4j.agentic.Agent; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface StoryWriter { @UserMessage( """ You are the Story Writer in an iterative children's story creation workflow. Create a short, engaging children's story based on the user's story idea. Requirements: 1. Use simple language suitable for children ages 5 to 10. 2. Create interesting characters and a clear beginning, middle, and ending. 3. Include a positive message or lesson. 4. Make the story imaginative, warm, and engaging. 5. Give the story a suitable title. Important: - Return only the story. - Do not include explanations or editorial comments. - Keep the story concise. Story idea: {{storyIdea}} """) @Agent( name = "storyWriter", description = """ Creates an engaging children's story from a given story idea. Produces the initial story that will be evaluated and improved by subsequent agents in the iterative workflow. """) String writeStory(@V("storyIdea") String storyIdea); }

  

StoryReviewer.java

 

package com.sample.app.agents; import com.sample.app.model.StoryReview; import dev.langchain4j.agentic.Agent; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface StoryReviewer { @UserMessage( """ You are the Story Reviewer in an iterative children's story improvement workflow. Review the provided story carefully and evaluate its overall quality. Evaluate the story based on: 1. Grammar and language Is the language clear and grammatically correct? 2. Clarity Are the characters, events, and ideas easy for children to understand? 3. Consistency Are characters, events, and story details consistent? 4. Pacing Does the story flow naturally without unnecessary repetition? 5. Age appropriateness Is the vocabulary, theme, and content appropriate for children ages 5 to 10? 6. Story quality Is the story interesting, imaginative, and emotionally engaging? 7. Lesson Is the intended message or lesson clear? Give the story an overall quality rating from 1 to 10. Scoring guidelines: - 1-4: Major improvements required - 5-6: Several improvements required - 7: Good but needs improvement - 8: Very good - 9: Excellent - 10: Outstanding Also provide concise, actionable feedback that the Story Improver can use to improve the story. Important: - Do not rewrite the story. - Do not provide unnecessary explanations. - Identify the most important improvements. - Focus the feedback on actionable changes. - Return the rating and feedback in the requested structured format. Current story: {{story}} """) @Agent( name = "storyReviewer", description = """ Evaluates the current children's story for grammar, clarity, consistency, pacing, age appropriateness, creativity, and overall quality. Returns a quality rating and actionable feedback that can be used by the Story Improver. """) StoryReview reviewStory(@V("story") String story); }

  

StoryImprover.java

package com.sample.app.agents; import com.sample.app.model.StoryReview; import dev.langchain4j.agentic.Agent; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface StoryImprover { @UserMessage( """ You are the Story Improver in an iterative children's story improvement workflow. The Story Reviewer has evaluated the current story and provided a quality rating and feedback. Your responsibility is to improve the story based on that feedback. Improve the story for: 1. Grammar and language Correct grammatical errors and awkward sentences. 2. Clarity Make characters, events, and ideas easier to understand. 3. Consistency Fix inconsistencies in character names, personalities, events, or story details. 4. Pacing Remove unnecessary repetition and improve the story flow. 5. Age appropriateness Ensure the vocabulary, themes, and writing style are suitable for children ages 5 to 10. 6. Story quality Make the story more engaging and imaginative while preserving its original intent. 7. Lesson Make the story's message clear without making it feel forced. Important: - Preserve the original story's core idea. - Do not introduce unrelated characters or events. - Use the review feedback to guide your improvements. - Do not make changes that are unrelated to the reviewer feedback. - Improve the existing story rather than completely replacing it. - Keep the title. - Return ONLY the improved story. - Do not include explanations, comments, or editorial notes. Current story: {{story}} Reviewer assessment: {{storyReview}} """) @Agent( name = "storyImprover", description = """ Improves an existing children's story using the quality rating and actionable feedback provided by the Story Reviewer. Preserves the original story's intent while addressing the identified quality issues and producing an improved version for the next review iteration. """) String improveStory(@V("story") String story, @V("storyReview") StoryReview review); }

   

AgentWorkflowListener.java

 

package com.sample.app.agents; import com.sample.app.console.ConsoleRenderer; import dev.langchain4j.agentic.observability.AgentListener; import dev.langchain4j.agentic.observability.AgentRequest; import dev.langchain4j.agentic.observability.AgentResponse; import dev.langchain4j.agentic.scope.AgenticScope; import java.util.Map; public class AgentWorkflowListener implements AgentListener { @Override public void beforeAgentInvocation(AgentRequest request) { if (!request.agent().leaf()) { return; } printInitialStateIfNeeded(request); ConsoleRenderer.info(nodeTitle(request.agent().outputKey())); ConsoleRenderer.thinking(); } @Override public void afterAgentInvocation(AgentResponse response) { if (!response.agent().leaf()) { return; } String outputKey = response.agent().outputKey(); AgenticScope scope = response.agenticScope(); // Store the agent output in the shared workflow state. scope.writeState(outputKey, response.output()); // Render the agent output. ConsoleRenderer.agent(outputLabel(outputKey) + "\n\n" + response.output()); // Show the state update. ConsoleRenderer.info("State updated: " + outputKey); System.out.println(" " + outputKey + " = " + scope.readState(outputKey, null)); System.out.println(); printState(scope); } @Override public boolean inheritedBySubagents() { return true; } private void printInitialStateIfNeeded(AgentRequest request) { AgenticScope scope = request.agenticScope(); if (scope.executionContext("initialStatePrinted") != null) { return; } /* * The workflow starts with storyIdea as the initial state. Store it in the * shared AgenticScope so that subsequent agents can build on the state produced * by previous agents. */ if (!scope.hasState("storyIdea") && request.inputs().containsKey("storyIdea")) { scope.writeState("storyIdea", request.inputs().get("storyIdea")); } scope.writeExecutionContext("initialStatePrinted", Boolean.TRUE); printState(scope); System.out.println(); } private void printState(AgenticScope scope) { ConsoleRenderer.info("workflow state"); ConsoleRenderer.info("-".repeat(100)); Map<String, Object> stateObj = scope.state(); for (String key : stateObj.keySet()) { Object value = stateObj.get(key); if (value != null) { String valueStr = value.toString(); if (valueStr.length() > 100) { valueStr = valueStr.substring(0, 100) + "..."; } ConsoleRenderer.info(key + " -> " + valueStr); } else { ConsoleRenderer.info(key + " -> null"); } } ConsoleRenderer.info("-".repeat(100)); } private String nodeTitle(String outputKey) { if ("plot".equals(outputKey)) { return "NODE 1 · Story Planner"; } if ("characters".equals(outputKey)) { return "NODE 2 · Character Designer"; } if ("draft".equals(outputKey)) { return "NODE 3 · Story Writer"; } if ("finalStory".equals(outputKey)) { return "NODE 4 · Story Editor"; } return "NODE · " + outputKey; } private String outputLabel(String outputKey) { if ("plot".equals(outputKey)) { return "Story Planner Output"; } if ("characters".equals(outputKey)) { return "Character Designer Output"; } if ("draft".equals(outputKey)) { return "Story Writer Output"; } if ("finalStory".equals(outputKey)) { return "Story Editor Output"; } return "Agent Output"; } }

   

Step 6: Define main Application class.

 

App.java

package com.sample.app; import com.sample.app.agents.AgentWorkflowListener; import com.sample.app.agents.StoryImprover; import com.sample.app.agents.StoryReviewer; import com.sample.app.agents.StoryWriter; import com.sample.app.config.OllamaConfig; import com.sample.app.console.ConsoleRenderer; import com.sample.app.model.StoryReview; import dev.langchain4j.agentic.AgenticServices; import dev.langchain4j.agentic.UntypedAgent; import dev.langchain4j.agentic.scope.ResultWithAgenticScope; import dev.langchain4j.model.chat.ChatModel; import java.util.LinkedHashMap; import java.util.Map; import java.util.Scanner; public class App { public static void main(String[] args) { ConsoleRenderer.printBanner(); System.out.println("Enter Your Story Idea"); Scanner scanner = new Scanner(System.in); String storyIdea = scanner.nextLine().trim(); if (storyIdea.isEmpty()) { ConsoleRenderer.error("A story idea is required to run the workflow."); return; } ChatModel chatModel = OllamaConfig.createChatModel(); ChatModel structuredChatModel = OllamaConfig.createStructuredChatModel(); // Define Agents StoryWriter storyWriter = AgenticServices.agentBuilder(StoryWriter.class) .chatModel(chatModel) .outputKey("story") .build(); StoryReviewer storyReviewer = AgenticServices.agentBuilder(StoryReviewer.class) .chatModel(structuredChatModel) .outputKey("storyReview") .build(); StoryImprover storyImprover = AgenticServices.agentBuilder(StoryImprover.class) .chatModel(chatModel) .outputKey("story") .build(); UntypedAgent storyImprovementLoop = AgenticServices.loopBuilder() .subAgents(storyReviewer, storyImprover) .maxIterations(5) .testExitAtLoopEnd(true) .exitCondition( (agenticScope, loopCounter) -> { StoryReview storyReview = agenticScope.readState("storyReview", null); double score = (storyReview != null) ? storyReview.getRating() : 0; return loopCounter <= 3 ? score >= 9 : score >= 7; }) .outputKey("story") .build(); UntypedAgent storyWorkflow = AgenticServices.sequenceBuilder() .name("sequentialStoryWorkflow") .subAgents(storyWriter, storyImprovementLoop) .listener(new AgentWorkflowListener()) .outputKey("story") .build(); Map<String, Object> input = new LinkedHashMap<>(); input.put("storyIdea", storyIdea); ResultWithAgenticScope<String> result = storyWorkflow.invokeWithAgenticScope(input); ConsoleRenderer.finalResult("Final Story"); ConsoleRenderer.finalResult(result.result()); } }

Build the application using Maven:

Navigate to the project where pom.xml is located and execute following command to generate jar file.

mvn clean package

   

Run the Application

 

java -jar ./target/loop-workflow-demo-1.0.0.jar
$java -jar ./target/loop-workflow-demo-1.0.0.jar ╔════════════════════════════════════════════════════╗ ║ ✨ Story Teller Workflow ✨ ║ ╚════════════════════════════════════════════════════╝ Enter Your Story Idea

   

Enter your story idea, for example: An Inspiring Journey of a Cricketer.

 

You can download this application from this link.

 

 

 

Previous                                                    Next                                                    Home
Read Entire Article