Club.noww.in
This is continuation to my previous post. In the previous post, I explained how to create sequential handoff pattern using untyped agents, now I am going to explain this with typed agents.
When building an agentic workflow, one of the first architectural questions we need to answer is: How should the different agents or nodes interact with each other?
We already know that an agentic workflow is built from three fundamental components:
· State: the shared memory of the workflow
· Nodes: the individual units that perform work
· Edges: the logic that determines how execution moves between nodes
Once we have these building blocks, the next question is, How do we connect these nodes to create a complete workflow?
There are several common orchestration patterns that help us answer this question. The simplest one is the Sequential Handoff Pattern.
1. What is the Sequential Handoff Pattern?
The Sequential Handoff Pattern is the simplest orchestration pattern where nodes execute one after another in a fixed, linear sequence.
For example:
Start │ ▼ Node A │ ▼ Node B │ ▼ Node C │ ▼ Result
Node A completes its work and passes control to Node B. Node B completes its work and passes control to Node C. Finally, Node C produces the final result.
There is no dynamic decision about which node should execute next. The execution path is predefined. This is why we can think of this pattern as an assembly line. Just like a manufacturing assembly line, each stage performs a specific operation and passes the partially completed product to the next stage.
2. Story Book Agent
The user provides a simple idea, "Write a children's story about a rabbit who wants to become a great runner."
The workflow could looks like below.
Here:
· Story Planner Agent: It converts the user's story idea into a structured story plan.
· Character Agent: Design the characters needed for the planned story.
· Story Writer Agent: Turn the story plan and character definitions into a complete story.
· Story Reviewer Agent: Review and polish the story produced by the Writer.
The easiest way to remember their responsibilities is:
· Planner → What happens?
· Character Agent → Who is involved?
· Writer → Tell the story.
· Reviewer → Check and improve the story.
Let’s build the story telling workflow
Define interfaces that helps to define Agents behavior.
StoryPlanner.java
public interface StoryPlanner { ( """ You are the Story Planner, the first agent in a sequential story-creation workflow. Your responsibility is to transform the user's simple story idea into a clear and engaging plot that the next agents can build upon. Follow these steps: 1. Understand the central idea and intended theme. 2. Define how the story begins and introduce the situation. 3. Identify the main problem or conflict. 4. Define the important events that move the story forward. 5. Describe the climax or most important turning point. 6. Define a satisfying and meaningful ending. Create the plot using exactly these headings: Beginning Main conflict Important events Climax Ending Guidelines: - Keep the story simple and easy to understand. - Make the plot suitable for children ages 5 to 10. - Keep the story warm, positive, and imaginative. - Avoid unnecessary characters or subplots. - Make sure the conflict has a clear resolution. - Do not write the complete story yet. - Focus only on creating the story blueprint for the next agent. Story idea: {{storyIdea}} Your output will be handed off to the Character Designer, who will use this plot to determine which characters are needed. """) ( name = "storyPlanner", description = """ Plans the overall structure of a children's story. Takes the user's story idea and transforms it into a clear beginning, conflict, key events, climax, and ending. Hands the resulting story plot to the Character Designer. """) String createPlot(@V("storyIdea") String storyIdea); }
CharacterDesigner.java
public interface CharacterDesigner { ( """ You are the Character Designer, the second agent in a sequential story-creation workflow. The Story Planner has already created the story plot. Your responsibility is to design the characters needed to tell that story effectively. Read both the original story idea and the plot from the previous agent. For each important character, provide: Name Type/species Personality Role in the story Character design guidelines: - Create only the characters that are necessary for the plot. - Keep the cast small and easy for children to remember. - Give each character a distinct personality. - Make the characters suitable for children ages 5 to 10. - Make sure every character has a meaningful role in the story. - Ensure the characters support the conflict and events described in the plot. - Avoid introducing characters that are not needed. - Do not write the story yet. Original story idea: {{storyIdea}} Plot created by the Story Planner: {{plot}} Your output will be handed off to the Story Writer. The Story Writer will use your character descriptions together with the plot to create the complete story draft. """) ( name = "characterDesigner", description = """ Designs the characters needed to bring the planned story to life. Uses the original story idea and the plot received from the Story Planner to define a small cast with clear personalities and story roles. Hands the character descriptions to the Story Writer. """) String designCharacters(@V("storyIdea") String storyIdea, @V("plot") String plot); }
StoryWriter.java
public interface StoryWriter { ( """ You are the Story Writer, the third agent in a sequential story-creation workflow. Two agents have already completed their work: - The Story Planner created the plot. - The Character Designer created the characters. Your responsibility is to combine their outputs with the original story idea and turn them into a complete, engaging children's story. Writing requirements: - Give the story a clear and appealing title. - Follow the plot created by the Story Planner. - Use the characters designed by the Character Designer. - Preserve the intended conflict, important events, climax, and ending from the plot. - Give the characters distinct personalities and meaningful actions. - Use simple, friendly, and imaginative language. - Keep the story suitable for children ages 5 to 10. - Maintain a clear beginning, middle, and ending. - Make the story engaging without becoming unnecessarily long. - Do not introduce major characters or plot elements that conflict with the previous agents' work. Important: You are creating a draft, not the final edited version. Focus on storytelling and narrative flow. Do not include explanations about your writing process. Story idea: {{storyIdea}} Plot from the Story Planner: {{plot}} Characters from the Character Designer: {{characters}} Your completed draft will be handed off to the Story Editor, who will review and polish it before it is presented as the final story. """) ( name = "storyWriter", description = """ Turns the story plan and character designs into a complete children's story draft. Combines the original idea, planned plot, and character profiles into a coherent narrative with a title, engaging events, and age-appropriate language. Hands the completed draft to the Story Editor for refinement. """) String writeStory( @V("storyIdea") String storyIdea, @V("plot") String plot, @V("characters") String characters); }
StoryEditor.java
public interface StoryEditor { ( """ You are the Story Editor, the final agent in a sequential story-creation workflow. The Story Writer has created a complete children's story draft. Your responsibility is to review, refine, and polish that draft so it is ready for the final reader. Review the story carefully for: 1. Grammar and language Correct grammatical errors and awkward sentences. 2. Clarity Make sure events, characters, and ideas are easy to understand. 3. Consistency Ensure character names, personalities, events, and story details remain consistent throughout the story. 4. Pacing Remove unnecessary repetition and make sure the story flows naturally from beginning to ending. 5. Age appropriateness Ensure the vocabulary, themes, conflict, and writing style are appropriate for children ages 5 to 10. 6. Story quality Preserve the imagination, warmth, lesson, and emotional appeal of the original story. Important: - Do not completely rewrite the story unless necessary. - Preserve the Story Writer's core idea and narrative. - Do not introduce unrelated characters or events. - Do not add explanations, comments, or editorial notes. - Return only the polished final story. - Keep the title. Draft story from the Story Writer: {{draft}} This is the final stage of the workflow. Your output will be returned to the user as the final story. """) ( name = "storyEditor", description = """ Reviews and polishes the story draft created by the Story Writer. Improves grammar, clarity, consistency, pacing, and age appropriateness while preserving the original story's intent and creativity. Produces the final story that is ready for the reader. """) String editStory(@V("draft") String draft); }
Define the agents using AgenticServices.
StoryPlanner storyPlanner = AgenticServices.agentBuilder(StoryPlanner.class) .chatModel(chatModel) .outputKey("plot") .build(); CharacterDesigner characterDesigner = AgenticServices.agentBuilder(CharacterDesigner.class) .chatModel(chatModel) .outputKey("characters") .build(); StoryWriter storyWriter = AgenticServices.agentBuilder(StoryWriter.class) .chatModel(chatModel) .outputKey("draft") .build(); StoryEditor storyEditor = AgenticServices.agentBuilder(StoryEditor.class) .chatModel(chatModel) .outputKey("story") .build();
Define myStoryTellingAgent using AgenticServices.sequenceBuilder().
UntypedAgent myStoryTellingAgent = AgenticServices.sequenceBuilder() .name("sequentialStoryWorkflow") .description( """ Creates a children's story through a deterministic sequence of specialized agents. Each agent completes one stage of the story creation process and hands its output to the next agent: Story Planner -> Character Designer -> Story Writer -> Story Editor The workflow starts with a simple story idea and progressively transforms it into a polished final story. """) .subAgents( // Handoff 1: Story Planner -> Character Designer storyPlanner, // Handoff 2: Character Designer -> Story Writer characterDesigner, // Handoff 3: Story Writer -> Story Editor storyWriter, storyEditor) .listener(new AgentWorkflowListener()) .outputKey("finalStory") .build();
Use ‘invokeWithAgenticScope’ method to trigger the workflow.
ResultWithAgenticScope<String> result = myStoryTellingAgent.invokeWithAgenticScope(input); ConsoleRenderer.agent(result.result());
As you see above snippet, we mentioned following as sub agents to the sequential story workflow.
· storyPlanner
· characterDesigner
· storyWriter
· storyEditor
Follow below step-by-step procedure to build the complete working application.
Step 1: Create new maven project 'sequential-handoff-pattern-typed-agents'.
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>sequential-handoff-pattern-typed-agents</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 OllamaConfig class.
Here, we are using a locally hosted Llama 3.2 instance. Make sure Ollama is running on your computer and that the `llama3.2` model is available.
OllamaConfig.java
package com.sample.app.model; import dev.langchain4j.model.chat.ChatModel; 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 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 Console utility classes to print the llm responses.
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); // 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 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 -/*/+} 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 4: Define Agent and Workflow related classes.
StoryPlanner.java
package com.sample.app.agents; import dev.langchain4j.agentic.Agent; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface StoryPlanner { ( """ You are the Story Planner, the first agent in a sequential story-creation workflow. Your responsibility is to transform the user's simple story idea into a clear and engaging plot that the next agents can build upon. Follow these steps: 1. Understand the central idea and intended theme. 2. Define how the story begins and introduce the situation. 3. Identify the main problem or conflict. 4. Define the important events that move the story forward. 5. Describe the climax or most important turning point. 6. Define a satisfying and meaningful ending. Create the plot using exactly these headings: Beginning Main conflict Important events Climax Ending Guidelines: - Keep the story simple and easy to understand. - Make the plot suitable for children ages 5 to 10. - Keep the story warm, positive, and imaginative. - Avoid unnecessary characters or subplots. - Make sure the conflict has a clear resolution. - Do not write the complete story yet. - Focus only on creating the story blueprint for the next agent. Story idea: {{storyIdea}} Your output will be handed off to the Character Designer, who will use this plot to determine which characters are needed. """) ( name = "storyPlanner", description = """ Plans the overall structure of a children's story. Takes the user's story idea and transforms it into a clear beginning, conflict, key events, climax, and ending. Hands the resulting story plot to the Character Designer. """) String createPlot(@V("storyIdea") String storyIdea); }
CharacterDesigner.java
package com.sample.app.agents; import dev.langchain4j.agentic.Agent; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface CharacterDesigner { ( """ You are the Character Designer, the second agent in a sequential story-creation workflow. The Story Planner has already created the story plot. Your responsibility is to design the characters needed to tell that story effectively. Read both the original story idea and the plot from the previous agent. For each important character, provide: Name Type/species Personality Role in the story Character design guidelines: - Create only the characters that are necessary for the plot. - Keep the cast small and easy for children to remember. - Give each character a distinct personality. - Make the characters suitable for children ages 5 to 10. - Make sure every character has a meaningful role in the story. - Ensure the characters support the conflict and events described in the plot. - Avoid introducing characters that are not needed. - Do not write the story yet. Original story idea: {{storyIdea}} Plot created by the Story Planner: {{plot}} Your output will be handed off to the Story Writer. The Story Writer will use your character descriptions together with the plot to create the complete story draft. """) ( name = "characterDesigner", description = """ Designs the characters needed to bring the planned story to life. Uses the original story idea and the plot received from the Story Planner to define a small cast with clear personalities and story roles. Hands the character descriptions to the Story Writer. """) String designCharacters(@V("storyIdea") String storyIdea, @V("plot") String plot); }
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 { ( """ You are the Story Writer, the third agent in a sequential story-creation workflow. Two agents have already completed their work: - The Story Planner created the plot. - The Character Designer created the characters. Your responsibility is to combine their outputs with the original story idea and turn them into a complete, engaging children's story. Writing requirements: - Give the story a clear and appealing title. - Follow the plot created by the Story Planner. - Use the characters designed by the Character Designer. - Preserve the intended conflict, important events, climax, and ending from the plot. - Give the characters distinct personalities and meaningful actions. - Use simple, friendly, and imaginative language. - Keep the story suitable for children ages 5 to 10. - Maintain a clear beginning, middle, and ending. - Make the story engaging without becoming unnecessarily long. - Do not introduce major characters or plot elements that conflict with the previous agents' work. Important: You are creating a draft, not the final edited version. Focus on storytelling and narrative flow. Do not include explanations about your writing process. Story idea: {{storyIdea}} Plot from the Story Planner: {{plot}} Characters from the Character Designer: {{characters}} Your completed draft will be handed off to the Story Editor, who will review and polish it before it is presented as the final story. """) ( name = "storyWriter", description = """ Turns the story plan and character designs into a complete children's story draft. Combines the original idea, planned plot, and character profiles into a coherent narrative with a title, engaging events, and age-appropriate language. Hands the completed draft to the Story Editor for refinement. """) String writeStory( @V("storyIdea") String storyIdea, @V("plot") String plot, @V("characters") String characters); }
StoryEditor.java
package com.sample.app.agents; import dev.langchain4j.agentic.Agent; import dev.langchain4j.service.UserMessage; import dev.langchain4j.service.V; public interface StoryEditor { ( """ You are the Story Editor, the final agent in a sequential story-creation workflow. The Story Writer has created a complete children's story draft. Your responsibility is to review, refine, and polish that draft so it is ready for the final reader. Review the story carefully for: 1. Grammar and language Correct grammatical errors and awkward sentences. 2. Clarity Make sure events, characters, and ideas are easy to understand. 3. Consistency Ensure character names, personalities, events, and story details remain consistent throughout the story. 4. Pacing Remove unnecessary repetition and make sure the story flows naturally from beginning to ending. 5. Age appropriateness Ensure the vocabulary, themes, conflict, and writing style are appropriate for children ages 5 to 10. 6. Story quality Preserve the imagination, warmth, lesson, and emotional appeal of the original story. Important: - Do not completely rewrite the story unless necessary. - Preserve the Story Writer's core idea and narrative. - Do not introduce unrelated characters or events. - Do not add explanations, comments, or editorial notes. - Return only the polished final story. - Keep the title. Draft story from the Story Writer: {{draft}} This is the final stage of the workflow. Your output will be returned to the user as the final story. """) ( name = "storyEditor", description = """ Reviews and polishes the story draft created by the Story Writer. Improves grammar, clarity, consistency, pacing, and age appropriateness while preserving the original story's intent and creativity. Produces the final story that is ready for the reader. """) String editStory(@V("draft") String draft); }
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; public class AgentWorkflowListener implements AgentListener { public void beforeAgentInvocation(AgentRequest request) { if (!request.agent().leaf()) { return; } printInitialStateIfNeeded(request); ConsoleRenderer.info(nodeTitle(request.agent().outputKey())); ConsoleRenderer.thinking(); } 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(); } 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); ConsoleRenderer.info("Initial workflow state"); printState(scope); System.out.println(); } private void printState(AgenticScope scope) { printStateValue(scope, "storyIdea"); printStateValue(scope, "plot"); printStateValue(scope, "characters"); printStateValue(scope, "draft"); printStateValue(scope, "finalStory"); } private void printStateValue(AgenticScope scope, String key) { Object value = scope.readState(key, null); String displayValue = value == null ? "<not set>" : value.toString(); System.out.println(" " + key + " = " + displayValue); } 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"; } }
AgentWorkflowFactory.java
package com.sample.app.agents; import dev.langchain4j.agentic.AgenticServices; import dev.langchain4j.agentic.UntypedAgent; import dev.langchain4j.model.chat.ChatModel; public final class AgentWorkflowFactory { private AgentWorkflowFactory() {} public static UntypedAgent createWorkflow(ChatModel chatModel) { StoryPlanner storyPlanner = AgenticServices.agentBuilder(StoryPlanner.class) .chatModel(chatModel) .outputKey("plot") .build(); CharacterDesigner characterDesigner = AgenticServices.agentBuilder(CharacterDesigner.class) .chatModel(chatModel) .outputKey("characters") .build(); StoryWriter storyWriter = AgenticServices.agentBuilder(StoryWriter.class) .chatModel(chatModel) .outputKey("draft") .build(); StoryEditor storyEditor = AgenticServices.agentBuilder(StoryEditor.class) .chatModel(chatModel) .outputKey("story") .build(); // ------------------------------------------------------------ // Sequential Handoff Workflow // ------------------------------------------------------------ return AgenticServices.sequenceBuilder() .name("sequentialStoryWorkflow") .description( """ Creates a children's story through a deterministic sequence of specialized agents. Each agent completes one stage of the story creation process and hands its output to the next agent: Story Planner -> Character Designer -> Story Writer -> Story Editor The workflow starts with a simple story idea and progressively transforms it into a polished final story. """) .subAgents( // Handoff 1: Story Planner -> Character Designer storyPlanner, // Handoff 2: Character Designer -> Story Writer characterDesigner, // Handoff 3: Story Writer -> Story Editor storyWriter, storyEditor) .listener(new AgentWorkflowListener()) .outputKey("finalStory") .build(); } }
Step 5: Define main application class.
App.java
package com.sample.app; import com.sample.app.agents.AgentWorkflowFactory; import com.sample.app.console.ConsoleRenderer; import com.sample.app.model.OllamaConfig; 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(); Scanner scanner = new Scanner(System.in); ConsoleRenderer.info("Enter your story idea:"); ConsoleRenderer.printPrompt(); String storyIdea = scanner.nextLine().trim(); if (storyIdea.isEmpty()) { ConsoleRenderer.error("A story idea is required to run the workflow."); return; } ChatModel chatModel = OllamaConfig.createChatModel(); UntypedAgent workflow = AgentWorkflowFactory.createWorkflow(chatModel); Map<String, Object> input = new LinkedHashMap<>(); input.put("storyIdea", storyIdea); try { ResultWithAgenticScope<String> result = workflow.invokeWithAgenticScope(input); ConsoleRenderer.info("Workflow completed successfully."); ConsoleRenderer.agent(result.result()); } catch (Exception exception) { handleWorkflowFailure(exception); } } private static void handleWorkflowFailure(Exception exception) { String baseUrl = OllamaConfig.resolveBaseUrl(); ConsoleRenderer.error("Workflow execution failed."); ConsoleRenderer.info("Unable to connect to Ollama at " + baseUrl + "."); ConsoleRenderer.info("Please make sure Ollama is running and the model is available."); if (exception.getMessage() != null && !exception.getMessage().isBlank()) { ConsoleRenderer.info("Technical details: " + exception.getMessage()); } } }
Total project structure looks like below.
Build the application using Maven:
Navigate to the project root folder where pom.xml is located and execute below command.
mvn clean package
Run the generated executable JAR:
java -jar ./target/sequential-handoff-pattern-typed-agents-1.0.0.jar
$ java -jar ./target/sequential-handoff-pattern-typed-agents-1.0.0.jar ╔════════════════════════════════════════════════════╗ ║ ✨ Story Teller Workflow ✨ ║ ╚════════════════════════════════════════════════════╝ ℹ Enter your story idea: You ❯
Enter a story idea when prompted. For example: Tell me story about a sage lived in India
You can download the Application from this link.
Previous Next Home













English (US)