Tag Archives: Agentic Design Patterns

Agentic Design Patterns using N8N – Routing Pattern

The routing pattern directs an incoming request to a suitable handler. A model or predefined rules determine the request’s category, then the application selects the instructions, tool, or workflow that should process it.

In the Java implementation, classes and conditional logic perform these steps. This example uses n8n nodes and connections to express the same flow: classify a request, select a branch, and generate a response.

Info: The workflow and supporting documentation are available in the project’s n8n directory.

Organizing the workflow

Two Basic LLM Chain nodes handle the model calls. The first classifies each request. A Switch node after the first LLM node selects a branch containing the appropriate handler instructions. All three branches connect to a shared second chain that generates the answer. The final nodes format each response, convert it into a text file, and save it to disk.

The overview shows the complete path from the Manual Trigger to file output. The model connections beneath the LLM Chains supply model configuration.

CategoryResponsibility
BOOKINGAcknowledge requests concerning flights or hotels.
INFOAnswer general knowledge questions.
UNCLEARRespond to ambiguous requests or requests outside the other categories.

Info: The booking branch does not make reservations, and the information branch does not search the web. This keeps the example focused on routing.

Creating the sample requests

Execute Routing Example is a Manual Trigger. It starts the workflow and passes control to Requests, a Code node that creates the three sample items. Coordinator Instructions then adds the classification prompt.

The connection labels show the transition from one trigger item to three request items. Each request travels through the classification and routing steps independently.

return [
  { json: { request: "Book me a flight to London." } },
  { json: { request: "What is the capital of Italy?" } },
  { json: { request: "Do that thing for me." } }
];

The Code node is configured to Run Once for All Items. It returns three separate n8n items, each with a json.request field.

Defining the coordinator’s instructions

Coordinator Instructions is an Edit Fields node in JSON mode. It adds an INSTRUCTIONS field containing the classification prompt.

{
  "INSTRUCTIONS": "Classify the user's request into exactly one category:\nBOOKING: Requests related to booking flights or hotels.\nINFO: General information questions.\nUNCLEAR: Ambiguous requests or requests outside those categories.\nReturn only BOOKING, INFO, or UNCLEAR. Do not answer the request itself."
}

Include Other Input Fields is enabled, so the original request remains in the output. The screenshot shows both fields on each item. This JSON defines workflow fields; it does not constrain the model’s answer to a JSON schema.

Configuring the model

The OpenAI Chat Model supplies credentials and model settings to the first chain. The screenshot selects gpt-5-mini and enables the Responses API. Select an OpenAI credential and a model available to your account.

The model is connected to the chain’s Model input, as shown below. It supplies the language model used by the chain.

Classifying each request

The first Basic LLM Chain acts as the coordinator. Set the prompt source to Define below, use the current request as the user prompt, and add a System message containing the classification instructions.

SettingValue
Prompt (User Message){{ $json.request }}
System message{{ $json.INSTRUCTIONS }}
Require Specific Output FormatOff

The output pane shows three items whose text values are BOOKING, INFO, and UNCLEAR. The coordinator returns the classification rather than answering the original request. The Basic LLM Chain documentation describes these prompt and message settings.

Selecting a route

Route by Request Category is a Switch node. Its three outputs connect to Booking Instructions, Info Instructions, and Unclear Instructions.

Use Rules mode and compare the classifier’s returned text with each supported category. Each rule reads the following expression:

{{ $json.text.trim() }}
ComparisonOutput
Is equal to BOOKINGBOOKING
Is equal to INFOINFO
Is equal to UNCLEARUNCLEAR

The model determines the category. The Switch performs the comparison and sends the item through the matching connection without making another model call. The screenshot shows one item on each category output.

trim() removes surrounding whitespace. The comparisons remain case-sensitive and do not accept explanatory sentences or quoted category names. The exported workflow has no fallback output, so unexpected classification text does not reach a handler. UNCLEAR is an explicit category, not a fallback for malformed output. See the Switch documentation for fallback options.

Preparing the selected handler

Each instruction branch uses an Edit Fields node to prepare request, category, and handlerInstructions. The booking branch is shown below.

The classifier returns its answer in text. To recover the original request, the branch references the linked item from Coordinator Instructions:

{{ $('Coordinator Instructions').item.json.request }}

n8n’s item linking associates the classification with the request that produced it. Using .item preserves that relationship rather than retrieving the first sample request for every branch.

{{ JSON.stringify({
  request: $('Coordinator Instructions').item.json.request,
  category: $json.text.trim(),
  handlerInstructions: "You are a booking assistant. Acknowledge the user's travel request briefly. Do not ask questions or request additional details. Do not claim to have booked anything or checked live availability."
}) }}

JSON.stringify() produces the JSON text expected by this node’s JSON-mode parameter. The resulting output exposes the three values as workflow fields.

The information branch supplies instructions to answer briefly, acknowledge uncertainty, and avoid claims of live research. The unclear branch asks for the fixed answer Your request was unclear. without follow-up questions.

Generating the answer

All three instruction nodes connect to Handle Request, a second Basic LLM Chain with its own connected OpenAI Chat Model node.

The selected branch supplies the system instructions, while the original request remains the user prompt. Set the prompt source to Define below and configure these fields:

SettingValue
Prompt (User Message){{ $json.request }}
System message{{ $json.handlerInstructions }}

The input pane exposes the branch data, and the output pane shows the generated text. The selected run in this screenshot includes additional wording after the unclear response. That differs from the requested fixed answer and illustrates why successful node execution still requires output review.

The shared chain keeps model-call configuration in one place. The branches vary its behavior through their instructions. These converging connections do not collect all answers into one item or synchronize the branches. The chain processes the items arriving from each branch.

Normal successful processing of the three samples requires six model calls: three classifications and three responses, excluding retries. The unclear branch also makes a second call, even though its instructions request fixed wording.

Formatting and saving responses

The final three nodes separate presentation from response generation. Format Final Response creates a String field named message with a heading, the handler’s returned text, and a footer. This step formats the answer without making another model call.

Plain Text Response uses Convert to File with Convert to Text File selected. Its Text Input Field is message, and the output binary field is data. The input setting contains the field name, not an expression containing the text. The binary output can be viewed or downloaded.

Read/Write Files from Disk then writes that binary data using this filename expression:

{{ '/files/output/output-' + $execution.id + '-' + ($runIndex + 1) + '.txt' }}

The execution ID distinguishes workflow executions. The run index distinguishes separate invocations of the writing node within an execution. For the three sample requests taking separate branches, filenames can look like:

Running the example

Import the workflow JSON, then select your OpenAI credential in both model nodes.

Info: This example runs in Docker. /files/output is a container path mapped to a host folder by the project’s Compose configuration. Confirm that the mount exists and is writable before running the workflow.

The credential screen below shows a successful connection test. Store the key in n8n’s credential configuration rather than in workflow fields.

Start Execute Routing Example, then inspect the classification output, selected branches, generated responses, and saved files. Execution makes live model requests and writes output files.

RequestExpected route
Book me a flight to London.BOOKING
What is the capital of Italy?INFO
Do that thing for me.UNCLEAR

Successful execution shows that the nodes completed. Review the generated text to confirm that each answer follows its selected instructions. This example uses ordinary text classification and has no configured fallback route or conversation memory.

Info: View the complete workflow as JSON at routing-example-workflow.json.

Summary

The n8n implementation separates classification, routing, and response generation into visible workflow steps. A Basic LLM Chain classifies each request, a Switch selects the instructions, and a shared second chain generates the answer. The same routing pattern used in Java is expressed through items, expressions, and node connections, with each stage available for inspection.

Info: Codex generated and edited substantial portions of this document.

Agentic Design Patterns Using Java – Routing Pattern

Image generated in ChatGPT

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.

  • AgenticpatternsApplication implements CommandLineRunner and selects the example using the ROUTING argument.
  • RoutingExampleService supplies sample requests and displays their responses.
  • CoordinatorAgent classifies 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.

AnnotationPurpose in this example
@AgentIdentifies the method as an agent operation and supplies its description.
@SystemMessageDefines the classification instructions.
@UserMessageDefines 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.

  1. coordinatorAgent.classify(request) returns RequestCategory.BOOKING.
  2. The application supplies "request" and "category" to handlers.invoke(...).
  3. The booking predicate matches, and the workflow invokes bookingHandler.
  4. The generated handler implementation calls the model with its booking instructions and the original request.
  5. 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.

ResourceDescriptionLink
Reference documentationModel configuration and the ChatClient API.Spring AI reference
Official examplesSpring AI sample projects, including routing workflows.Examples repository
Routing walkthroughClassification followed by a specialized prompt.Routing Workflow with Spring AI
Patterns overviewRouting alongside other application patterns.Five Spring AI Agentic Patterns
Workflow examplesRouting, failure handling, and model-call costs.Spring AI workflow patterns
Model routingSelects a model using Spring AI TypeSafe and Jev.Model router walkthrough and example code
Provider gatewayProvider routing, failover, and rate limiting.LLM Gateway for Java
Framework sourceSpring 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.

ResourceDescriptionLink
API referenceJava request parameters and response types.OpenAI Java API reference
Source and examplesSDK source, setup instructions, and usage examples.OpenAI Java SDK repository
Libraries overviewOpenAI 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.

ResourceDescriptionLink
Reference documentationFramework introduction and integration guides.LangChain4j documentation
AI ServicesAnnotated interfaces, prompt templates, and output conversion.AI Services guide
Agents and workflowsAgent builders, conditional workflows, and AgenticScope.Agents and Agentic AI
Model routingSelects a ChatModel through a ChatModelRouter.Model routing guide
RoutingChatModelSource for the model-routing implementation.API / source
DecisionModelChatModelRouterUses a decision model to select a route.Javadoc
Retrieval routingSelects content retrievers for a query.QueryRouter Javadoc and example code
Decision routerDecisionRouterPlanner for agent selection.Javadoc
Framework sourceLangChain4j 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.