As AI applications become more sophisticated, a single agent is often not enough to handle every type of user request. Different requests may require different expertise, instructions, tools, or processing logic. For example, a medical question should be handled differently from a legal question, while a technical question may require an entirely different agent.
One common approach to solving this problem is to introduce a router agent. The router first analyzes the user's request, determines its category or intent, and then directs the request to the appropriate specialized agent.
For example, a user might ask:
I broke my leg. What should I do? → Medical Agent
What are my rights as a tenant? → Legal Agent
How do I fix a NullPointerException in Java? → Technical Agent
This pattern is known as a conditional workflow because the next step in the workflow depends on a condition, in this case, the category identified by the router.
LangChain4j provides support for building such agentic workflows using components such as AgenticServices, conditionalBuilder(), sequenceBuilder(), and shared agentic state. This allows us to compose multiple specialized agents into a single workflow without putting all the logic into one large agent.
In this post, we will build a simple conditional workflow, the workflow will invoke the corresponding specialized expert agent based on the user query.
The overall flow will look like this:
User Request → Category Router → Conditional Routing → Specialized Expert Agent → Response
Let's see how this can be implemented using LangChain4j.
1. Conditional Workflow Use cases
Conditional workflows are useful whenever the next agent or processing step depends on the result of a previous decision. Here are several practical use cases you can mention in the post and later implement one of them.
1.1 Customer Support Request Routing
Classify a customer request and route it to the appropriate agent.
Flow:
User Request → Classifier → Billing / Technical / Account / Shipping Agent
Example:
· My payment was charged twice → Billing Agent
· I can't log in to my account → Account Support Agent
1.2 Software Development Assistant
Classify a developer's request and route it to a specialized coding agent.
Flow:
Request → Classifier → Java / SQL / DevOps / Security Agent
Example:
· Optimize this PostgreSQL query → Database Agent
· Create a Kubernetes deployment → DevOps Agent
· Review this code for vulnerabilities → Security Agent
1.3 Document Processing
Determine the type of uploaded document and use the appropriate processing workflow.
Flow:
Document → Document Classifier → Invoice / Resume / Contract / Report Processor
For example:
· Invoice Agent → Extract invoice details
· Resume Agent → Extract candidate information
· Contract Agent → Identify important clauses
1.4 E-Commerce Shopping Assistant
Classify the customer's intent and route it to the appropriate agent.
Flow:
User Request → Intent Classifier → Product / Order / Return / Recommendation Agent
Example:
· Show me laptops under ₹70,000 → Product Search Agent
· Where is my order? → Order Tracking Agent
· I want to return my headphones → Returns Agent
1.5 Travel Planning Assistant
Identify what the user wants to do and invoke the appropriate travel agent.
Flow:
Request → Intent Classifier → Flight / Hotel / Restaurant / Activity Agent
Example:
· Find flights from Bangalore to Delhi → Flight Agent
· Find a hotel near the airport → Hotel Agent
· What are some things to do in Delhi? → Activity Agent
1.6 Content Creation Workflow
Classify the type of content requested and invoke the appropriate content-generation agent.
Flow:
Request → Content Classifier → Blog / Social Media / Email / Documentation Agent
For example:
· Write a technical blog about Kafka → Blog Agent
· Create a LinkedIn post about this feature → Social Media Agent
· Write an announcement email → Email Agent
2. Example: Content Creation Workflow
Use Case: User provides a content request, and the workflow determines what type of content is being requested
For example:
· Write a blog post explaining Java virtual threads -> handled by Blog Agent
· Create a LinkedIn post about our new AI feature -> Social Media Agent
· Write an announcement email for our new product release → Email Agent
Content Router Agent
public interface ContentRouter {
@UserMessage(
"""
Analyze the following user request and categorize it as
'blog', 'social_media' or 'email'.
Use 'blog' when the user wants a blog post, article,
tutorial, or long-form technical/content article.
Use 'social_media' when the user wants content for
LinkedIn, X/Twitter, Facebook, Instagram, or similar
social media platforms.
Use 'email' when the user wants an email, announcement,
newsletter, or email communication.
If the request doesn't belong to any of these categories,
categorize it as 'unknown'.
Reply with only one of these words and nothing else.
The user request is: '{{request}}'.
""")
@Agent("Categorizes a content creation request")
ContentType classify(@V("request") String request);
}
As you above snippet, Content Router is responsible to take user request and identify the category of the request. It returns one of the following enum.
public enum ContentType {
BLOG,
SOCIAL_MEDIA,
EMAIL,
UNKNOWN
}
Let's define respective special agents.
public interface BlogExpert {
@UserMessage(
"""
You are an expert technical content writer.
Create a well-structured blog post based on the user's
request.
The blog should:
- Have a clear title
- Start with an engaging introduction
- Use appropriate headings
- Explain concepts clearly
- Include examples where useful
- End with a concise conclusion
Return only the blog content.
The user request is:
{{request}}
""")
@Agent("Creates technical blog posts and long-form articles")
String createBlog(@V("request") String request);
}
public interface EmailExpert {
@UserMessage(
"""
You are a professional business communication writer.
Write a clear and professional email based on the
user's request.
Include:
- A suitable subject
- A professional greeting
- A concise and clear message
- A professional closing
Return only the email content.
The user request is:
{{request}}
""")
@Agent("Creates professional emails")
String createEmail(@V("request") String request);
}
public interface SocialMediaExpert {
@UserMessage(
"""
You are a professional social media content creator.
Create an engaging social media post based on the
user's request.
Keep the content concise and engaging.
Use appropriate formatting and hashtags when useful.
Return only the social media post.
The user request is:
{{request}}
""")
@Agent("Creates social media posts")
String createPost(@V("request") String request);
}
public interface UnknownContentExpert {
@UserMessage(
"""
You are a general content creation assistant.
The user's request does not clearly belong to the
supported content types: blog, social media, or email.
Analyze the request and provide a helpful response.
If appropriate, explain what type of content the user
should request.
The user request is:
{{request}}
""")
@Agent("Handles unsupported or unknown content requests")
String handle(@V("request") String request);
}
Content Creator Workflow Interface
This is the public interface that your application will use.
public interface ContentCreator {
@Agent
String create(@V("request") String request);
}
The application doesn't need to know which specialist agent will execute the request.
It simply calls:
String response = contentCreator.create(request);
The conditional workflow takes care of the routing.
Build the Router Agent
ContentRouter routerAgent =
AgenticServices.agentBuilder(ContentRouter.class)
.chatModel(chatModel)
.outputKey("contentType")
.build();
The important part here is:
.outputKey("contentType")
The router's result is stored in the shared AgenticScope under the key contentType.
LangChain4j's agentic workflow uses AgenticScope as shared state between agents, allowing one agent's output to become available to other agents.
Build the Specialized Agents
BlogExpert blogExpert =
AgenticServices.agentBuilder(BlogExpert.class)
.chatModel(chatModel)
.outputKey("response")
.build();
SocialMediaExpert socialMediaExpert =
AgenticServices.agentBuilder(SocialMediaExpert.class)
.chatModel(chatModel)
.outputKey("response")
.build();
EmailExpert emailExpert =
AgenticServices.agentBuilder(EmailExpert.class)
.chatModel(chatModel)
.outputKey("response")
.build();
UnknownContentExpert unknownContentExpert =
AgenticServices.agentBuilder(UnknownContentExpert.class)
.chatModel(chatModel)
.outputKey("response")
.build();
Create the Conditional Workflow
This is the most important part of the example.
UntypedAgent contentAgent =
AgenticServices.conditionalBuilder()
.subAgents(
scope -> scope.readState("contentType", ContentType.UNKNOWN)
== ContentType.BLOG,
blogExpert)
.subAgents(
scope -> scope.readState("contentType", ContentType.UNKNOWN)
== ContentType.SOCIAL_MEDIA,
socialMediaExpert)
.subAgents(
scope -> scope.readState("contentType", ContentType.UNKNOWN)
== ContentType.EMAIL,
emailExpert)
.subAgents(
scope -> scope.readState("contentType", ContentType.UNKNOWN)
== ContentType.UNKNOWN,
unknownContentExpert)
.build();
This is directly analogous to the conditional workflow in the LangChain4j documentation, where predicates inspect the shared state and activate the appropriate specialist agent.
Conceptually:
contentType == BLOG
↓
BlogExpert
contentType == SOCIAL_MEDIA
↓
SocialMediaExpert
contentType == EMAIL
↓
EmailExpert
Only the agent whose condition evaluates to true is activated.
Combine Router + Conditional Workflow
Now we combine the router and conditional workflow into a sequence.
ContentCreator contentCreator = AgenticServices
.sequenceBuilder(ContentCreator.class)
.subAgents(routerAgent, contentAgent)
.outputKey("response")
.build();
This gives us the complete workflow.
The sequence workflow first executes the router and then the conditional workflow. LangChain4j's sequence workflow supports composing agents so that they execute in order and share state through AgenticScope
Follow below step by step procedure to build the working Application.
Step 1: Create new maven project 'content-creation-conditional-workflow'
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>content-creation-conditional-workflow</artifactId>
<version>1.0.0</version>
<name>Sequential Handoff Pattern Demo</name>
<description>
Simple Java console application demonstrating a Conditional 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 ContentType enum.
ContentType.java
package com.sample.app.enums;
public enum ContentType {
BLOG,
SOCIAL_MEDIA,
EMAIL,
UNKNOWN
}
Step 3: Define language 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 = "codellama:7b";
private OllamaConfig() {}
public static ChatModel createChatModel() {
String baseUrl = resolveBaseUrl();
String modelName = resolveModelName();
return OllamaChatModel.builder().baseUrl(baseUrl).modelName(modelName).temperature(0.2).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;
}
}
Here I am using ‘codellama:7b’ model.
Step 3: Define Agent interfaces.
BlogExpert.java
package com.sample.app.agents;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
public interface BlogExpert {
@UserMessage(
"""
You are an expert technical content writer.
Create a well-structured blog post based on the user's
request.
The blog should:
- Have a clear title
- Start with an engaging introduction
- Use appropriate headings
- Explain concepts clearly
- Include examples where useful
- End with a concise conclusion
Return only the blog content.
The user request is:
{{request}}
""")
@Agent("Creates technical blog posts and long-form articles")
String createBlog(@V("request") String request);
}
ContentCreator.java
package com.sample.app.agents;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.V;
public interface ContentCreator {
@Agent
String create(@V("request") String request);
}
ContentRouter.java
package com.sample.app.agents;
import com.sample.app.enums.ContentType;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
public interface ContentRouter {
@UserMessage(
"""
Analyze the following user request and categorize it as
'blog', 'social_media' or 'email'.
Use 'blog' when the user wants a blog post, article,
tutorial, or long-form technical/content article.
Use 'social_media' when the user wants content for
LinkedIn, X/Twitter, Facebook, Instagram, or similar
social media platforms.
Use 'email' when the user wants an email, announcement,
newsletter, or email communication.
If the request doesn't belong to any of these categories,
categorize it as 'unknown'.
Reply with only one of these words and nothing else.
The user request is: '{{request}}'.
""")
@Agent("Categorizes a content creation request")
ContentType classify(@V("request") String request);
}
EmailExpert.java
package com.sample.app.agents;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
public interface EmailExpert {
@UserMessage(
"""
You are a professional business communication writer.
Write a clear and professional email based on the
user's request.
Include:
- A suitable subject
- A professional greeting
- A concise and clear message
- A professional closing
Return only the email content.
The user request is:
{{request}}
""")
@Agent("Creates professional emails")
String createEmail(@V("request") String request);
}
SocialMediaExpert.java
package com.sample.app.agents;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
public interface SocialMediaExpert {
@UserMessage(
"""
You are a professional social media content creator.
Create an engaging social media post based on the
user's request.
Keep the content concise and engaging.
Use appropriate formatting and hashtags when useful.
Return only the social media post.
The user request is:
{{request}}
""")
@Agent("Creates social media posts")
String createPost(@V("request") String request);
}
UnknownContentExpert.java
package com.sample.app.agents;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;
public interface UnknownContentExpert {
@UserMessage(
"""
You are a general content creation assistant.
The user's request does not clearly belong to the
supported content types: blog, social media, or email.
Analyze the request and provide a helpful response.
If appropriate, explain what type of content the user
should request.
The user request is:
{{request}}
""")
@Agent("Handles unsupported or unknown content requests")
String handle(@V("request") String request);
}
Step 4: Define main Application class.
App.java
package com.sample.app;
import com.sample.app.agents.BlogExpert;
import com.sample.app.agents.ContentCreator;
import com.sample.app.agents.ContentRouter;
import com.sample.app.agents.EmailExpert;
import com.sample.app.agents.SocialMediaExpert;
import com.sample.app.agents.UnknownContentExpert;
import com.sample.app.config.OllamaConfig;
import com.sample.app.enums.ContentType;
import dev.langchain4j.agentic.AgenticServices;
import dev.langchain4j.agentic.UntypedAgent;
import dev.langchain4j.model.chat.ChatModel;
import java.util.Scanner;
public class App {
private static String readInput(Scanner scanner) {
System.out.print("> ");
String input = scanner.nextLine().trim();
return "exit".equalsIgnoreCase(input) ? null : input;
}
public static void main(String[] args) {
ChatModel chatModel = OllamaConfig.createChatModel();
ContentRouter routerAgent =
AgenticServices.agentBuilder(ContentRouter.class)
.chatModel(chatModel)
.outputKey("contentType")
.build();
BlogExpert blogExpert =
AgenticServices.agentBuilder(BlogExpert.class)
.chatModel(chatModel)
.outputKey("response")
.build();
SocialMediaExpert socialMediaExpert =
AgenticServices.agentBuilder(SocialMediaExpert.class)
.chatModel(chatModel)
.outputKey("response")
.build();
EmailExpert emailExpert =
AgenticServices.agentBuilder(EmailExpert.class)
.chatModel(chatModel)
.outputKey("response")
.build();
UnknownContentExpert unknownContentExpert =
AgenticServices.agentBuilder(UnknownContentExpert.class)
.chatModel(chatModel)
.outputKey("response")
.build();
UntypedAgent contentAgent =
AgenticServices.conditionalBuilder()
.subAgents(
scope -> scope.readState("contentType", ContentType.UNKNOWN) == ContentType.BLOG,
blogExpert)
.subAgents(
scope ->
scope.readState("contentType", ContentType.UNKNOWN) == ContentType.SOCIAL_MEDIA,
socialMediaExpert)
.subAgents(
scope -> scope.readState("contentType", ContentType.UNKNOWN) == ContentType.EMAIL,
emailExpert)
.subAgents(
scope -> scope.readState("contentType", ContentType.UNKNOWN) == ContentType.UNKNOWN,
unknownContentExpert)
.build();
ContentCreator contentCreator =
AgenticServices.sequenceBuilder(ContentCreator.class)
.subAgents(routerAgent, contentAgent)
.outputKey("response")
.build();
try (Scanner scanner = new Scanner(System.in)) {
while (true) {
String input = readInput(scanner);
if ("exit".equalsIgnoreCase(input)) {
System.exit(0);
}
String response = contentCreator.create(input);
System.out.println(response);
}
}
}
}
Build the project
Navigate to the project where pom.xml is located and execute following command.
mvn clean package
Run the Application
Execute below command to run the Application.
java -jar ./target/content-creation-conditional-workflow-1.0.0.jar
$ java -jar ./target/content-creation-conditional-workflow-1.0.0.jar
> Please draft an email to all engineers asking them to reset their passwords immediately as a precautionary measure following a potential password leak.
Subject: Urgent: Reset Your Password Immediately
Dear All Engineers,
I hope this email finds you well. As a precautionary measure, I am writing to inform you that a potential password leak has been identified. As a result, I kindly request that you reset your passwords immediately.
This is a security measure to ensure the safety and security of our systems and data. Please follow the instructions provided in the password reset link sent to your email.
Thank you for your prompt attention to this matter. If you have any questions or concerns, please do not hesitate to reach out to me.
Best regards,
[Your Name]
[Your Title]
[Your Company]
[Your Contact Information]
You can download the Application from this link.
Previous Next Home


No comments:
Post a Comment