Agentic Design Patterns using Java and N8N – Pipeline Pattern

The prompt chaining, or pipeline, pattern passes output from one task to the next. This article follows a laptop description through two model calls: one extracts its specifications, and the other formats them as JSON. The examples use Spring AI, the OpenAI Java SDK, LangChain4j, and n8n.

The example presented here adapts the prompt chaining workflow from Antonio Gullí’s Agentic Design Patterns: A Hands-On Guide to Building Intelligent Systems. Each implementation processes the same product description and requests the keys cpu, memory, and storage.

The examples use the following product description and two sets of instructions. Each Java handler receives the instructions for its stage.

Info: The prompt texts were altered slightly in this post from the book’s example.

Product description

Experience the power to take on your day with a laptop built around a
3.5 GHz octa-core processor and 16GB of RAM. Whether you’re moving between
work projects, browsing your favorite sites, or enjoying your downtime,
this combination puts capable performance at your fingertips.
A spacious 1TB NVMe SSD gives you room for your documents, photos,
applications, and media, along with fast access to the files you need.
From your first task of the morning to your next creative project,
this laptop brings processing power, memory, and storage together
to help you keep moving.

Extraction instructions

Extract the technical specifications from the following text.

Formatting instructions

Transform the following specifications into a JSON object with
"cpu", "memory", and "storage" as keys.
Return only the JSON object.
Do not include Markdown code fences, explanations, or other text.

The first stage extracts specifications from the product description. The second receives those specifications and organizes them as JSON.

Info: The GitHub project contains the Java source code and the importable n8n pipeline workflow for this blog post.

Prompt Chaining with Spring AI

For a Spring application, prompt chaining provides a way to organize AI processing around tasks with defined responsibilities. Each stage receives the information it needs, performs one operation, and supplies a result to the next stage. The Spring AI example applies this approach to the laptop description, separating the identification of specifications from their presentation as JSON.

Info: The example classes are intentionally simple to keep the focus on the prompt chaining pattern and the flow of data between its stages.

The Spring AI example resides in com.jamesabrannan.agenticpatterns.springai.pipeline and its handlers subpackage. PipelineExampleService starts the workflow by calling PipelineAgent.executePipeline(). The agent holds an ExtractHandler and a FormatHandler, each responsible for one stage.

Both handlers extend the project’s RequestHandler and receive an org.springframework.ai.chat.client.ChatClient through their constructors. This interface provides the prompt API used to send instructions and input to the model. The inherited method creates a prompt, sets the system instructions with system(instructions), supplies the stage input with user(request), sends the request with call(), and retrieves the response text with content().

String response = chatClient.prompt()
        .system(instructions)
        .user(request)
        .call()
        .content();

ExtractHandler.handle(request) passes the product description and extraction instructions to the inherited method. FormatHandler.handle(request) passes the extracted specifications and instructions requesting a JSON object. Each handler returns the model’s text to PipelineAgent.

Executing the two model calls

The following sequence diagram illustrates the application’s workflow.

PipelineExampleService.runExample() calls PipelineAgent.executePipeline(). The agent passes the product description to ExtractHandler, trims the response, and passes the extracted specifications to FormatHandler.

String response = this.extractHandler.handle(inputText).trim();
String result = this.formatHandler.handle(response).trim();
return result;

After the agent returns, PipelineExampleService parses the result with Jackson and prints it with indentation. readTree(result) parses the returned text; the writer then serializes that tree for console output.

String result = agent.executePipeline();
JsonMapper mapper = JsonMapper.builder().build();
String prettyJson = mapper.writerWithDefaultPrettyPrinter()
        .writeValueAsString(mapper.readTree(result));
System.out.println("Final JSON output:");
System.out.println(prettyJson);

Here, the application controls the sequence and transfers results between stages. Spring AI supplies the model-call API, while the Java classes define the workflow.

Prompt Chaining with OpenAI Java SDK

A pipeline does not require a framework dedicated to agent workflows. The OpenAI Java SDK and Spring AI leave workflow composition to application code, while LangChain4j provides abstractions for connecting agents. As the previous section demonstrated, an application implements a pipeline by dividing a task into stages and passing results between them. The OpenAI Java SDK example follows this approach: two model requests form a workflow, with the second using the output of the first.

The OpenAI Java SDK example resides in com.jamesabrannan.agenticpatterns.openai.pipeline. PipelineExample.main() creates the client and the shared OpenAiTextService, then passes the service to PipelineAgent. The agent constructs both handlers with that service.

The com.openai.client.okhttp.OpenAIOkHttpClient.fromEnv() method creates a client using environment settings. The returned com.openai.client.OpenAIClient exposes the API operations used by the text service. ProviderModelSettings.MODEL_NAME supplies the model name when the application constructs the service.

OpenAIClient client = OpenAIOkHttpClient.fromEnv();
try {
    OpenAiTextService textService =
            new OpenAiTextService(client, ProviderModelSettings.MODEL_NAME);
    PipelineAgent agent = new PipelineAgent(textService);
    String jsonString = agent.executePipeline();
    JsonMapper mapper = JsonMapper.builder().build();
    String prettyJson = mapper.writerWithDefaultPrettyPrinter()
            .writeValueAsString(mapper.readTree(jsonString));
    System.out.println("Final JSON output:");
    System.out.println(prettyJson);
} finally {
    client.close();
}

After the pipeline returns, PipelineExample parses the text with Jackson’s com.fasterxml.jackson.databind.json.JsonMapper and prints it with indentation. The entry point declares throws JsonProcessingException using com.fasterxml.jackson.core.JsonProcessingException, so parsing failures propagate to the caller. The finally block closes the client even if parsing fails.

ExtractHandler and FormatHandler implement the project’s RequestHandler interface. Each defines handle(String request) and calls textService.generate(INSTRUCTIONS, request). The extraction handler requests specifications; the formatting handler requests a JSON object with the three output keys.

Executing the two Responses API calls

The sequence diagram follows PipelineAgent.executePipeline() through extraction and formatting.

public String executePipeline() {
    String response = extractHandler.handle(inputText).trim();
    response = formatHandler.handle(response).trim();
    return response;
}

The agent passes the product description to ExtractHandler, trims the returned specifications, then passes them to FormatHandler.

For each stage, the text service builds a com.openai.models.responses.ResponseCreateParams instance. The builder selects the model with model(modelName), supplies instructions with instructions(instructions), and sets the input with input(request). The call client.responses().create(params) sends the request and returns a com.openai.models.responses.Response containing its status and output.

ResponseCreateParams params = ResponseCreateParams.builder()
        .model(modelName)
        .instructions(instructions)
        .input(request)
        .build();
Response response = client.responses().create(params);

The application creates the chain by passing one request’s result to the next. The SDK sends the requests; the Java pipeline determines their order and connects their results.

Prompt Chaining with LangChain4j

As a workflow grows, it needs a way to define execution order and pass results between stages. LangChain4j provides abstractions for composing agents into workflows. This example declares extraction and formatting as a sequence, with the result of the first stage supplying the input for the second.

The workflow builders come from langchain4j-agentic. This project uses version 1.24.0-beta34 alongside LangChain4j 1.24.0. The agentic module documentation identifies the module as experimental, so its APIs may change between versions.

The classes in com.jamesabrannan.agenticpatterns.langchain4j.pipeline define the stages as interfaces and build a sequence from them. The PipelineExample class creates a dev.langchain4j.model.openai.OpenAiChatModel using the configured API key and model name. This class implements the dev.langchain4j.model.chat.ChatModel interface accepted by PipelineAgent.

OpenAiChatModel model = OpenAiChatModel.builder()
        .apiKey(ProviderModelSettings.API_KEY)
        .modelName(ProviderModelSettings.MODEL_NAME)
        .build();
PipelineAgent agent = new PipelineAgent(model);

The ExtractHandler interface declares the extraction operation. @dev.langchain4j.agentic.Agent marks the method as an agent operation. @dev.langchain4j.service.SystemMessage supplies its instructions, while @dev.langchain4j.service.UserMessage defines the input template. @dev.langchain4j.service.V("inputText") names the argument that fills {{inputText}}.

@Agent("Extracts technical specifications")
@SystemMessage(INSTRUCTIONS)
@UserMessage("{{inputText}}")
String handle(@V("inputText") String request);

FormatHandler declares the same return type with a different input name. Its @dev.langchain4j.service.UserMessage("{{specifications}}") template receives the extraction result through the argument marked @dev.langchain4j.service.V("specifications"). Its system instructions request JSON.

@Agent("Formats extracted specifications as JSON")
@SystemMessage(INSTRUCTIONS)
@UserMessage("{{specifications}}")
String handle(@V("specifications") String specifications);

dev.langchain4j.agentic.AgenticServices.agentBuilder() creates implementations of the two interfaces. The chatModel(model) setting assigns the shared model, and outputKey(...) names the state entry that receives the agent’s return value. The extractor writes to specifications; the formatter writes to json.

ExtractHandler extractHandler = AgenticServices.agentBuilder(ExtractHandler.class)
        .chatModel(model)
        .outputKey("specifications")
        .build();
FormatHandler formatHandler = AgenticServices.agentBuilder(FormatHandler.class)
        .chatModel(model)
        .outputKey("json")
        .build();

Passing named state through the sequence

The following sequence diagram illustrates the processing.

The dev.langchain4j.agentic.AgenticServices.sequenceBuilder() builds a workflow whose subAgents(extractHandler, formatHandler) setting fixes the execution order. The output function reads the json entry after the formatter finishes. PipelineAgent stores the workflow as a dev.langchain4j.agentic.UntypedAgent, which accepts a map of named inputs and returns an object.

The extractor stores its result under specifications. The sequence uses that entry to supply the formatter’s parameter marked @dev.langchain4j.service.V("specifications"). The formatter stores its result under json, which becomes the pipeline’s return value.

this.pipeline = AgenticServices.sequenceBuilder()
     .subAgents(extractHandler, formatHandler)
     .output(scope -> scope.readState("json"))
     .build();

executePipeline(inputText) supplies the product description under the inputText key. The workflow returns the formatter’s output, which the method casts to a string and trims.

String result = ((String) pipeline.invoke(
        Map.of("inputText", inputText))).trim();
return result;

PipelineExample parses the returned text with Jackson, rejects trailing tokens, requires the root value to be an object, and prints the JSON with indentation. These checks do not verify the specification values or require the three requested keys.

LangChain4j defines and runs the sequence through its workflow API. The agents describe the tasks, while the sequence manages their execution and passes results between them.

Prompt Chaining with N8N

A visual workflow offers another way to express the dependencies between AI tasks. In n8n, the pipeline appears as a path from the product description to the resulting JSON, with each stage represented in the workflow. This view places the processing steps and the movement of information together on one canvas.

The workflow expresses the two stages through connected nodes. A Manual Trigger starts the execution. Format input and instructions creates the product description and prompts. Extract specifications makes the first model call; Format specifications receives its result and makes the second. Each chain connects to an OpenAI Chat Model node, and the formatting chain also connects to a Structured Output Parser.

Creating the input and instructions

Format input and instructions uses an Edit Fields node in JSON mode to create one item with three fields: input, extract, and format. The input field holds the laptop description. The extract field asks for specifications stated in the text and tells the model to omit missing specifications and assumptions. The format field requests a JSON object containing cpu, memory, and storage.

The output pane shows these fields together. The extraction chain reads the description and extraction instructions from this item. The formatting chain later retrieves the formatting instructions from the same node.

Extracting the specifications

Extract specifications uses a Basic LLM Chain. Its prompt source is Define below. The Prompt (User Message) field reads {{ $json.extract }}, and a User chat message reads {{ $json.input }}. These expressions supply the extraction instruction and product description to the first model call.

The chain returns the specifications in its text field. The screenshot shows the processor, RAM, and storage extracted from the description. The next chain receives this item through the connection between the two nodes.

Formatting the extraction result

Format specifications uses a second Basic LLM Chain. Its prompt reads {{ $('Format input and instructions').item.json.format }} to retrieve the formatting instructions. Its User chat message reads {{ $json.text }} to pass the extractor’s result to the model.

Require Specific Output Format is enabled, and the chain connects to the Structured Output Parser. The screenshot shows an object under output with cpu, memory, and storage fields. The second call restructures the first call’s output into those fields.

Defining the output structure

The Structured Output Parser uses Generate From JSON Example. The example defines nested fields for processor frequency, core count, description, memory size, storage size, and storage type. n8n generates a schema from the property names and value types and treats every field as required. It does not fix the output to the example’s literal values: 3.5 and 16 illustrate numeric fields.

The Java examples request three top-level keys without prescribing their internal structure. The n8n example goes further by defining nested fields through its output parser. Parsing JSON checks its form; it does not establish that the extracted specifications are correct.

{
  "cpu": {
    "frequency_ghz": 3.5,
    "cores": 8,
    "description": "octa-core"
  },
  "memory": {
    "size_gb": 16
  },
  "storage": {
    "size_tb": 1,
    "type": "NVMe SSD"
  }
}

The parser processes the formatting chain’s response and returns the parsed object. The schema defines the field names and value types; the model supplies the values from the extracted specifications. The screenshot’s parser output contains the processor, memory, and storage data from the product description.

n8n defines the sequence through node connections and passes results through workflow items. The canvas shows the flow between stages, and the output parser specifies the structure expected from the formatter.

Running the examples

The Java projects target Java 17 and use Maven. Set OPENAI_API_KEY in the process environment before running an example. The source links below identify each project and entry point; launch the Java entry points from your IDE with the project dependencies on the classpath.

Spring AI project: run com.jamesabrannan.agenticpatterns.springai.AgenticpatternsApplication with PIPELINE as the program argument. Spring configuration reads the key from the environment.

OpenAI Java SDK project: run com.jamesabrannan.agenticpatterns.openai.pipeline.PipelineExample. The client reads its settings from the environment.

LangChain4j project: run com.jamesabrannan.agenticpatterns.langchain4j.pipeline.PipelineExample. The model configuration reads the key from the environment.

n8n pipeline workflow: download the JSON file and import it into n8n. Select your OpenAI credential in both model nodes, then start the Manual Trigger. The export omits local credential bindings.

Running any example makes live model requests. For this input, the workflow uses two model calls: one for extraction and one for formatting, excluding retries.

Summary

All four implementations follow the same flow: extract specifications, pass them to the formatting stage, and return JSON. Spring AI and the OpenAI Java SDK use application code to control the sequence. LangChain4j provides workflow builders and named state entries to connect the stages. n8n expresses the pipeline through nodes, expressions, and connections, with a Structured Output Parser defining the output structure. The choice determines where you define and maintain the workflow: in application code, through an orchestration API, or on a visual canvas.

Leave a Reply

Your email address will not be published. Required fields are marked *