Thursday, 26 November 2026

Optional Agents in LangChain4j: Building Flexible Agentic Workflows

  

In an agentic workflow, not every agent needs to run for every request. Some agents may depend on optional inputs that are not always available. For example, a story-generation workflow might have an AudienceEditor that refines the story based on the target audience. If the user doesn't provide an audience, there may be no reason for that agent to execute.

 

By default, when a LangChain4j agent cannot find one of its required input arguments in the AgenticScope, the workflow fails with a MissingArgumentException. This behavior is useful when an input is mandatory, but it can be restrictive when an agent is only relevant in certain situations.

 

Optional agents solve this problem. By marking an agent as optional, we tell LangChain4j to skip that agent when its required inputs are unavailable and allow the rest of the workflow to continue.

 

In this post, we'll explore how optional agents work in LangChain4j, how to configure them using the optional(true) builder method and the @Agent(optional = true) annotation, and how they can be used to build more flexible and resilient agentic workflows.

 

1. Story Workflow Application

Let’s build following Story Workflow Application.


The workflow is a sequential agentic workflow where each component performs a specific task and passes information through the AgenticScope.

 

StoryRequestAnalyzer: Analyzes the user's natural language request and extracts the topic, style, and audience. If it cannot determine a value, it returns null.

 

StoryRequestAnalyzer storyRequestAnalyzer =
        AgenticServices.agentBuilder(StoryRequestAnalyzer.class)
                .chatModel(chatModel)
                .outputKey("storyRequest")
                .build();

The StoryRequestAnalyzer analyzes the user's request and extracts:

 

·      topic

·      style

·      audience

 

Its result is stored in the AgenticScope using the key 'storyRequest'.

 

For example:

storyRequest = {
    topic: "dragons and wizards",
    style: "fantasy",
    audience: "children"
}

   

extractStoryRequest: This is an AgenticScopeAction, not an LLM agent. It reads the StoryRequest, applies default values for missing topic and style, and writes topic, style, and audience into the AgenticScope.

 

AgenticScopeAction extractStoryRequest =
        AgenticServices.agentAction(scope -> {

            StoryRequest storyRequest =
                    (StoryRequest) scope.readState("storyRequest");

            if (storyRequest.getTopic() == null
                    || storyRequest.getTopic().isBlank()) {

                System.out.println(
                        "Unable to deduce the topic, setting to 'Any Interesting Topic'");

                storyRequest.setTopic("Any Interesting Topic");
            }

            if (storyRequest.getStyle() == null
                    || storyRequest.getStyle().isBlank()) {

                System.out.println(
                        "Unable to deduce the style, setting it to 'creative'");

                storyRequest.setStyle("creative");
            }

            scope.writeState("topic", storyRequest.getTopic());
            scope.writeState("style", storyRequest.getStyle());

            if (storyRequest.getAudience() != null
                    && !storyRequest.getAudience().isBlank()) {

                scope.writeState("audience", storyRequest.getAudience());
            }

            System.out.println(
                    "Deduced following data : \n" + storyRequest);
        });

   

This is an AgenticScopeAction, not an LLM-based agent. It reads the StoryRequest from the scope, applies default values where necessary, and writes the individual values back into the scope.

 

The scope eventually contains:

 

·      topic: dragons and wizards

·      style: fantasy

·      audience: children

 

If the audience cannot be determined, audience is not written to the scope. That missing state is what allows the optional agent to be skipped.

 

CreativeWriter: Uses the topic from the AgenticScope to generate the initial story and stores it under the story key.

 

CreativeWriter creativeWriter =
        AgenticServices.agentBuilder(CreativeWriter.class)
                .chatModel(chatModel)
                .outputKey("story")
                .build();

The CreativeWriter uses the topic from the AgenticScope to generate the initial story. Its output is stored as story.

 

AudienceEditor: Optional Agent Rewrites the story based on the target audience. It requires the audience argument. If the audience property is not set then this agent step is skipped.

 

This optional step is configured by setting the optional to true at the time of Agent definition.

AudienceEditor audienceEditor =
    AgenticServices.agentBuilder(AudienceEditor.class)
        .chatModel(chatModel)
        .outputKey("story")
        .optional(true)
        .build();

   

This is the key part of the example. The AudienceEditor requires:

 

@V("story")

@V("audience")

 

Normally, if audience is missing, LangChain4j would throw a MissingArgumentException. But because we configured '.optional(true)', the agent is simply skipped when audience is unavailable.

 

If audience exists:

CreativeWriter
      ↓
AudienceEditor
      ↓
StyleEditor

If audience doesn't exist:

CreativeWriter
      ↓
AudienceEditor  → SKIPPED
      ↓
StyleEditor

   

The workflow therefore continues without failure.

 

StyleEditor: Takes the story and the requested style and improves the story accordingly. It runs regardless of whether AudienceEditor was executed.

 

StyleEditor styleEditor =
        AgenticServices.agentBuilder(StyleEditor.class)
                .chatModel(chatModel)
                .outputKey("story")
                .build();

   

The StyleEditor takes the generated story and applies the requested style. For example, style = fantasy. It runs after AudienceEditor, regardless of whether the optional agent was executed or skipped.

 

Build the Sequential Workflow

 

UntypedAgent storyWorkflow =
        AgenticServices.sequenceBuilder()
                .subAgents(
                        storyRequestAnalyzer,
                        extractStoryRequest,
                        creativeWriter,
                        audienceEditor,
                        styleEditor)
                .outputKey("story")
                .build();

   

This defines the execution order:

 

StoryRequestAnalyzer
        ↓
extractStoryRequest
        ↓
CreativeWriter
        ↓
AudienceEditor (optional)
        ↓
StyleEditor

   

The important thing is that the workflow itself doesn't need conditional logic around AudienceEditor. The .optional(true) configuration handles the missing input automatically.

 

Invoke the Workflow

 

ResultWithAgenticScope<String> result =
        storyWorkflow.invokeWithAgenticScope(
                Map.of("request", input));

   

In summary, optional(true) makes an agent tolerant of missing inputs. Instead of failing the entire workflow when audience is unavailable, LangChain4j skips AudienceEditor and continues with StyleEditor.

 

Follow below step-by-step procedure to build the complete working Application.

 

Step 1: Create new maven project ‘optional-agents-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

 

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>

	<groupId>com.sample.app</groupId>
	<artifactId>optional-agents-demo</artifactId>
	<version>1.0.0</version>

	<name>Sequential Handoff Pattern Demo</name>
	<description>
		Simple Java console application demonstrating a Conditional workflow with LangChain4j and Ollama.
	</description>

	<properties>

		<!-- Java -->
		<java.version>21</java.version>
		<maven.compiler.release>${java.version}</maven.compiler.release>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

		<!-- LangChain4j -->
		<langchain4j.version>1.18.1</langchain4j.version>
		<langchain4j.agentic.version>1.18.1-beta28</langchain4j.agentic.version>

		<!-- Logging -->
		<slf4j.version>2.0.17</slf4j.version>

		<!-- Console -->
		<jline.version>3.30.6</jline.version>

		<!-- Application -->
		<main.class>com.sample.app.App</main.class>

		<!-- Maven Plugins -->
		<maven.compiler.plugin.version>3.14.1</maven.compiler.plugin.version>
		<maven.surefire.plugin.version>3.5.4</maven.surefire.plugin.version>
		<maven.shade.plugin.version>3.6.1</maven.shade.plugin.version>
		<spotless.maven.plugin.version>3.4.0</spotless.maven.plugin.version>

	</properties>

	<dependencies>

		<!-- LangChain4j Core -->
		<dependency>
			<groupId>dev.langchain4j</groupId>
			<artifactId>langchain4j-core</artifactId>
			<version>${langchain4j.version}</version>
		</dependency>

		<!-- LangChain4j Ollama Integration -->
		<dependency>
			<groupId>dev.langchain4j</groupId>
			<artifactId>langchain4j-ollama</artifactId>
			<version>${langchain4j.version}</version>
		</dependency>

		<!-- LangChain4j Agentic -->
		<dependency>
			<groupId>dev.langchain4j</groupId>
			<artifactId>langchain4j-agentic</artifactId>
			<version>${langchain4j.agentic.version}</version>
		</dependency>

		<!-- SLF4J -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-nop</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<!-- JLine -->
		<dependency>
			<groupId>org.jline</groupId>
			<artifactId>jline</artifactId>
			<version>${jline.version}</version>
		</dependency>

	</dependencies>

	<build>

		<plugins>

			<!-- Java Compiler -->

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${maven.compiler.plugin.version}</version>
				<configuration>
					<release>${maven.compiler.release}</release>
				</configuration>
			</plugin>

			<!-- Unit Tests -->

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>${maven.surefire.plugin.version}</version>
			</plugin>

			<!-- Build Executable JAR -->

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>${maven.shade.plugin.version}</version>

				<executions>
					<execution>
						<phase>package</phase>

						<goals>
							<goal>shade</goal>
						</goals>

						<configuration>
							<createDependencyReducedPom>false</createDependencyReducedPom>

							<transformers>
								<transformer
									implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
									<mainClass>${main.class}</mainClass>
								</transformer>
							</transformers>
						</configuration>

					</execution>
				</executions>

			</plugin>

			<!-- Code Formatting -->

			<plugin>
				<groupId>com.diffplug.spotless</groupId>
				<artifactId>spotless-maven-plugin</artifactId>
				<version>${spotless.maven.plugin.version}</version>

				<configuration>
					<java>

						<!-- Apply Google Java Format -->
						<googleJavaFormat />

						<!-- General formatting and cleanup -->
						<trimTrailingWhitespace />
						<endWithNewline />
						<removeUnusedImports />

					</java>
				</configuration>

				<executions>
					<execution>
						<id>spotless-check</id>
						<goals>
							<goal>check</goal>
						</goals>
						<phase>verify</phase>
					</execution>
				</executions>

			</plugin>

		</plugins>

	</build>

</project>

   

Step 3: Define StoryRequest model class.

 

StoryRequest.java

 

package com.sample.app.model;

public class StoryRequest {

	private String topic;
	private String style;
	private String audience;

	public String getTopic() {
		return topic;
	}

	public void setTopic(String topic) {
		this.topic = topic;
	}

	public String getStyle() {
		return style;
	}

	public void setStyle(String style) {
		this.style = style;
	}

	public String getAudience() {
		return audience;
	}

	public void setAudience(String audience) {
		this.audience = audience;
	}

	@Override
	public String toString() {
	    return "------- Story Request -------\n" +
	           "Topic: " + topic + "\n" +
	           "Style: " + style + "\n" +
	           "Audience: " + audience + "\n" +
	           "-----------------------------";
	}
	
}

   

Step 4: Define llm config class.

 

OllamaConfig.java

 

package com.sample.app.config;

import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.request.ResponseFormat;
import dev.langchain4j.model.ollama.OllamaChatModel;

public final class OllamaConfig {

  public static final String DEFAULT_BASE_URL = "http://localhost:11434";
  public static final String DEFAULT_MODEL_NAME = "codellama:7b";

  private OllamaConfig() {}

  public static ChatModel createChatModel() {
    String baseUrl = resolveBaseUrl();
    String modelName = resolveModelName();

    return OllamaChatModel.builder().baseUrl(baseUrl).modelName(modelName).temperature(0.2).build();
  }

  public static ChatModel createStructuredChatModel() {
    String baseUrl = resolveBaseUrl();
    String modelName = resolveModelName();

    return OllamaChatModel.builder()
        .baseUrl(baseUrl)
        .modelName(modelName)
        .temperature(0.2)
        .responseFormat(ResponseFormat.JSON)
        .build();
  }

  public static String resolveBaseUrl() {
    return readSetting("OLLAMA_BASE_URL", DEFAULT_BASE_URL);
  }

  public static String resolveModelName() {
    return readSetting("OLLAMA_MODEL", DEFAULT_MODEL_NAME);
  }

  private static String readSetting(String key, String defaultValue) {
    String systemValue = System.getProperty(key);
    if (systemValue != null && !systemValue.trim().isEmpty()) {
      return systemValue.trim();
    }

    String environmentValue = System.getenv(key);
    if (environmentValue != null && !environmentValue.trim().isEmpty()) {
      return environmentValue.trim();
    }

    return defaultValue;
  }
}

   

Step 5: Define Agent interfaces.

 

AudienceEditor.java

 

package com.sample.app.agents;

import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

public interface AudienceEditor {

    @UserMessage("""
        Rewrite the following story so that it is appropriate for the specified audience.

        Story:
        {{story}}

        Target audience:
        {{audience}}
        """)
    @Agent("Edits the story for the target audience")
    String edit(
        @V("story") String story,
        @V("audience") String audience);
}

   

CreativeWriter.java

 

package com.sample.app.agents;

import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

public interface CreativeWriter {

    @UserMessage("""
        Write a short creative story based on the following topic.

        Topic: '{{topic}}'
        """)
    @Agent("Writes a creative story based on the given topic")
    String write(@V("topic") String topic);
}

   

StoryRequestAnalyzer.java

 

package com.sample.app.agents;

import com.sample.app.model.StoryRequest;

import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

public interface StoryRequestAnalyzer {

    @UserMessage("""
            Analyze the following user request and extract information needed
            to create a story.

            Extract:
            - topic: The main subject of the story.
            - style: The desired writing style, such as fantasy, funny,
              adventurous, educational, etc.
            - audience: The intended audience, such as children, adults,
              teenagers, etc.

            If you cannot determine a value from the user request, return
            null for that field.

            Do not guess or invent missing information.

            User request:
            '{{request}}'
            """)
    @Agent("Analyzes the user's story request and extracts topic, style and audience")
    StoryRequest analyze(@V("request") String request);
}

   

StyleEditor.java

 

package com.sample.app.agents;

import dev.langchain4j.agentic.Agent;
import dev.langchain4j.service.UserMessage;
import dev.langchain4j.service.V;

public interface StyleEditor {

    @UserMessage("""
        Improve the writing style of the following story.

        Story:
        {{story}}

        Desired style:
        {{style}}

        Return only the improved story.
        """)
    @Agent("Improves the story according to the requested style")
    String edit(
        @V("story") String story,
        @V("style") String style);
}

   

Step 6: Define main Application class.

App.java

 

package com.sample.app;

import java.util.Map;
import java.util.Scanner;

import com.sample.app.agents.AudienceEditor;
import com.sample.app.agents.CreativeWriter;
import com.sample.app.agents.StoryRequestAnalyzer;
import com.sample.app.agents.StyleEditor;
import com.sample.app.config.OllamaConfig;
import com.sample.app.model.StoryRequest;

import dev.langchain4j.agentic.AgenticServices;
import dev.langchain4j.agentic.AgenticServices.AgenticScopeAction;
import dev.langchain4j.agentic.UntypedAgent;
import dev.langchain4j.agentic.scope.ResultWithAgenticScope;
import dev.langchain4j.model.chat.ChatModel;

public class App {

    private static String readInput(Scanner scanner) {
        System.out.print("> ");
        String input = scanner.nextLine().trim();

        return "exit".equalsIgnoreCase(input) ? null : input;
    }

    public static void main(String[] args) {
        ChatModel chatModel = OllamaConfig.createChatModel();

        StoryRequestAnalyzer storyRequestAnalyzer = AgenticServices.agentBuilder(StoryRequestAnalyzer.class)
                .chatModel(chatModel).outputKey("storyRequest").build();

        AgenticScopeAction extractStoryRequest = AgenticServices.agentAction(scope -> {

            StoryRequest storyRequest = (StoryRequest) scope.readState("storyRequest");

            if (storyRequest.getTopic() == null || storyRequest.getTopic().isBlank()) {
                System.out.println("Unable to deduce the topic, setting to 'Any Interesting Topic'");
                storyRequest.setTopic("Any Interesting Topic");
            }

            if (storyRequest.getStyle() == null || storyRequest.getStyle().isBlank()) {
                System.out.println("Unable to deduce the style, setting it to 'creative'");
                storyRequest.setStyle("creative");
            }
            
            scope.writeState("topic", storyRequest.getTopic());
            scope.writeState("style", storyRequest.getStyle());

            if (storyRequest.getAudience() != null && !storyRequest.getAudience().isBlank()) {

                scope.writeState("audience", storyRequest.getAudience());
            }
            
            System.out.println("Deduced following data : \n" + storyRequest);
        });

        CreativeWriter creativeWriter = AgenticServices.agentBuilder(CreativeWriter.class).chatModel(chatModel)
                .outputKey("story").build();

        AudienceEditor audienceEditor = AgenticServices.agentBuilder(AudienceEditor.class).chatModel(chatModel)
                .outputKey("story").optional(true).build();

        StyleEditor styleEditor = AgenticServices.agentBuilder(StyleEditor.class).chatModel(chatModel)
                .outputKey("story").build();

        UntypedAgent storyWorkflow = AgenticServices.sequenceBuilder()
                .subAgents(storyRequestAnalyzer, extractStoryRequest, creativeWriter, audienceEditor, styleEditor)
                .outputKey("story").build();

        try (Scanner scanner = new Scanner(System.in)) {
            while (true) {
                String input = readInput(scanner);

                if ("exit".equalsIgnoreCase(input)) {
                    System.exit(0);
                }

                ResultWithAgenticScope<String> result = storyWorkflow.invokeWithAgenticScope(Map.of("request", input));
                System.out.println(result.result());
            }
        }

    }
}

   

Build the application using Maven:

Navigate to the project where pom.xml is located and execute below command.

 

mvn clean package

Run the generated executable JAR:

Execute below command to run the Application.

java -jar ./target/optional-agents-demo-1.0.0.jar

$ java -jar ./target/optional-agents-demo-1.0.0.jar 
> Tell me a story
Unable to deduce the topic, setting to 'Any Interesting Topic'
Unable to deduce the style, setting it to 'creative'
Deduced following data : 
------- Story Request -------
Topic: Any Interesting Topic
Style: creative
Audience: null
-----------------------------

Once upon a time, there was a young girl named Maria. She lived in a small village surrounded by lush green forests and sparkling rivers. Maria was a curious and adventurous girl, always eager to explore the world around her.

...............
...............

   

You can download the Application from this link.



Previous                                                    Next                                                    Home

No comments:

Post a Comment