Step 03 - Composing Multiple Agentic Workflows
Composing Multiple Agentic Workflows
In the previous step, you created a sequential workflow that orchestrated two agents working together:
- The
CleaningAgentdetermined if a car needed cleaning - The
CarConditionFeedbackAgentupdated the car's condition based on feedback
A single sequential pattern works well when you just need agents to run one after another. However, real-world scenarios often require more sophisticated orchestration patterns.
In this step, you'll learn how to compose workflows by nesting them within other workflows to build complex agentic systems. You'll create multi-level orchestration patterns that combine different execution patterns (sequential, parallel, and conditional).
New Requirement from Miles of Smiles Management: Comprehensive Car Management
The Miles of Smiles management team wants a more sophisticated car management system. When cars are returned, they want the system to automatically:
- Analyze feedback for both cleaning needs AND maintenance requirements simultaneously
- Route cars appropriately to maintenance if needed, otherwise to cleaning if needed
- Track all feedback sources from rentals, cleaning, and maintenance teams
- Update car conditions based on all collected feedback
These new features require more advanced orchestration between agents to route requests appropriately.
What You'll Learn
In this step, you will:
- Understand how to nest workflows within workflows to create sophisticated multi-level orchestration
- Explore additional types of workflow patterns such as parallel and conditional
- Use a decision agent to get a typed answer from a decision model and route each car with it
- See how
AgenticScopeflows through nested workflow levels
Composing Agentic Workflows
Let's start with a bit of theory. In Step 02, you learned about the four fundamental workflow patterns: sequential, parallel, conditional, and loop. Now we'll explore how to compose these patterns by nesting workflows within other workflows.
What is Agentic Workflow Nesting?
Workflow nesting means using a workflow as a sub-agent within another workflow. This allows you to:
- Combine patterns: Use parallel execution within a sequential flow
- Organize complexity: Break down complex orchestration into manageable pieces
- Reuse workflows: Use the same sub-workflow in multiple places
- Create hierarchies: Build multi-level agent systems
Example: Nested Agentic Workflow Architecture
graph TD
Main["Main Workflow<br/>Sequential"] --> Sub1["Sub-Workflow 1<br/>Parallel"]
Main --> Sub2["Sub-Workflow 2<br/>Conditional"]
Main --> Agent["Single Agent"]
Sub1 --> A1["Agent A"]
Sub1 --> A2["Agent B"]
Sub2 --> B1["Agent C"]
Sub2 --> B2["Agent D"]
style Main fill:#90EE90,stroke:#333,stroke-width:2,color:#000
style Sub1 fill:#87CEEB,stroke:#333,stroke-width:2,color:#000
style Sub2 fill:#FFD700,stroke:#333,stroke-width:2,color:#000
style Agent fill:#90EE90,stroke:#333,stroke-width:2,color:#000
This creates a three-level nested workflow where:
- The main sequential workflow coordinates the overall flow
- Sub-workflows handle specific orchestration patterns (parallel, conditional)
- Individual agents perform specific tasks
How AgenticScope Works with Nesting
When workflows are nested, the AgenticScope flows through all levels:
graph LR
A["Main Workflow<br/>AgenticScope"] --> B["Sub-Workflow 1<br/>Same Scope"]
B --> C["Agent A<br/>Same Scope"]
B --> D["Agent B<br/>Same Scope"]
A --> E["Sub-Workflow 2<br/>Same Scope"]
Key points:
- All nested workflows and agents share the same
AgenticScopeinstance - Data written by any agent is available to all subsequent agents
- The scope maintains state throughout the entire execution hierarchy
What is Being Added?
Now that we have that bit of theory under out belt, we can continue to transform our car management system. We're going to implement:
- 3 feedback sources: collect human feedback not only from the car rental returns team, but also from the cleaning team, and from the maintenance team
- Parallel analysis: do concurrent evaluation for both cleaning and maintenance needs
- Conditional routing: implement intelligent decision-making about where to send each car
- Update the system: add additional Tools the agents can call to update the car conditions in the database based on all feedback
The Complete Solution Architecture
The final system uses a 3-level nested workflow, similar to what we saw above in the theoretical part:
graph TB
Start([Car Return]) --> A[CarProcessingWorkflow<br/>Sequential - Level 1]
A --> B[Step 1: FeedbackWorkflow<br/>Parallel - Level 2]
B --> B1[CleaningFeedbackAgent]
B --> B2[MaintenanceFeedbackAgent]
B1 --> BEnd[Both complete]
B2 --> BEnd
BEnd --> DA[Step 2: CarAssignmentDecisionAgent<br/>Decision Agent - Level 1]
DA --> C[Step 3: CarAssignmentWorkflow<br/>Conditional - Level 2]
C --> C1{Decision is<br/>MAINTENANCE?}
C1 -->|Yes| C2[MaintenanceAgent]
C1 -->|No| C3{Decision is<br/>CLEANING?}
C3 -->|Yes| C4[CleaningAgent]
C2 --> C3
C3 -->|No| CEnd[Action complete]
C4 --> CEnd
CEnd --> D[Step 4: CarConditionFeedbackAgent<br/>Single Agent - Level 1]
D --> End([Updated Car Conditions])
style A fill:#90EE90
style B fill:#87CEEB
style DA fill:#90EE90
style C fill:#FFD700
style D fill:#90EE90
style Start fill:#E8E8E8
style End fill:#E8E8E8
style BEnd fill:#F0F0F0
style CEnd fill:#F0F0F0
The Flow:
-
FeedbackWorkflow (Parallel): Analyzes feedback simultaneously from two perspectives:
- Does the car need maintenance?
- Does the car need cleaning?
-
CarAssignmentDecisionAgent (Decision) reads both analyses and chooses the team that handles the car next. It answers maintenance if any maintenance is required, otherwise cleaning if any cleaning is required, and otherwise that no action is needed.
-
CarAssignmentWorkflow (Conditional) activates the agent that matches this answer, which is either the
MaintenanceAgentor theCleaningAgent. When no action is needed it activates neither of them, and the flow continues. -
CarConditionFeedbackAgent (Single): Updates the car's condition based on all feedback
Key Implementation Details
How Each Level Works
Level 1: Main Sequential Workflow
The CarProcessingWorkflow orchestrates the entire process sequentially:
CarProcessingWorkflow.java
@SequenceAgent(outputKey = "carProcessingAgentResult",
subAgents = { FeedbackWorkflow.class, CarAssignmentDecisionAgent.class, CarAssignmentWorkflow.class, CarConditionFeedbackAgent.class })
Notice that subAgents contains two workflows and two agents. Workflows are first-class citizens that can be nested just like agents.
Level 2a: Parallel Feedback Workflow
The FeedbackWorkflow runs multiple agents simultaneously:
FeedbackWorkflow.java
@ParallelAgent(outputKey = "feedbackResult",
subAgents = { CleaningFeedbackAgent.class, MaintenanceFeedbackAgent.class })
The agents analyze different aspects (cleaning vs. maintenance) and don't depend on each other, so running them concurrently improves performance.
Level 1: Car Assignment Decision Agent
The two feedback agents describe what the car needs in free text, so the result of the parallel analysis has to be turned into a routing choice before the next workflow can act on it. The CarAssignmentDecisionAgent makes this choice as the second step of the sequence. It is a decision agent, an agent that answers a question about its arguments with a decision model instead of a chat model. A decision agent makes a single model call and receives a typed answer rather than generated text, which makes it cheaper and faster than an AI agent and a natural fit for routing, gating and classification steps.
CarAssignmentDecisionAgent.java
@Decide("""
Which team should handle this car next: MAINTENANCE if any maintenance is required, \
otherwise CLEANING if any cleaning is required, otherwise NONE?""")
@Agent(description = "Car assignment decider. Decides if the car goes to maintenance, to cleaning, or needs no action.",
outputKey = "carAssignment")
CarAssignment decideAssignment(
String maintenanceRequest,
String cleaningRequest);
The question is the value of @Decide, and the return type of the method determines what kind of question it is. With an enum such as CarAssignment, the answer is a choice among its constants MAINTENANCE, CLEANING and NONE, whereas a boolean return type would make it a yes/no question. The question also carries the priority between the teams, since it asks for MAINTENANCE whenever any maintenance is required and considers cleaning only otherwise.
Like any other agent, the decision agent reads its arguments from the AgenticScope by name, which here are the maintenanceRequest and cleaningRequest written by the two feedback agents. It writes its answer to its outputKey, so the chosen CarAssignment is available under carAssignment to the activation conditions and to the agents that run later. A decision agent has no prompt, tools or chat memory, which is why the method carries neither @SystemMessage nor @UserMessage.
The decision model is configured in application.properties, next to the chat model:
application.properties
# Decision model used by the car assignment decision agent
quarkus.langchain4j.openai.decision-model.model-name=gpt-6-luna
With the OpenAI provider, a decision agent uses OpenAI's Decisions API with the same API key as the chat model, and it needs no extra dependency. This step sets the model to gpt-6-luna, which is also the default.
Note
Experimental feature
The Quarkus LangChain4j agentic guide marks decision agents and the DecisionModel API as experimental, and OpenAI's Decisions API as a public beta.
Level 2b: Conditional Action Workflow
The CarAssignmentWorkflow uses activation conditions to intelligently route cars to the appropriate team based on the answer of the decision agent:
CarAssignmentWorkflow.java
@ConditionalAgent(outputKey = "analysisResult",
subAgents = { MaintenanceAgent.class, CleaningAgent.class })
String processAction(
CarInfo carInfo,
Integer carNumber,
String cleaningRequest,
String maintenanceRequest);
@ActivationCondition(MaintenanceAgent.class)
static boolean assignToMaintenance(CarAssignment carAssignment) {
return carAssignment == CarAssignment.MAINTENANCE;
}
@ActivationCondition(CleaningAgent.class)
static boolean assignToCleaning(CarAssignment carAssignment) {
return carAssignment == CarAssignment.CLEANING;
}
- If
assignToMaintenance()returnstrue→ MaintenanceAgent runs - If
assignToCleaning()returnstrue→ CleaningAgent runs
Both conditions take the carAssignment value that the decision agent stored in the AgenticScope. assignToMaintenance() compares it with CarAssignment.MAINTENANCE and assignToCleaning() compares it with CarAssignment.CLEANING, so at most one of the two agents runs. The priority routing, in which maintenance takes precedence over cleaning, is already settled by the question of the decision agent and doesn't have to be repeated in the conditions. When the answer is NONE, neither condition is true, so the conditional workflow activates no agent and the sequence continues with the CarConditionFeedbackAgent.
Try the Complete Solution
Now that you understand the architecture, let's see it in action!
Start the Application
- If a previous step's Quarkus server is still running, stop it first (press
Ctrl+Cin the terminal). - Navigate to the complete solution directory:
Linux / macOS
cd section-2/step-03
./mvnw quarkus:dev
Windows
cd section-2\step-03
mvnw quarkus:dev
Test Different Scenarios
Try these scenarios to see how the nested workflows route cars:
Scenario 1: Maintenance Priority
Enter the following text in the feedback field for the Honda Civic:
Engine making strange noise and car is dirty
What happens:
flowchart TD
Start([Input: Brakes squealing <br>and car is dirty])
Start --> FW[FeedbackWorkflow<br/>Parallel Analysis]
FW --> MFA[MaintenanceFeedbackAgent]
FW --> CFA[CleaningFeedbackAgent]
MFA --> MR[Detects: maintenance needed ✓]
CFA --> CR[Detects: cleaning needed ✓]
MR --> DA[CarAssignmentDecisionAgent<br/>Maintenance has higher priority]
CR --> DA
DA -->|MAINTENANCE| CAW{CarAssignmentWorkflow<br/>Conditional Routing}
CAW --> MA[Route to MaintenanceAgent]
MA --> Result([Result: Car goes to maintenance])
style FW fill:#FAE5D3,stroke:#333,stroke-width:2,color:#333
style DA fill:#D6EAF8,stroke:#333,stroke-width:2,color:#333
style CAW fill:#D5F5E3,stroke:#333,stroke-width:2,color:#333
style MA fill:#F9E79F,stroke:#333,stroke-width:2,color:#333
style Result fill:#D2B4DE,stroke:#333,stroke-width:2,color:#333
Scenario 2: Cleaning Only
Enter the following text in the Mercedes Benz feedback field:
Car is very dirty but runs fine
What happens:
flowchart TD
Start([Input: Car is very dirty<br/>but runs fine])
Start --> FW[FeedbackWorkflow<br/>Parallel Analysis]
FW --> MFA[MaintenanceFeedbackAgent]
FW --> CFA[CleaningFeedbackAgent]
MFA --> MR[Detects: no maintenance needed ✗]
CFA --> CR[Detects: cleaning needed ✓]
MR --> DA[CarAssignmentDecisionAgent<br/>No maintenance needed, 2nd priority is cleaning]
CR --> DA
DA -->|CLEANING| CAW{CarAssignmentWorkflow<br/>Conditional Routing}
CAW --> CA[Route to CleaningAgent]
CA --> Result([Result: Car goes to cleaning])
style FW fill:#FAE5D3,stroke:#333,stroke-width:2,color:#333
style DA fill:#D6EAF8,stroke:#333,stroke-width:2,color:#333
style CAW fill:#D5F5E3,stroke:#333,stroke-width:2,color:#333
style CA fill:#F9E79F,stroke:#333,stroke-width:2,color:#333
style Result fill:#D2B4DE,stroke:#333,stroke-width:2,color:#333
Scenario 3: Maintenance Return
Find the BMW X5 (status: In Maintenance) in the Fleet Status grid and enter in its feedback field:
Fixed the brakes, car could use a wash now
What happens:
- FeedbackWorkflow: Analyzes maintenance feedback
- CarAssignmentDecisionAgent: Answers
CLEANING - CarAssignmentWorkflow: Routes to CleaningAgent
- Result: Car goes from maintenance to cleaning
Check the Logs
Watch the console output while the application processes a return. For the first scenario it contains these messages:
FeedbackWorkflow executing...
├─ CleaningFeedbackAgent analyzing...
└─ MaintenanceFeedbackAgent analyzing...
CarAssignmentWorkflow evaluating conditions...
CarAssignmentDecisionAgent decided: MAINTENANCE
CarConditionFeedbackAgent updating...
The line that starts with CarAssignmentDecisionAgent decided is the one that tells you what the agents did. The @Output method of CarProcessingWorkflow logs the CarAssignment that the decision agent stored in the AgenticScope, so it shows MAINTENANCE, CLEANING or NONE depending on the feedback you entered. The other lines are progress messages that CarManagementService prints before it calls the workflow and after the workflow returns, which is why they look the same for every car. When a car goes to cleaning you will also see a CleaningAgent activated line, which the CleaningTool logs when the cleaning agent calls it.
CarManagementService sets the status of the car from the same CarAssignment value, so the Fleet Status grid confirms the decision. The car ends up In Maintenance for MAINTENANCE, At Cleaning for CLEANING, and Available to Rent for NONE.
Why Nested Workflows Matter
Separation of Concerns
Each workflow has a single responsibility:
- FeedbackWorkflow: Analyze all feedback sources
- CarAssignmentWorkflow: Route cars to appropriate teams
- CarProcessingWorkflow: Orchestrate the complete process
This makes the system easier to understand, test, and modify.
Reusability
Workflows are reusable components. For example, you could use FeedbackWorkflow in other contexts:
// Use in a different workflow
public interface DifferentWorkflow {
@SequenceAgent(outputKey = "differentResult", subAgents = {
FeedbackWorkflow.class, // Reuse the same workflow!
SomeOtherAgent.class
})
String process(CarInfo carInfo, Integer carNumber, String feedback);
}
Type Safety
The Quarkus LangChain4j extension validates the agentic system at build time. A mistake in the declaration of an agent or of one of the nested workflows is therefore reported before the application starts, rather than in the middle of a car return.
AgenticScope Across Levels
The AgenticScope flows through all levels of nesting:
sequenceDiagram
participant Main as CarProcessingWorkflow
participant Feedback as FeedbackWorkflow
participant Decision as CarAssignmentDecisionAgent
participant Action as CarAssignmentWorkflow
participant Scope as AgenticScope
Main->>Scope: Store: rentalFeedback, cleaningFeedback, maintenanceFeedback
Note over Feedback: Level 2 - Parallel
Main->>Feedback: Execute
Feedback->>Scope: Write: maintenanceRequest, cleaningRequest
Note over Decision: Level 1 - Decision
Main->>Decision: Execute
Decision->>Scope: Read: maintenanceRequest, cleaningRequest
Decision->>Scope: Write: carAssignment
Note over Action: Level 2 - Conditional
Main->>Action: Execute
Action->>Scope: Read: carAssignment
Action->>Scope: Execute selected agent
Main->>Scope: Final agent updates condition
All agents and workflows share the same scope, enabling seamless data flow across levels.
Optional: Implement It Yourself
If you want hands-on practice implementing these patterns, you can build the solution step-by-step.
Warning
Short on time? There are quite a few changes to make, so if you're short on time and would like to learn about the next concepts, feel free to skip to the next step. As a middle-of-the-road solution, you can also read on and walk through the implementation steps in the source code of section-2/step-03 without making all the code changes yourself.
What You'll Build
Starting from your current code in section-2/step-02, you'll add:
- Feedback Analysis Agents (MaintenanceFeedbackAgent, CleaningFeedbackAgent)
- Parallel Feedback Workflow to run them concurrently
- Action Agents (MaintenanceAgent, updated CleaningAgent)
- Decision Agent (CarAssignmentDecisionAgent) that chooses the team for each car
- Conditional Action Workflow for intelligent routing
- Nested Main Workflow that orchestrates everything
- Supporting Infrastructure (tools, models, service updates)
Time: 60-90 minutes (20-30 minutes if you're working directly from step-03)
Prerequisites
Before starting:
- You have stopped (Ctrl+C) any running Quarkus instances
- You are in the root project directory (not a
step-XXsubdirectory)
Option 1: Continue from Step 02
If you want to continue building on top of Step 02 code, you'll need to copy the updated UI files from step-03:
Linux / macOS
cd section-2/step-02
cp ../step-03/src/main/resources/META-INF/resources/css/styles.css ./src/main/resources/META-INF/resources/css/styles.css
cp ../step-03/src/main/resources/META-INF/resources/js/app.js ./src/main/resources/META-INF/resources/js/app.js
cp ../step-03/src/main/resources/META-INF/resources/index.html ./src/main/resources/META-INF/resources/index.html
cp ../step-03/src/main/resources/import.sql ./src/main/resources/import.sql
cp ../step-03/src/main/java/com/carmanagement/model/CarStatus.java ./src/main/java/com/carmanagement/model/CarStatus.java
Windows
cd section-2\step-02
copy ..\step-03\src\main\resources\META-INF\resources\css\styles.css .\src\main\resources\META-INF\resources\css\styles.css
copy ..\step-03\src\main\resources\META-INF\resources\js\app.js .\src\main\resources\META-INF\resources\js\app.js
copy ..\step-03\src\main\resources\META-INF\resources\index.html .\src\main\resources\META-INF\resources\index.html
copy ..\step-03\src\main\resources\import.sql .\src\main\resources\import.sql
copy ..\step-03\src\main\java\com\carmanagement\model\CarStatus.java .\src\main\java\com\carmanagement\model\CarStatus.java
Option 2: Follow along using the completed solution
If you prefer to follow along (without making any code changes), navigate to the completed step-03 directory:
Linux / macOS
cd section-2/step-03
./mvnw quarkus:dev
Windows
cd section-2\step-03
mvnw quarkus:dev
Create Feedback Analysis Agents
Let's create the agents that will analyze the feedback from the UI form.
The feedback string is evaluated differently by each agent: The MaintenanceFeedbackAgent will look for anything that might point to the car needing repairs,
while the CleaningFeedbackAgent is specialized in looking for clues in the string that car might be dirty and in need of cleaning.
MaintenanceFeedbackAgent
In src/main/java/com/carmanagement/agentic/agents, create MaintenanceFeedbackAgent.java:
MaintenanceFeedbackAgent.java
package com.carmanagement.agentic.agents;
import com.carmanagement.model.CarInfo;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
/**
* Agent that analyzes feedback to determine if maintenance is needed.
*/
public interface MaintenanceFeedbackAgent {
@SystemMessage("""
You are a car maintenance analyzer for a car rental company. Your job is to determine if a car needs maintenance based on feedback.
Analyze the feedback and car condition to decide if maintenance is needed.
Maintenance never includes any cleaning or detailing.
If the feedback mentions mechanical issues, strange noises, performance problems, significant body damage or anything that suggests
the car needs maintenance, recommend appropriate maintenance.
Be specific about what type of maintenance is needed (oil change, tire rotation, brake service, engine service, transmission service, body work).
If no service of any kind, repairs or maintenance are needed, respond with "MAINTENANCE_NOT_REQUIRED".
Include the reason for your choice but keep your response short.
""")
@UserMessage("""
Car Information:
Make: {carInfo.make}
Model: {carInfo.model}
Year: {carInfo.year}
Previous Condition: {carInfo.condition}
Feedback: {feedback}
""")
@Agent(description = "Car maintenance analyzer. Using feedback, determines if a car needs maintenance.",
outputKey = "maintenanceRequest")
String analyzeForMaintenance(
CarInfo carInfo,
Integer carNumber,
String feedback);
}
Key Points:
- Focuses on mechanical issues, body damage, and maintenance needs
- Returns "MAINTENANCE_NOT_REQUIRED" when no maintenance is needed
- Uses
outputKeyto store result in AgenticScope - Accesses the feedback string via
{feedback}in the@UserMessagetemplate
CleaningFeedbackAgent
In src/main/java/com/carmanagement/agentic/agents, create CleaningFeedbackAgent.java:
CleaningFeedbackAgent.java
package com.carmanagement.agentic.agents;
import com.carmanagement.model.CarInfo;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
/**
* Agent that analyzes feedback to determine if a cleaning is needed.
*/
public interface CleaningFeedbackAgent {
@SystemMessage("""
You are a cleaning analyzer for a car rental company.
Your job is to determine if a car needs cleaning based on feedback and past car condition.
Maintenance never cleans cars. If car needed cleaning prior to maintenance, the car will still need cleaning afterwards.
If the feedback or car condition mentions dirt, mud, stains, or anything that suggests the car is dirty, recommend a cleaning.
If there's cleaning feedback, prioritize it over the previous car condition.
Be specific about what type of cleaning is needed (exterior, interior, detailing, waxing).
If no interior or exterior car cleaning services are needed based on the feedback, respond with "CLEANING_NOT_REQUIRED".
Include the reason for your choice but keep your response short.
""")
@UserMessage("""
Car Information:
Make: {carInfo.make}
Model: {carInfo.model}
Year: {carInfo.year}
Previous Condition: {carInfo.condition}
Feedback: {feedback}
""")
@Agent(description = "Cleaning analyzer. Using feedback, determines if a cleaning is needed.",
outputKey = "cleaningRequest")
String analyzeForCleaning(
CarInfo carInfo,
Integer carNumber,
String feedback);
}
Key Points:
- Focuses on cleanliness issues
- Returns "CLEANING_NOT_REQUIRED" when no cleaning needed
- Stores result in AgenticScope for later use
Create the Parallel Feedback Workflow
Now, we'll create a parallel workflow that runs both feedback agents simultaneously.
This is where the @ParallelAgent annotation comes into play.
In src/main/java/com/carmanagement/agentic/workflow, create FeedbackWorkflow.java:
FeedbackWorkflow.java
package com.carmanagement.agentic.workflow;
import com.carmanagement.agentic.agents.CleaningFeedbackAgent;
import com.carmanagement.agentic.agents.MaintenanceFeedbackAgent;
import com.carmanagement.model.CarInfo;
import dev.langchain4j.agentic.declarative.ParallelAgent;
/**
* Workflow for processing car feedback in parallel.
*/
public interface FeedbackWorkflow {
/**
* Runs multiple feedback agents in parallel to analyze different aspects of car feedback.
*/
// --8<-- [start:parallel-agent]
@ParallelAgent(outputKey = "feedbackResult",
subAgents = { CleaningFeedbackAgent.class, MaintenanceFeedbackAgent.class })
// --8<-- [end:parallel-agent]
String analyzeFeedback(
CarInfo carInfo,
Integer carNumber,
String feedback);
}
Key Points:
@ParallelAgentmakes both agents execute simultaneously- Both agents can read from and write to the shared
AgenticScope - Results are available to subsequent workflow steps
Create Car Specialist Agents
These agents will examine the analysis results and determine what should happen to the car based on their specialty (either maintenance or cleaning)
MaintenanceAgent
In src/main/java/com/carmanagement/agentic/agents, create MaintenanceAgent.java:
MaintenanceAgent.java
package com.carmanagement.agentic.agents;
import com.carmanagement.model.CarInfo;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.agentic.Agent;
/**
* Agent that determines what maintenance services to request.
*/
public interface MaintenanceAgent {
@SystemMessage("""
You handle intake for the car maintenance department of a car rental company.
Based on the maintenance request, determine what specific services are needed and provide a detailed maintenance plan.
Be specific about what services are needed based on the maintenance request.
Available maintenance services include:
- Oil change
- Tire rotation
- Brake service
- Engine service
- Transmission service
- Body work (dent repair, paint, collision repair)
For body damage like dents, scratches, or collision damage, include body work in your plan.
Provide your response as a structured maintenance plan listing the specific services needed.
""")
@UserMessage("""
Car Information:
Make: {carInfo.make}
Model: {carInfo.model}
Year: {carInfo.year}
Car Number: {carNumber}
Maintenance Request:
{maintenanceRequest}
""")
@Agent(description = "Car maintenance specialist. Using car information and request, determines what maintenance services are needed.",
outputKey = "analysisResult")
String processMaintenance(
CarInfo carInfo,
Integer carNumber,
String maintenanceRequest);
}
Key Points:
- This agent demonstrates pure LLM reasoning without tool calling
- Unlike CleaningAgent which uses CleaningTool, MaintenanceAgent relies entirely on the LLM's analysis
- Returns structured recommendations that the system can act upon
- Shows that not every agent needs tools - some can be pure reasoning agents
Update CleaningAgent
The CleaningAgent we created previously should now return analysisResult as well, so the results are aggregated.
Update src/main/java/com/carmanagement/agentic/agents/CleaningAgent.java:
CleaningAgent.java
package com.carmanagement.agentic.agents;
import io.quarkiverse.langchain4j.ToolBox;
import com.carmanagement.agentic.tools.CleaningTool;
import com.carmanagement.model.CarInfo;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
/**
* Agent that determines what cleaning services to request.
*/
public interface CleaningAgent {
@SystemMessage("""
You handle intake for the cleaning department of a car rental company.
""")
@UserMessage("""
Taking into account all provided feedback, determine if the car needs a cleaning.
If the feedback indicates the car is dirty, has stains, or any other cleanliness issues,
call the provided tool and recommend appropriate cleaning services (exterior wash, interior cleaning, waxing, detailing).
Be specific about what services are needed.
If no specific cleaning request is provided, request a standard exterior wash.
Car Information:
Make: {carInfo.make}
Model: {carInfo.model}
Year: {carInfo.year}
Car Number: {carNumber}
Cleaning Request:
{cleaningRequest}
""")
@Agent(description = "Cleaning specialist. Determines what cleaning services are needed.",
outputKey = "analysisResult")
@ToolBox(CleaningTool.class)
String processCleaning(
CarInfo carInfo,
Integer carNumber,
String cleaningRequest);
}
Create the Car Assignment Decision Agent
The two feedback agents store their analysis as free text, while the conditional workflow we'll create next needs a definite choice between maintenance, cleaning and no action. A decision agent makes this choice by asking a decision model a single question about both analyses, as described in How Each Level Works.
In src/main/java/com/carmanagement/agentic/agents, create CarAssignmentDecisionAgent.java:
CarAssignmentDecisionAgent.java
package com.carmanagement.agentic.agents;
import com.carmanagement.model.CarAssignment;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.decision.Decide;
/**
* Agent that decides which team the car must be assigned to.
* It asks a decision model a single question and gets a typed answer instead of generated text.
*/
public interface CarAssignmentDecisionAgent {
@Decide("""
Which team should handle this car next: MAINTENANCE if any maintenance is required, \
otherwise CLEANING if any cleaning is required, otherwise NONE?""")
@Agent(description = "Car assignment decider. Decides if the car goes to maintenance, to cleaning, or needs no action.",
outputKey = "carAssignment")
CarAssignment decideAssignment(
String maintenanceRequest,
String cleaningRequest);
}
The method reads maintenanceRequest and cleaningRequest from the AgenticScope and stores its answer under carAssignment, the name that the activation conditions of the conditional workflow use for their parameter. Its return type is the CarAssignment enum, which belongs to the supporting infrastructure created further down, so your IDE reports it as missing until you get there.
The agent sends its question to a decision model, which is configured with its own property and uses the OpenAI API key already set for the chat model.
Open src/main/resources/application.properties and add the decision model:
application.properties
# Decision model used by the car assignment decision agent
quarkus.langchain4j.openai.decision-model.model-name=gpt-6-luna
Create the Conditional Car Assignment Workflow
The Car Assignment workflow is the conditional workflow that activates the appropriate specialist agent based on the answer of the decision agent. Its outputKey is the same analysisResult that the MaintenanceAgent and the CleaningAgent write.
In src/main/java/com/carmanagement/agentic/workflow, create CarAssignmentWorkflow.java:
CarAssignmentWorkflow.java
package com.carmanagement.agentic.workflow;
import com.carmanagement.agentic.agents.CleaningAgent;
import com.carmanagement.agentic.agents.MaintenanceAgent;
import com.carmanagement.model.CarAssignment;
import com.carmanagement.model.CarInfo;
import dev.langchain4j.agentic.declarative.ActivationCondition;
import dev.langchain4j.agentic.declarative.ConditionalAgent;
/**
* Workflow for assigning cars to appropriate teams based on feedback analysis.
*/
public interface CarAssignmentWorkflow {
/**
* Assigns the car to the appropriate team based on the feedback analysis.
*/
// --8<-- [start:conditional-agent]
@ConditionalAgent(outputKey = "analysisResult",
subAgents = { MaintenanceAgent.class, CleaningAgent.class })
String processAction(
CarInfo carInfo,
Integer carNumber,
String cleaningRequest,
String maintenanceRequest);
@ActivationCondition(MaintenanceAgent.class)
static boolean assignToMaintenance(CarAssignment carAssignment) {
return carAssignment == CarAssignment.MAINTENANCE;
}
@ActivationCondition(CleaningAgent.class)
static boolean assignToCleaning(CarAssignment carAssignment) {
return carAssignment == CarAssignment.CLEANING;
}
// --8<-- [end:conditional-agent]
}
Key Points:
@ConditionalAgentevaluates conditions to determine which agent runs@ActivationConditionmethods returntrueto activate an agent
Both conditions declare a CarAssignment carAssignment parameter, which receives the answer that the decision agent stored in the AgenticScope. Each of them compares it with a single constant, so maintenance and cleaning are never activated together, and neither agent runs when the answer is NONE. The priority of maintenance over cleaning doesn't appear in this file, because the decision agent has already applied it when it answered.
Update CarConditionFeedbackAgent
Update src/main/java/com/carmanagement/agentic/agents/CarConditionFeedbackAgent.java to add the new maintenance recommendations:
CarConditionFeedbackAgent.java
package com.carmanagement.agentic.agents;
import com.carmanagement.model.CarInfo;
import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
/**
* Agent that analyzes feedback to update the car condition.
*/
public interface CarConditionFeedbackAgent {
@SystemMessage("""
You are a car condition analyzer for a car rental company. Your job is to determine the current condition of a car based on feedback.
Analyze all feedback and the previous car condition to provide an updated condition description.
Always provide a very short (no more than 200 characters) condition description, even if there's minimal feedback.
Do not add any headers or prefixes to your response.
""")
@UserMessage("""
Car Information:
Make: {carInfo.make}
Model: {carInfo.model}
Year: {carInfo.year}
Previous Condition: {carInfo.condition}
Feedback from other agents:
Cleaning Recommendation: {cleaningRequest}
Maintenance Recommendation: {maintenanceRequest}
""")
@Agent(description = "Car condition analyzer. Determines the current condition of a car based on feedback.",
outputKey = "carCondition")
String analyzeForCondition(
CarInfo carInfo,
Integer carNumber,
String cleaningRequest,
String maintenanceRequest);
}
Create Supporting Infrastructure
Create CarAssignment Model
In src/main/java/com/carmanagement/model, create CarAssignment.java:
CarAssignment.java
package com.carmanagement.model;
/**
* Enum representing the type of possible car assignments for car processing
*/
public enum CarAssignment {
MAINTENANCE,
CLEANING,
NONE
}
Update CarConditions Model
Update src/main/java/com/carmanagement/model/CarConditions.java:
CarConditions.java
package com.carmanagement.model;
/**
* Record representing the conditions of a car.
*
* @param generalCondition A description of the car's general condition
* @param carAssignment Indicates the action required
*/
public record CarConditions(String generalCondition, CarAssignment carAssignment) {
}
Update the main Car Processing Workflow
Now it's finally time to compose the sub workflows in the main Car Processing workflow! We need to replace the direct call to the CleaningAgent with the FeedbackWorkflow that will analyze the feedback from the intake, followed by the CarAssignmentDecisionAgent that chooses the team, and then the CarAssignmentWorkflow to actually assign the car to that team.
We'll also update the outputKey and the output method, which now returns the assignment chosen by the decision agent together with the car condition.
Update src/main/java/com/carmanagement/agentic/workflow/CarProcessingWorkflow.java:
CarProcessingWorkflow.java
package com.carmanagement.agentic.workflow;
import com.carmanagement.agentic.agents.CarAssignmentDecisionAgent;
import com.carmanagement.agentic.agents.CarConditionFeedbackAgent;
import com.carmanagement.model.CarConditions;
import com.carmanagement.model.CarAssignment;
import com.carmanagement.model.CarInfo;
import dev.langchain4j.agentic.declarative.Output;
import dev.langchain4j.agentic.declarative.SequenceAgent;
import io.quarkus.logging.Log;
/**
* Workflow for processing car returns using a sequence of agents.
*/
public interface CarProcessingWorkflow {
/**
* Processes a car return by running feedback analysis and then appropriate actions.
*/
// --8<-- [start:sequence-agent]
@SequenceAgent(outputKey = "carProcessingAgentResult",
subAgents = { FeedbackWorkflow.class, CarAssignmentDecisionAgent.class, CarAssignmentWorkflow.class, CarConditionFeedbackAgent.class })
// --8<-- [end:sequence-agent]
CarConditions processCarReturn(
CarInfo carInfo,
Integer carNumber,
String feedback);
@Output
static CarConditions output(String carCondition, CarAssignment carAssignment) {
Log.infof("CarAssignmentDecisionAgent decided: %s", carAssignment);
return new CarConditions(carCondition, carAssignment);
}
}
Key Points:
@SequenceAgentruns the workflows and agents in order- Sub-agents can be other workflows (FeedbackWorkflow, CarAssignmentWorkflow)
- All agents share the same
AgenticScope
The @Output method takes carCondition and carAssignment from the AgenticScope, logs the assignment so that the answer of the decision agent shows up in the console, and returns both values together as a CarConditions record. It contains no routing logic of its own, because the decision agent has already determined what needs to happen next.
Update the Service Layer
And finally, we'll update the Car Management service to handle the result from the Agentic AI workflow and update the system accordingly.
Update src/main/java/com/carmanagement/service/CarManagementService.java:
CarManagementService.java
package com.carmanagement.service;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.transaction.Transactional;
import com.carmanagement.agentic.workflow.CarProcessingWorkflow;
import com.carmanagement.model.CarConditions;
import com.carmanagement.model.CarInfo;
import com.carmanagement.model.CarStatus;
import io.quarkus.logging.Log;
/**
* Service for managing car returns from various operations.
*/
@ApplicationScoped
public class CarManagementService {
@Inject
CarProcessingWorkflow carProcessingWorkflow;
/**
* Process a car return from any operation.
*
* @param carNumber The car number
* @param feedback Optional feedback
* @return Result of the processing
*/
@Transactional
public String processCarReturn(Integer carNumber, String feedback) {
CarInfo carInfo = CarInfo.findById(carNumber);
if (carInfo == null) {
return "Car not found with number: " + carNumber;
}
Log.info("FeedbackWorkflow executing...");
Log.info(" ├─ CleaningFeedbackAgent analyzing...");
Log.info(" └─ MaintenanceFeedbackAgent analyzing...");
Log.info("CarAssignmentWorkflow evaluating conditions...");
// Process the car return using the workflow
CarConditions carConditions = carProcessingWorkflow.processCarReturn(carInfo, carNumber, feedback);
Log.info("CarConditionFeedbackAgent updating...");
// Update the car's condition with the result from CarConditionFeedbackAgent
carInfo.condition = carConditions.generalCondition();
// Update the car status based on the required action
switch (carConditions.carAssignment()) {
case MAINTENANCE:
carInfo.status = CarStatus.IN_MAINTENANCE;
break;
case CLEANING:
carInfo.status = CarStatus.AT_CLEANING;
break;
case NONE:
carInfo.status = CarStatus.AVAILABLE;
break;
}
// Persist the changes to the database
carInfo.persist();
return carConditions.generalCondition();
}
}
Test Your Implementation
Once you've implemented all the parts:
- Start your application:
Linux / macOS
./mvnw quarkus:dev
Windows
mvnw quarkus:dev
-
Test with the scenarios described earlier (in the Test Different Scenarios section)
-
Compare your implementation with the complete solution in
section-2/step-03
Experiment Further
1. Add Priority Levels
What if you wanted to add a third level of priority (e.g., emergency repairs)?
- Add an
EmergencyRepairFeedbackAgent - Update
CarAssignmentWorkflowwith a third condition - Ensure emergency repairs take highest priority
2. Make Feedback Analysis Sequential
Try changing FeedbackWorkflow from @ParallelAgent to @SequenceAgent. How does this affect performance? When might you want sequential analysis?
3. Add More Sophisticated Conditions
The activation conditions of CarAssignmentWorkflow currently only compare the answer of the decision agent with an enum constant. Try adding:
- Cost-based conditions (only send to maintenance if estimated cost < $500)
- Time-based conditions (skip cleaning if it was cleaned in last 24 hours)
- Severity-based conditions (emergency repairs vs. routine maintenance)
4. Visualize the Workflow
Add logging to each agent and workflow to print when they start and finish. Observe the parallel execution in the logs!
Troubleshooting
Parallel agents not executing in parallel
Check that your system has multiple CPU cores and that the thread pool is configured properly. In development mode, Quarkus should handle this automatically.
Conditional workflow always/never executing certain agents
- Verify your
@ActivationConditionmethods are correctly named - Check that parameter names match the
outputKeyvalues exactly - Add logging to the condition methods to see what values they're receiving
- If they receive a
CarAssignmentvalue you didn't expect, compare it with the text ofmaintenanceRequestandcleaningRequestand review the question in@Decide
Error: Cannot find symbol 'CarAssignment'
Make sure you created both:
- The
CarAssignmentenum - Updated
CarConditionsto use it
Agents getting wrong input values
Remember that parameter names must match the outputKey from previous agents or workflow inputs. Check for typos!
Cleanup
Before moving to the next step, let's clean up:
-
Stop the running server by pressing
Ctrl+Cin the terminal where Quarkus is running -
Return to the root project directory:
cd ..
What's Next?
You've built a sophisticated multi-level nested workflow combining sequence, parallel, and conditional execution!
In Step 04, you'll learn about using a supervisor pattern for dynamic orchestration of a set of agents!
Continue to Step 04 - Supervisor Pattern for Dynamic Orchestration