
The routing pattern directs an incoming request to a suitable handler. A router determines the request’s category or intent, then selects an agent, tool, or workflow. Classification can use predefined rules or a model, allowing each handler to focus on a specific task. In this blog post, you explore using the routing pattern from the book Agentic Design Patterns using Java (Spring AI, LangChain4j, and OpenAI Java SDK).
Info: See Agentic Design Patterns Using n8n – Routing Pattern for an implementation of this pattern as an n8n workflow.
Antonio Gulli’s Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems presents 21 patterns with explanations and Python examples. In this series, I implement examples from the book in Java.
Info: This post implements the same routing example with Spring AI, the OpenAI Java SDK, and LangChain4j. Using the same requests and instructions makes their differences in configuration, model calls, and handler selection easier to compare.

The routing example in chapter two of Gulli’s book has three categories.
- BOOKING: Requests related to flights or hotels.
- INFO: General information questions.
- UNCLEAR: Ambiguous requests or requests outside the other categories.
The example uses three sample requests.
- Book me a flight to London.
- What is the capital of Italy?
- Do that thing for me.
The coordinator classifies the input. Java code or a conditional workflow then selects the handler that processes the original request.
The booking handler acknowledges a travel request without making a reservation. The information handler answers from the model’s knowledge without a live search. The unclear handler is instructed to reply, “Your request was unclear.”
Info: The Java examples are available in the project repository, with subprojects for Spring AI, the OpenAI Java SDK, and LangChain4j.
All three examples use the following classification and handler instructions.
Classify the user's request into exactly one category:
BOOKING: Requests related to booking flights or hotels.
INFO: General information questions.
UNCLEAR: Ambiguous requests or requests outside those categories.
Return only BOOKING, INFO, or UNCLEAR. Do not answer the request itself.
INFO
You are an information assistant.
Answer the user's general knowledge question briefly and clearly.
Acknowledge uncertainty when you do not know the answer.
Do not claim to have searched the web or checked live information.
Do not ask questions or request additional details.
BOOKING
You are a booking assistant.
Acknowledge the user's travel request without asking questions or requesting
additional details.
Keep your response brief.
Do not claim to have booked anything or checked live availability.
UNCLEAR
Reply only with: Your request was unclear.
Do not ask questions or request additional details.Each successfully processed request normally makes two model calls: one for classification and one for the selected handler’s response. All three versions pass the original request to the handler, including UnclearHandler, which uses a model call even though its instructions request fixed wording.
Routing with Spring AI

Organizing the application
Spring AI uses a shared ChatClient and Spring-managed classes. CoordinatorAgent handles both classification and handler selection.
There are three main responsibilities.
AgenticpatternsApplicationimplementsCommandLineRunnerand selects the example using theROUTINGargument.RoutingExampleServicesupplies sample requests and displays their responses.CoordinatorAgentclassifies each request, selects a handler, and returns its answer.
Creating the shared client
The ChatClientConfig configuration class provides one shared ChatClient bean.
@Bean
public ChatClient routingChatClient(ChatClient.Builder builder) {
return builder.build();
}Spring AI supplies the configured ChatClient.Builder. The coordinator and handlers receive the resulting client through constructor injection.
Info: Sharing a client shares configuration and does not automatically share conversation history or combine the coordinator’s instructions with a handler’s instructions (see chapter 8, Memory Management).
Processing the sample requests
The RoutingExampleService Spring service defines the requests.
private static final List<String> REQUESTS = List.of(
"Book me a flight to London.",
"What is the capital of Italy?",
"Do that thing for me.");RoutingExampleService receives a CoordinatorAgent. When AgenticpatternsApplication runs with the ROUTING command-line argument, it calls the service’s runExample() method.
The service loops through the requests and calls coordinator.handleRequest(request) for each one.
for (String request : REQUESTS) {
String response = coordinator.handleRequest(request);
}Classifying and routing requests
The CoordinatorAgent defines instructions to examine a request and identify it as one of the three RequestCategory values.
private static final String INSTRUCTIONS = """
Classify the user's request into exactly one category:
BOOKING: Requests related to booking flights or hotels.
INFO: General information questions.
UNCLEAR: Ambiguous requests or requests outside those categories.
Return only BOOKING, INFO, or UNCLEAR. Do not answer the request itself.
""";The classification is represented by the RequestCategory enum.
public enum RequestCategory {
BOOKING,
INFO,
UNCLEAR;
}The coordinator passes its instructions and the original request to ChatClient. It converts the returned text to RequestCategory with RequestCategory.valueOf(requestType.trim()).
public String handleRequest(String request) {
String requestType = chatClient.prompt()
.system(INSTRUCTIONS)
.user(request)
.call()
.content();
RequestCategory category;
try {
category = RequestCategory.valueOf(requestType.trim());
} catch (IllegalArgumentException exception) {
throw new IllegalStateException("Invalid category", exception);
}
return routeRequest(category, request);
}.system(INSTRUCTIONS) supplies the classification rules, and .user(request) supplies the original request. .call() performs the model call, and .content() returns the generated text.
The coordinator’s routeRequest() method selects an InfoHandler, BookingHandler, or UnclearHandler and passes the original request with that handler’s instructions.
private String routeRequest(RequestCategory requestCategory, String request) {
return switch (requestCategory) {
case INFO -> infoHandler.handle(request, InfoHandler.INSTRUCTIONS);
case BOOKING -> bookingHandler.handle(request, BookingHandler.INSTRUCTIONS);
case UNCLEAR -> unclearHandler.handle(request, UnclearHandler.INSTRUCTIONS);
};
}Sharing the handler implementation
Each handler extends RequestHandler and inherits its concrete handle(request, instructions) method. The subclasses supply their own INSTRUCTIONS constants without overriding the method.
public String handle(String request, String instructions)
{
String response = chatClient.prompt()
.system(instructions)
.user(request)
.call()
.content();
return response;
}The sequence diagram follows a request from RoutingExampleService through classification and response generation. CoordinatorAgent selects the handler and passes the original request with that handler’s instructions.

Info: Spring AI source code on GitHub
Routing with OpenAI Java SDK

The OpenAI Java SDK version constructs its objects directly in main(). The coordinator classifies requests, while RoutingExample selects the handler. A shared OpenAiTextService makes the model calls. OpenAIOkHttpClient.fromEnv() reads client settings from the environment, and ProviderModelSettings.MODEL_NAME supplies the model name.
Creating the client and selecting handlers
RoutingExample.main() creates the OpenAI client, the shared text service, the coordinator, and three handlers. It classifies each sample request, selects a handler with a Java switch, and passes that handler the original request.
public static void main(String[] args) {
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
try {
OpenAiTextService textService = new OpenAiTextService(client,
ProviderModelSettings.MODEL_NAME);
CoordinatorAgent coordinatorAgent = new CoordinatorAgent(textService);
BookingHandler bookingHandler = new BookingHandler(textService);
InfoHandler infoHandler = new InfoHandler(textService);
UnclearHandler unclearHandler = new UnclearHandler(textService);
String[] requests = {
"Book me a flight to London.",
"What is the capital of Italy?",
"Do that thing for me."
};
for (String request : requests) {
RequestCategory category = coordinatorAgent.classify(request);
RequestHandler handler = switch (category) {
case BOOKING -> bookingHandler;
case INFO -> infoHandler;
case UNCLEAR -> unclearHandler;
};
String response = handler.handle(request);
}
} finally {client.close();}
}Classifying and routing requests
CoordinatorAgent.classify(request) calls textService.generate(INSTRUCTIONS, request) with the classification instructions. It converts the returned text to RequestCategory using RequestCategory.valueOf(response.trim()). The switch in main() then selects the handler.
Each handler implements the RequestHandler interface and defines handle(String request). That method calls the shared text service with the handler’s own instructions and the original request. In the Spring AI version, the handlers instead inherit a shared implementation from an abstract class.
Calling the model through a shared service
OpenAiTextService holds a shared OpenAIClient that sends requests through the Responses API. Both the coordinator and the handlers use this service.
The generate(instructions, request) method builds the request parameters, calls client.responses().create(params), and extracts the generated text. The project also checks completion status, refusals, and blank output; those checks are omitted from this snippet.
public String generate(String instructions, String request) {
ResponseCreateParams params = ResponseCreateParams.builder()
.model(modelName)
.instructions(instructions)
.input(request)
.build();
Response response = client.responses().create(params);
String text = response.output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.map(outputText -> outputText.text())
.collect(Collectors.joining());
return text;
}Building parameters and reading the response
ResponseCreateParams is a class in the official OpenAI Java SDK that holds the parameters for a request to the Responses API. Here, .model(modelName) selects the model, .instructions(instructions) supplies the system or developer instructions that guide its behavior, and .input(request) provides the user’s request.
Response is the OpenAI Java SDK class that represents the result returned by the Responses API, including generated output, completion status, and token usage. In this statement, client.responses().create(params) sends the configured request to OpenAI and assigns the returned result to response.
Info: See Creating a model response in the OpenAI Java API reference.
The sequence diagram shows the two model calls made through OpenAiTextService. The coordinator returns a category to RoutingExample, which selects a handler and calls it with the original request.

Info: Github OpenAI SDK example project (openai).
Routing with LangChain4j

The LangChain4j implementation defines the coordinator and handlers as annotated Java interfaces. LangChain4j supplies their implementations at runtime, and its agentic module provides the conditional workflow that selects a handler.
The three steps remain the same: classify the request, select a handler, and generate an answer. Annotations define the model messages, builders create the agents, and workflow state carries data between steps.
Creating the shared model
RoutingExample.main() begins by constructing an OpenAiChatModel.
OpenAiChatModel model = OpenAiChatModel.builder()
.apiKey(ProviderModelSettings.API_KEY)
.modelName(ProviderModelSettings.MODEL_NAME)
.build();OpenAiChatModel is LangChain4j’s OpenAI chat-model implementation. ProviderModelSettings reads the API key from OPENAI_API_KEY and selects gpt-4o-mini.
The coordinator and all three handlers receive the same model object when built. Each agent still has its own instructions and receives its own input.
The project uses three LangChain4j dependencies: langchain4j supplies the AI Services functionality, langchain4j-open-ai provides the OpenAI integration, and langchain4j-agentic supplies agent construction and workflow orchestration.
Defining model behavior with interfaces
CoordinatorAgent is an interface containing one annotated method.
public interface CoordinatorAgent {
@Agent("Classifies a request for routing to the appropriate handler")
@SystemMessage("""
Classify the user's request into exactly one category:
BOOKING: Requests related to booking flights or hotels.
INFO: General information questions.
UNCLEAR: Ambiguous requests or requests outside those categories.
Return only BOOKING, INFO, or UNCLEAR. Do not answer the request itself.
""")
@UserMessage("{{request}}")
RequestCategory classify(@V("request") String request);
}The interface declares classify() without a method body. LangChain4j creates an implementation that builds the messages, calls the model, and converts the output to RequestCategory. The Spring AI and OpenAI SDK examples perform that conversion explicitly in Java (LangChain4j AI Services).
The annotations divide the declaration into four parts.
| Annotation | Purpose in this example |
|---|---|
@Agent | Identifies the method as an agent operation and supplies its description. |
@SystemMessage | Defines the classification instructions. |
@UserMessage | Defines the user-message template. |
@V("request") | Associates the method argument with the template variable named request. |
The handler interfaces follow the same structure. For example, BookingHandler uses these annotations as follows.
@Agent("Handles flight and hotel booking inquiries")
@SystemMessage("""
You are a booking assistant.
Acknowledge the user's travel request without asking questions or requesting additional details.
Keep your response brief.
Do not claim to have booked anything or checked live availability.
Do not ask questions or request additional details.
""")
@UserMessage("{{request}}")
String handle(@V("request") String request);The handler returns the model’s response as a String. InfoHandler and UnclearHandler use the same method signature with different system instructions.
Building executable agents
An annotated interface describes an agent, but the application still needs an object it can invoke. AgenticServices.agentBuilder() creates that object.
BookingHandler bookingHandler =
AgenticServices.agentBuilder(BookingHandler.class)
.chatModel(model)
.outputKey("response")
.build();BookingHandler.class identifies the interface to implement and .chatModel(model) supplies the configured model. The .build() method returns an implementation assignable to BookingHandler. The coordinator, information handler, and unclear handler are constructed in the same way.
AgenticServices provides factory methods for creating agents and workflows (AgenticServices API).
The .outputKey("response") setting names the state entry where the handler’s return value is stored. All three handlers use the same key because each selected branch produces the workflow’s answer.
Defining the conditional workflow
The earlier implementations select a handler with a Java switch. This implementation registers conditions and their associated agents with a conditional workflow.
UntypedAgent handlers = AgenticServices
.conditionalBuilder()
.subAgents(
scope -> scope.readState("category")
== RequestCategory.BOOKING,
bookingHandler)
.subAgents(
scope -> scope.readState("category")
== RequestCategory.INFO,
infoHandler)
.subAgents(
scope -> scope.readState("category")
== RequestCategory.UNCLEAR,
unclearHandler)
.output(scope -> scope.readState("response"))
.build();Each .subAgents(...) call associates a Java predicate with a handler. The predicate reads the category from workflow state and compares it with an enum constant. For these three mutually exclusive conditions, one handler matches the supplied category.
The model determines the category during classification. The conditional workflow evaluates the Java predicates to determine which handler executes. The descriptions in @Agent do not select these branches (Conditional workflow API).
The final .output(...) function defines the workflow’s return value. After the selected handler stores its answer under "response", this function reads that entry and returns it to the caller.
Passing data through AgenticScope
The scope parameter is an AgenticScope, the shared execution context for a workflow. Conditions and agents read or write its named state entries. This example uses "request" for the original text, "category" for the classification, and "response" for the answer (AgenticScope API).
The application supplies the initial values through a map.
RequestCategory category = coordinatorAgent.classify(request);
Map<String, Object> arguments = Map.of(
"request", request,
"category", category
);
Object response = handlers.invoke(arguments);UntypedAgent provides a general workflow entry point accepting a map of named inputs and returning Object. LangChain4j makes those inputs available in the workflow’s scope. It uses the handler parameter’s @V("request") name to resolve the original request from state. The category controls selection; it is not included in the handler’s user-message template. Agents and Agentic AI
For a booking request, the data moves through the workflow as follows.
coordinatorAgent.classify(request)returnsRequestCategory.BOOKING.- The application supplies
"request"and"category"tohandlers.invoke(...). - The booking predicate matches, and the workflow invokes
bookingHandler. - The generated handler implementation calls the model with its booking instructions and the original request.
- The handler’s answer is stored under
"response", which the workflow returns.
The coordinator is called separately before the conditional workflow. Although its builder also specifies .outputKey("response"), that setting does not populate the handler workflow’s "category" entry. The application explicitly transfers the classification into the input map.
The sequence diagram shows how classification feeds the conditional workflow. The workflow evaluates the category predicates, invokes the matching handler, and returns its response through AgenticScope.

Info: Github LangChain4j example project (langchain4j).
Other Resources
The following documentation and examples provide more detail on the APIs used in this post. Some resources also cover related forms of routing: choosing a model, a provider, or a source of retrieved content.
Spring AI
Start with the reference documentation and examples repository for ChatClient and routing workflows. The community articles below include additional implementations and related model-routing and gateway examples.
| Resource | Description | Link |
|---|---|---|
| Reference documentation | Model configuration and the ChatClient API. | Spring AI reference |
| Official examples | Spring AI sample projects, including routing workflows. | Examples repository |
| Routing walkthrough | Classification followed by a specialized prompt. | Routing Workflow with Spring AI |
| Patterns overview | Routing alongside other application patterns. | Five Spring AI Agentic Patterns |
| Workflow examples | Routing, failure handling, and model-call costs. | Spring AI workflow patterns |
| Model routing | Selects a model using Spring AI TypeSafe and Jev. | Model router walkthrough and example code |
| Provider gateway | Provider routing, failover, and rate limiting. | LLM Gateway for Java |
| Framework source | Spring AI source code and project documentation. | Spring AI repository |
OpenAI Java SDK
The SDK reference describes request parameters, response types, and model calls. The repository includes Java examples. In the implementation shown here, the application supplies the classification and handler-selection logic.
| Resource | Description | Link |
|---|---|---|
| API reference | Java request parameters and response types. | OpenAI Java API reference |
| Source and examples | SDK source, setup instructions, and usage examples. | OpenAI Java SDK repository |
| Libraries overview | OpenAI client libraries and installation guidance. | OpenAI libraries |
LangChain4j
The AI Services and agentic documentation explain the interfaces and conditional workflow used in this post. Model routing and retrieval routing are related features: they select a model or content retriever rather than one of this example’s handler agents.
| Resource | Description | Link |
|---|---|---|
| Reference documentation | Framework introduction and integration guides. | LangChain4j documentation |
| AI Services | Annotated interfaces, prompt templates, and output conversion. | AI Services guide |
| Agents and workflows | Agent builders, conditional workflows, and AgenticScope. | Agents and Agentic AI |
| Model routing | Selects a ChatModel through a ChatModelRouter. | Model routing guide |
| RoutingChatModel | Source for the model-routing implementation. | API / source |
| DecisionModelChatModelRouter | Uses a decision model to select a route. | Javadoc |
| Retrieval routing | Selects content retrievers for a query. | QueryRouter Javadoc and example code |
| Decision router | DecisionRouterPlanner for agent selection. | Javadoc |
| Framework source | LangChain4j source code and project documentation. | LangChain4j repository |
Summary
All three implementations follow the same routing pattern: classify the request, select a handler, and generate a response. Spring AI uses Spring-managed classes and a shared ChatClient. The OpenAI Java SDK keeps model calls and routing explicit in Java. LangChain4j creates implementations from annotated interfaces and executes handlers through a conditional workflow. The example stays the same, making it easier to compare how each approach handles prompts, classification, and handler selection.
Info: This post was extensively edited with assistance from OpenAI Codex. All work remains the author’s own.


