Agentic AI

The Agentic module provides abstractions for building AI systems that coordinate multiple agents. These systems go beyond simple single-model interactions, enabling complex workflows where multiple specialized agents collaborate to solve problems.

Overview

Agentic systems are built around the idea of composing multiple specialized agents into higher-level workflows. Each agent performs a specific task, like generating content, classifying input, scoring quality, and the agentic system orchestrates their execution.

The module distinguishes between two categories of agentic systems:

  • Workflows: deterministic orchestration patterns where the execution order is defined at design time (sequence, loop, parallel, conditional).

  • Pure Agents: LLM-driven orchestration where the model dynamically decides which agents to invoke (supervisor, planner).

You do NOT implement the agentic methods yourself. An agent is a CDI bean class whose agentic method is native, or an interface. Quarkus LangChain4j detects the agents at build time, validates their configuration, implements their agentic methods and registers them as CDI beans.

Getting started

Add the following dependency to your project:

<dependency>
    <groupId>io.quarkiverse.langchain4j</groupId>
    <artifactId>quarkus-langchain4j-agentic</artifactId>
</dependency>

Core Concepts

Agents

An agent is a CDI bean class with a method annotated with @Agent, declared native because the extension implements it. The method defines the agent’s task, typically via an LLM prompt using @UserMessage.

@ApplicationScoped
public class CreativeWriter {

    @UserMessage("""
            You are a creative writer.
            Generate a draft of a story long no more than 3 sentence around the given topic.
            Return only the story and nothing else.
            The topic is {{topic}}.
            """)
    @Agent(description = "Generate a story based on the given topic", outputKey = "story")
    public native String generateStory(String topic);
}

The agent is an ordinary bean: it can inject other beans, declare a scope and bind interceptors, see Agents as CDI Beans. An agent can also be declared as an interface with the same annotations, the form shared with plain LangChain4j, see Agent Interfaces and Static Helpers:

public interface CreativeWriter {

    @UserMessage("...")
    @Agent(description = "Generate a story based on the given topic", outputKey = "story")
    String generateStory(String topic);
}

@Agent attributes:

Attribute Description Default

value / description

Describes what the agent does. Essential for supervisor patterns where the LLM picks which agent to invoke.

Empty

outputKey

The key under which the agent’s return value is stored in the AgenticScope.

Empty

name

Unique identifier for the agent within a workflow.

The method name

AgenticScope

The AgenticScope is essentially a shared state through which agents exchange data. Each agent reads its inputs from the scope (matched by the names of the arguments of the agentic method, that can be overwritten through the LangChain4j @V annotation) and writes its output under its outputKey.

For example, when CreativeWriter completes, its return value is stored in the scope under the key "story". A subsequent AudienceEditor agent can then read that value by declaring a parameter String story.

Inject and Use

Agent classes without a scope annotation, and agent interfaces, are registered as @ApplicationScoped CDI beans. Simply inject them:

@Inject
CreativeWriter writer;

String story = writer.generateStory("dragons and wizards");

Defining Agents

AI Agents

AI Agents are classes or interfaces whose agentic method is backed by an LLM. They combine @Agent with prompt annotations like @UserMessage and @SystemMessage.

@ApplicationScoped
public class MedicalExpert {

    @UserMessage("""
            You are a medical expert.
            Analyze the following user request under a medical point of view
            and provide the best possible answer.
            The user request is {{request}}.
            """)
    @Agent(description = "A medical expert", outputKey = "response")
    public native String medical(String request);
}

Non-AI Agents

Plain Java code (not backed by an LLM) can participate in agent workflows. A non-AI agent is a bean with an instance method annotated with @Agent, with a body:

@ApplicationScoped
public class OrderLookup {

    @Inject
    OrderService orders;

    @Agent(description = "Find the status of an order", outputKey = "orderStatus")
    public String status(@V("orderId") String orderId) {
        return orders.statusOf(orderId);
    }
}

The method is invoked on the bean, through its client proxy, so its interceptor bindings apply. A class with such a method and no scope annotation is registered as an @ApplicationScoped bean when it can be one: concrete, non-final, with a no-arg constructor. Any other class, like a final class, a record or a class with constructor parameters, stays a plain class, whose instances the application passes to a programmatic builder, as in plain LangChain4j. A non-AI agent can also be a plain class with a static method annotated with @Agent, as in plain LangChain4j:

public class PlainProcessListAgent {

    @Agent(description = "Get first item from a list", outputKey = "output")
    public static String getFirst(List<String> aList) {
        return aList.get(0);
    }
}

The static method can also use CDI beans, see Using CDI Beans in Static Agent Methods.

A2A and MCP Client Agents

An agent can also be a remote one: @A2AClientAgent declares an agent executed by a remote A2A agent, and @McpClientAgent an agent that calls a tool of an MCP server. They need the langchain4j-agentic-a2a and the langchain4j-agentic-mcp library respectively:

<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-agentic-a2a</artifactId>
</dependency>
<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-agentic-mcp</artifactId>
</dependency>
public interface RemoteWriter {

    @A2AClientAgent(a2aServerUrl = "http://localhost:8080", description = "Writes a story", outputKey = "story")
    String writeStory(@V("topic") String topic);
}

public interface WeatherAgent {

    @McpClientAgent(toolName = "getWeatherForecast", description = "Fetches the weather forecast", outputKey = "weather")
    String fetchWeather(@V("destination") String destination);

    @McpClientSupplier
    static McpClient mcpClient(@McpClientName("weather") McpClient mcpClient) {
        return mcpClient;
    }
}

The @McpClientSupplier method provides the MCP client, here one configured with the MCP extension and received as a CDI parameter, see Using CDI Beans in Static Agent Methods.

A remote agent is declared as an interface: LangChain4j implements it with a proxy of the interface, so @A2AClientAgent or @McpClientAgent on a method of a class fails the build.

The remote agent and the MCP server are contacted when the agent is first invoked, and not when the application starts, so they don’t have to be available then:

  • the agent card of an A2A agent is fetched at its first invocation, within 30 seconds. resolutionTimeoutSeconds on @A2AClientAgent changes this limit, and 0 removes it

  • the @McpClientSupplier method runs, and the tools of the MCP server are listed, at the first invocation of an MCP client agent. This has no time limit of its own: the timeouts of the MCP client apply, like its initialization-timeout. resolutionTimeoutSeconds on @McpClientAgent adds a limit, and the lower one wins

  • when the remote agent or the MCP server doesn’t answer, or not in time, the invocation fails with an exception caused by an A2AAgentCardException or by an McpToolResolutionException, and the next invocation tries again. Both are AgentUnavailableException`s, which an `@ErrorHandler can look for among the causes of the failure to skip the agent

  • the fetch of the agent card, and the @McpClientSupplier method of an agent with a resolution timeout, run on another thread, where no request context is active

Agents as CDI Beans

An agent class is a CDI bean, and the kind of agent is decided by its agentic method:

Agentic method Agent Bean

native, annotated with @Agent, a workflow annotation, @SupervisorAgent, @PlannerAgent or @Decide

AI, decision, workflow, supervisor or planner agent, implemented by the extension

Yes

Instance method with a body, annotated with @Agent or @HumanInTheLoop

Non-AI or human-in-the-loop agent, invoked on the bean

Yes

static method with a body, annotated with @Agent or @HumanInTheLoop

Non-AI or human-in-the-loop agent, invoked statically

No, a plain class

Abstract method of an interface

Any agent, implemented by the extension

Yes, a synthetic bean

A class declares exactly one agentic method. The other native methods of an AI agent class, declared by the class or inherited from a superclass, are AI service methods, like the other abstract methods of an agent interface.

An agent class can implement MonitoredAgent: it declares agentMonitor() as a native method, which the extension implements like the agentic one. A workflow class can implement AgenticScopeAccess in the same way, declaring its methods native.

Bean Rules

  • A scope annotation is optional: without one, the class is an @ApplicationScoped bean. Any normal scope is accepted, like @RequestScoped or a custom scope, and so is @Singleton, which behaves like @ApplicationScoped. @Dependent is rejected, because the helper methods are invoked on the bean instance of the current context.

  • The class must be concrete and non-final, with a no-arg constructor, the agentic method must be neither private, static nor final, and the instance helper methods neither private nor final: the bean is invoked through a client proxy. An abstract class fails the build: make it concrete and declare the agentic method native.

  • The no-arg constructor runs for the bean and for the subclasses the extension generates to implement the agent, so it must be cheap and free of side effects. Keep the state in injected fields or initialize it in a @PostConstruct method.

  • Interceptor bindings on the class, on the agentic method and on the helper methods apply, because every method is invoked through the client proxy, also when a workflow invokes the agent as a sub-agent.

Helper Methods

Every helper annotation of the declarative API is accepted on an instance method of the agent class, which can be package-private: the suppliers like @ChatModelSupplier, @ToolsSupplier or @ChatMemoryProviderSupplier, and @ExitCondition, @ActivationCondition, @Output, @BeforeCall, @ErrorHandler, @SupervisorRequest, @ParallelExecutor, @DecisionModelSupplier and @DecisionThresholdSupplier. The method takes the same parameters as the static form: values from the AgenticScope, the parameters provided by the framework, like the AgenticScope or the ErrorContext, and CDI beans annotated with @CdiBean or a qualifier, which remain allowed but are unnecessary, since the bean injects them.

@RequestScoped
public class StoryReview {

    @Inject
    ReviewSettings settings;

    @Inject
    StoryRepository repository;

    @LoopAgent(outputKey = "story", maxIterations = 5, subAgents = { StyleScorer.class, StyleEditor.class })
    public native String review(@V("story") String story);

    @ExitCondition
    boolean done(@V("score") double score) {
        return score >= settings.minimumScore();
    }

    @Output
    @Transactional
    String save(@V("story") String story) {
        repository.save(story);
        return story;
    }
}

The helper methods are found on the class and on its superclasses. A static and an instance method annotated with the same helper annotation on one agent fail the build.

The model of an agent is chosen with @ModelName on the agentic method or with a @ChatModelSupplier method: an injected ChatModel field is an ordinary injection that never selects the model of the agent.

Scoped Agents

For an agent with a scope other than the application scope, like @RequestScoped, each bean instance has its own AgenticScope, created on the first invocation of the instance. The chat memories that the agents of the system create during the invocations of the instance, like the ones of the AI sub-agents with a @ChatMemoryProviderSupplier and no @MemoryId parameter, default to the memory id of the instance. When the instance is destroyed, at the end of the request for a @RequestScoped agent, its AgenticScope is evicted and those chat memories are deleted, with the messages they stored: the memory id of the instance is never used again. A @MemoryId parameter keeps its explicit meaning.

The same applies to an agent interface annotated with a scope. The @ApplicationScoped agents, the default, keep an ephemeral AgenticScope per invocation unless a @MemoryId is given, and so do the @Singleton ones: their single instance is shared by every caller too, so it has no AgenticScope of its own.

The agentic scope of a bean instance is bound to the thread invoking it. The parallel and asynchronous agents run on the executor of the extension, which propagates the request context, so a @RequestScoped bean is available to them too. The executor that a workflow provides with @ParallelExecutor propagates the request context only if the application makes it do so.

Composing Agents with AI Service Annotations

An AI agent class or interface can be annotated with @RegisterAiService, and its attributes, like tools, chatMemoryProviderSupplier or retrievalAugmentor, configure the AI service implementing the agent, together with @ToolBox, @McpToolBox, @Skills, the guardrails and @ModelName:

@RegisterAiService(tools = StyleTools.class)
public class StyleScorer {

    @Inject
    ScoringRules rules;

    @UserMessage("Score the style of {{story}}")
    @Agent(outputKey = "score")
    @ModelName("scoring")
    public native double score(@V("story") String story);

    @ActivationCondition
    boolean enabled(@V("story") String story) {
        return rules.applies(story);
    }
}

A @RegisterAiService attribute configuring the same feature as an agentic supplier method on the same type fails the build: for instance tools together with @ToolsSupplier, chatMemoryProviderSupplier together with @ChatMemoryProviderSupplier, or modelName together with @ChatModelSupplier. The default scope of an agent stays @ApplicationScoped, also with @RegisterAiService.

A class annotated with @RegisterAiService whose native methods carry no agent annotation is a plain AI service in its class form, see AI Services as Classes: it is not an agent, and it cannot be a sub-agent.

Workflow Patterns

Sequential Workflow

The @SequenceAgent annotation invokes sub-agents one after another. Each agent receives the outputs of all prior agents via the AgenticScope.

@ApplicationScoped
public class StoryCreator {

    @SequenceAgent(
            outputKey = "story",
            subAgents = { CreativeWriter.class, AudienceEditor.class, StyleEditor.class })
    public native String write(String topic, String style, String audience);
}

In this example, CreativeWriter generates a story and stores it under the key "story". Then AudienceEditor reads "story" and "audience" from the scope, rewrites the story, and stores the result back under "story". Finally, StyleEditor reads the updated "story" and "style", and produces the final version.

Inject and use the workflow:

@Inject
StoryCreator storyCreator;

String story = storyCreator.write("dragons and wizards", "fantasy", "young adults");

Loop Workflow

The @LoopAgent annotation repeatedly invokes sub-agents until an exit condition is met or maxIterations is reached.

@ApplicationScoped
public class StyleReviewLoopAgent {

    @Inject
    ReviewSettings settings;

    @LoopAgent(
            description = "Review the given story to ensure it aligns with the specified style",
            outputKey = "story",
            maxIterations = 5,
            subAgents = { StyleScorer.class, StyleEditor.class })
    public native String write(String story);

    @ExitCondition
    boolean exit(double score) {
        return score >= settings.minimumScore();
    }
}

At each iteration, StyleScorer scores the story and stores the result under "score". Then StyleEditor rewrites the story. The loop exits when the @ExitCondition method returns true or after 5 iterations.

@ExitCondition rules:

  • An instance method of the agent class, or a static method of the agent interface

  • Must return boolean

  • Parameters are resolved from the AgenticScope

Composing Sequence and Loop

Workflows can be composed by nesting them. For example, a sequence that first generates a story, then runs a review loop:

@ApplicationScoped
public class StoryCreatorWithReview {

    @SequenceAgent(
            outputKey = "story",
            subAgents = { CreativeWriter.class, StyleReviewLoopAgent.class })
    public native String write(String topic, String style);
}
@Inject
StoryCreatorWithReview storyCreatorWithReview;

String story = storyCreatorWithReview.write("dragons and wizards", "comedy");

Parallel Workflow

The @ParallelAgent annotation executes multiple independent agents simultaneously.

public interface FoodExpert {

    @UserMessage("""
            You are a great evening planner.
            Propose a list of 3 meals matching the given mood.
            The mood is {{mood}}.
            For each meal, just give the name of the meal.
            Provide a list with the 3 items and nothing else.
            """)
    @Agent(outputKey = "meals")
    List<String> findMeal(String mood);
}

public interface MovieExpert {

    @UserMessage("""
            You are a great evening planner.
            Propose a list of 3 movies matching the given mood.
            The mood is {{mood}}.
            Provide a list with the 3 items and nothing else.
            """)
    @Agent(outputKey = "movies")
    List<String> findMovie(String mood);
}

public record EveningPlan(String movie, String meal) {
}

public interface EveningPlannerAgent {

    @ParallelAgent(
            outputKey = "plans",
            subAgents = { FoodExpert.class, MovieExpert.class })
    List<EveningPlan> plan(String mood);

    @Output
    static List<EveningPlan> createPlans(List<String> movies, List<String> meals) {
        List<EveningPlan> moviesAndMeals = new ArrayList<>();
        for (int i = 0; i < movies.size(); i++) {
            if (i >= meals.size()) {
                break;
            }
            moviesAndMeals.add(new EveningPlan(movies.get(i), meals.get(i)));
        }
        return moviesAndMeals;
    }
}

Both FoodExpert and MovieExpert run at the same time. Their results are stored under "meals" and "movies" respectively. Then the @Output method createPlans combines those results into a list of EveningPlan.

Parallel Mapper

The @ParallelMapperAgent annotation maps a single sub-agent over a collection of items, executing each invocation in parallel:

public record Person(String name, String sign) {
}

public interface PersonAstrologyAgent {

    @UserMessage("""
            Generate the horoscope for {{person}}.
            The person has a name and a zodiac sign.
            Use both to create a personalized horoscope.
            """)
    @Agent(description = "An astrologist that generates horoscopes for a person", outputKey = "horoscope")
    String horoscope(Person person);
}

public interface BatchHoroscopeAgent {

    @ParallelMapperAgent(subAgent = PersonAstrologyAgent.class)
    List<String> generateHoroscopes(List<Person> persons);
}

Each Person in the list is passed to a separate invocation of PersonAstrologyAgent, all running in parallel.

Asynchronous Agents

An agent declared with async = true runs on another thread, and the workflow waits for it only where its result is read: by a later agent taking its output key as an argument, or by the output key or the @Output method of the workflow. A workflow does not wait for an asynchronous agent whose result nobody reads: it returns while that agent is still running. A slow last step, like a fix that takes minutes or a notification, can then run on its own while the workflow returns its result as soon as it is known:

public interface Remediation {

    @UserMessage("Apply the fix required by this decision: {{decision}}")
    @Agent(description = "Applies the fix required by a decision", outputKey = "fix", async = true)
    String remediate(@V("decision") String decision);
}

public interface RolloutAnalysis {

    @SequenceAgent(outputKey = "decision", subAgents = { RolloutAnalyst.class, Remediation.class })
    String analyze(@V("rollout") String rollout);
}

@ApplicationScoped
public class RemediationListener implements AgentListener {

    @Override
    public void afterAgentInvocation(AgentResponse response) {
        if (response.agentName().equals("remediate")) {
            Log.infof("Fix applied: %s", response.output());
        }
    }

    @Override
    public void onAgentInvocationError(AgentInvocationError error) {
        if (error.agentName().equals("remediate")) {
            Log.error("Fix failed", error.error());
        }
    }
}

analyze returns the decision while remediate is still running, since no agent reads fix. For such an agent:

  • the result and the failure are notified to the listeners of the agent, with afterAgentInvocation and onAgentInvocationError. They include the AgentListener beans, see Listeners, Monitoring and Dev UI. They are notified on the thread of the agent, possibly after the request that invoked the workflow has returned, so these beans must be @ApplicationScoped and can’t use the request, the security identity or a @RequestScoped bean

  • the result is also written to the AgenticScope under the output key of the agent, where a later invocation with the same memory id can read it

  • a failure is handled by the @ErrorHandler of the workflow, but its caller has already received a successful result: it gets no exception, and no compensation runs

  • the work in progress is lost when the application shuts down

  • a later invocation with the same memory id waits for the agent before it starts, so an endpoint invoking the same memory id repeatedly can block on the side task of the previous invocation

To tell whether an invocation waited for an asynchronous agent, enable the DEBUG level of the category below: at the end of an invocation it logs the output keys of the asynchronous agents still running.

quarkus.log.category."dev.langchain4j.agentic.scope.DefaultAgenticScope".level=DEBUG

Conditional Workflow

The @ConditionalAgent annotation routes execution to different sub-agents based on conditions evaluated against the AgenticScope.

@ApplicationScoped
public class ExpertsAgent {

    @ConditionalAgent(
            outputKey = "response",
            subAgents = { MedicalExpert.class, TechnicalExpert.class, LegalExpert.class })
    public native String askExpert(String request);

    @ActivationCondition(MedicalExpert.class)
    boolean activateMedical(RequestCategory category) {
        return category == RequestCategory.MEDICAL;
    }

    @ActivationCondition(TechnicalExpert.class)
    boolean activateTechnical(RequestCategory category) {
        return category == RequestCategory.TECHNICAL;
    }

    @ActivationCondition(LegalExpert.class)
    boolean activateLegal(RequestCategory category) {
        return category == RequestCategory.LEGAL;
    }
}

Each sub-agent is guarded by an @ActivationCondition method. Only the agent whose condition returns true is invoked.

@ActivationCondition rules:

  • An instance method of the agent class, or a static method of the agent interface

  • Must return boolean

  • Takes the Class of the sub-agent it guards as the annotation value

  • Parameters are resolved from the AgenticScope

Router Pattern

A common pattern is to compose a classifier agent with a conditional agent in a sequence:

@ApplicationScoped
public class CategoryRouter {

    @UserMessage("""
            Analyze the following user request and categorize it as 'legal', 'medical' or 'technical'.
            In case the request doesn't belong to any of those categories categorize it as 'unknown'.
            Reply with only one of those words and nothing else.
            The user request is: '{{request}}'.
            """)
    @Agent(description = "Categorize a user request", outputKey = "category")
    public native RequestCategory classify(String request);
}

@ApplicationScoped
public class ExpertRouterAgent {

    @SequenceAgent(
            outputKey = "response",
            subAgents = { CategoryRouter.class, ExpertsAgent.class })
    public native ResultWithAgenticScope<String> ask(String request);
}

The CategoryRouter classifies the request and writes the "category" to the scope. The ExpertsAgent then conditionally routes to the matching expert based on that category.

@Inject
ExpertRouterAgent expertRouterAgent;

ResultWithAgenticScope<String> result = expertRouterAgent.ask("I broke my leg what should I do");
RequestCategory category = result.agenticScope().readState("category"); // MEDICAL
String response = result.result();

Pure Agentic Patterns

Supervisor Agent

The @SupervisorAgent uses an LLM to dynamically decide which sub-agents to invoke. Sub-agents are described to the LLM via their @Agent(description = "…​").

public interface WithdrawAgent {

    @SystemMessage("You are a banker that can only withdraw US dollars (USD) from a user account.")
    @UserMessage("Withdraw {{amountInUSD}} USD from {{withdrawUser}}'s account and return the new balance.")
    @Agent("A banker that withdraw USD from an account")
    String withdraw(String withdrawUser, Double amountInUSD);
}

public interface CreditAgent {

    @SystemMessage("You are a banker that can only credit US dollars (USD) to a user account.")
    @UserMessage("Credit {{amountInUSD}} USD to {{creditUser}}'s account and return the new balance.")
    @Agent("A banker that credit USD to an account")
    String credit(String creditUser, Double amountInUSD);
}

public interface ExchangeAgent {

    @UserMessage("""
            You are an operator exchanging money in different currencies.
            Use the tool to exchange {{amount}} {{originalCurrency}} into {{targetCurrency}}
            returning only the final amount provided by the tool as it is and nothing else.
            """)
    @Agent(outputKey = "exchange",
            description = "A money exchanger that converts a given amount of money from the original to the target currency")
    Double exchange(String originalCurrency, Double amount, String targetCurrency);
}

public interface SupervisorBanker {

    @SupervisorAgent(
            responseStrategy = SupervisorResponseStrategy.SUMMARY,
            subAgents = { WithdrawAgent.class, CreditAgent.class, ExchangeAgent.class })
    String invoke(String request);
}

The supervisor LLM reads the descriptions of the sub-agents and decides which ones to call and in what order to fulfill the user request.

Response strategies:

Strategy Description

LAST

Returns the last sub-agent’s output (default).

SUMMARY

The supervisor LLM summarizes all sub-agent outputs.

Custom Supervisor Prompt

Use @SupervisorRequest to customize the prompt sent to the supervisor LLM:

@ApplicationScoped
public class SupervisorStoryCreator {

    @Inject
    PromptCatalog prompts;

    @SupervisorAgent(
            outputKey = "story",
            responseStrategy = SupervisorResponseStrategy.LAST,
            subAgents = { CreativeWriter.class, StyleReviewLoopAgent.class })
    public native ResultWithAgenticScope<String> write(@V("topic") String topic, @V("style") String style);

    @SupervisorRequest
    String request(String topic, String style) {
        return prompts.supervisorRequest(topic, style);
    }
}

The model calls that a supervisor makes to plan its work are notified to its AgentListener`s with `onPlannerModelResponse, which gives the token usage and the model name of each call. The Executions page of the Dev UI shows their tokens on the row of the supervisor, separately from the ones of its sub-agents.

Planner Agent

The @PlannerAgent annotation uses a custom Planner implementation for orchestration logic. This enables advanced patterns like goal-oriented planning and peer-to-peer agent coordination.

public interface MyPlannerAgent {

    @PlannerAgent(
            outputKey = "result",
            subAgents = { AgentA.class, AgentB.class, AgentC.class })
    String plan(String input);

    @PlannerSupplier
    static Planner planner() {
        return new MyPlanner();
    }
}

A planner agent doesn’t use a chat model itself, so an agentic system made of planners and agents that don’t use one, like non-AI agents or decision agents, needs no chat model. A Planner that uses a model receives it as a parameter of the @PlannerSupplier method, see Using CDI Beans in Static Agent Methods:

@PlannerSupplier
static Planner planner(@ModelName("planning") ChatModel chatModel) {
    return new MyLlmPlanner(chatModel);
}

Such a Planner reports each response of its model with planningContext.reportChatModelResponse(…​) or planningContext.reportDecisionModelResponse(…​), from firstAction or nextAction and not from init. The responses are then notified to the listeners and counted in the Executions page like the planning calls of a supervisor. A planner that calls an AI service reports from an AiServiceResponseReceivedListener registered on that service.

Accessing AgenticScope

From the Return Value

Wrap the return type in ResultWithAgenticScope<T> to get both the result and the full scope:

public interface StoryCreatorWithReview {

    @SequenceAgent(
            outputKey = "story",
            subAgents = { CreativeWriter.class, StyleReviewLoopAgent.class })
    ResultWithAgenticScope<String> write(String topic, String style);
}
ResultWithAgenticScope<String> result = storyCreator.write("dragons", "comedy");
String story = result.result();
AgenticScope scope = result.agenticScope();
String topic = scope.readState("topic");
double score = scope.readState("score", 0.0);

From the Interface

Extend AgenticScopeAccess to get scope access methods directly on the agent interface:

public interface StyledWriter extends AgenticScopeAccess {

    @Agent
    ResultWithAgenticScope<String> writeStoryWithStyle(String topic, String style);
}

Memory IDs

Use @MemoryId for per-conversation isolation:

public interface MedicalExpertWithMemory {

    @UserMessage("""
            You are a medical expert.
            Analyze the following user request under a medical point of view
            and provide the best possible answer.
            The user request is {{request}}.
            """)
    @Agent(description = "A medical expert", outputKey = "response")
    String medical(@MemoryId String memoryId, String request);
}

Error Handling

Define an error recovery strategy with an @ErrorHandler method on the root agent of an agentic system, the workflow, supervisor or planner agent that the application invokes:

public interface StoryCreatorWithErrorRecovery extends StoryCreator {

    @ErrorHandler
    static ErrorRecoveryResult errorHandler(ErrorContext errorContext) {
        if (errorContext.agentName().equals("generateStory")
                && errorContext.exception() instanceof MissingArgumentException mEx
                && mEx.argumentName().equals("topic")) {
            errorContext.agenticScope().writeState("topic", "dragons and wizards");
            return ErrorRecoveryResult.retry();
        }
        return ErrorRecoveryResult.throwException();
    }
}

The handler of the root agent receives the failures of every agent of the system, at any level of nesting, and ErrorContext.agentName() tells which agent failed. The @ErrorHandler method of an agent is not invoked when the agent runs as a sub-agent of another one: the build logs a warning for such a method.

@ErrorHandler rules:

  • An instance method of the agent class, or a static method of the agent interface

  • Must take ErrorContext as parameter

  • Must return ErrorRecoveryResult

Recovery options:

Method Description

ErrorRecoveryResult.throwException()

Propagates the error (default behavior).

ErrorRecoveryResult.retry()

Retries the failed agent after corrective actions (e.g., writing missing values to the scope).

ErrorRecoveryResult.result(Object)

Returns a fallback value, skipping the failed agent.

Human-in-the-Loop

The @HumanInTheLoop annotation pauses workflow execution to wait for human input. The method is an instance method of a bean, invoked on the bean, or a static method of an interface or class:

@ApplicationScoped
public class AudienceRetriever {

    @Inject
    PendingResponses pendingResponses;

    @HumanInTheLoop(
            description = "Ask for audience preference",
            outputKey = "audience",
            async = true)
    public String humanResponse(AgenticScope scope, String topic) {
        CompletableFuture<String> futureResult = new CompletableFuture<>();
        pendingResponses.register(scope.memoryId(), futureResult);
        try {
            return futureResult.get();
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}

The optional async = true flag, used in this example, allows running this in a separate thread so the workflow engine is not blocked while waiting for the human response. Another agent or external trigger completes the CompletableFuture to resume execution. The workflow waits for the human response only where a later agent reads audience, see Asynchronous Agents.

A human-in-the-loop agent doesn’t use a chat model. This agent can be composed in a sequential workflow with other agents:

@ApplicationScoped
public class StoryCreatorWithHumanInTheLoop {

    @SequenceAgent(outputKey = "story", subAgents = {
            AudienceRetriever.class,
            CreativeWriter.class,
            AudienceEditor.class })
    public native String write(String topic);
}

Configuring the Chat Model

Default Model

By default, agents use the CDI ChatModel bean configured via application properties (e.g., quarkus.langchain4j.openai.api-key).

Only the AI agents and the supervisor agents use a chat model. Workflows, planner, human-in-the-loop, decision, non-AI and remote agents don’t, so an application without AI or supervisor agents needs no chat model.

Per-Agent Model with @ChatModelSupplier

Use @ChatModelSupplier on a helper method, an instance method of the agent class or a static method of the agent interface, to provide a specific ChatModel for an agent:

public interface CategoryRouter {

    @UserMessage("Categorize as 'legal', 'medical' or 'technical': '{{request}}'")
    @Agent(description = "Categorize a user request", outputKey = "category")
    RequestCategory classify(@V("request") String request);

    @ChatModelSupplier
    static ChatModel chatModel() {
        return OpenAiChatModel.builder()
                .apiKey("...")
                .modelName("gpt-4o")
                .build();
    }
}

Named Models with @ModelName

Use @ModelName to select a named model configuration, exactly like with AI Services:

public interface NamedModelAgent {

    @UserMessage("Answer the following question: {{question}}")
    @Agent(value = "An agent using a named model", outputKey = "answer")
    @ModelName("mymodel")
    String answer(@V("question") String question);
}

Configure the named model in application.properties:

quarkus.langchain4j.mymodel.chat-model.provider=openai
quarkus.langchain4j.openai.mymodel.api-key=sk-...

Dynamic Model Selection with @ChatModelSupplier

The @ChatModelSupplier method can also accept parameters, enabling dynamic model selection based on the current agent execution state. Parameters are resolved from the AgenticScope, meaning they can receive outputs produced by previously executed agents in the workflow. This allows an agent to pick a different ChatModel at runtime depending on the results of earlier steps.

public interface DynamicModelAgent {

    @UserMessage("Answer the following question: {{text}}")
    @Agent(value = "An agent using a dynamic model selection", outputKey = "answer")
    String answer(String text);

    @ChatModelSupplier
    static ChatModel chatModel(Double threshold) {
        return threshold > 0.5 ? baseModel() : enhancedModel();
    }
}

Here the threshold parameter is resolved from the AgenticScope and the ChatModel to be used for the current invocation is selected based on its value. The method can also receive CDI beans, for instance a @ModelName qualified ChatModel, see Using CDI Beans in Static Agent Methods.

This is particularly useful when:

  • Different inputs require models with different capabilities or cost profiles (e.g., using a cheaper model for simple requests and a more powerful one for complex ones).

  • The model selection depends on the outcome of a prior classification or routing step.

Decision Agents

A decision agent answers questions about its arguments with a decision model instead of a chat model. Its implementation is a single call to a DecisionModel, which returns typed answers and their probabilities rather than generated text. That makes it cheaper and faster than an AI agent, and a natural fit for the routing, gating and classification steps of an agentic system.

Decision agents and the DecisionModel API are experimental in LangChain4j and may change in future releases.

Declaring a Decision Agent

A decision agent is an interface whose @Agent method is annotated with @Decide, which contains the question:

public interface SpamGate {

    @Decide("Is this message spam?")
    @Agent(description = "Detects spam", outputKey = "spam")
    boolean isSpam(@V("message") String message);
}

Like the arguments of any agent, the arguments of the method are read from the AgenticScope by name. They are sent to the decision model as the input of the decision, objects being converted to maps. The answer is written as it is to the output key, so that the activation and exit conditions and the agents that follow can read it:

public enum Team {
    @Description("Payments, payouts, invoices and refunds")
    BILLING,
    @Description("Problems using the product")
    SUPPORT
}

public interface TeamRouter {

    @Decide("Which team should handle this request?")
    @Agent(description = "Routes a request to a team", outputKey = "team")
    Team route(@V("request") String request);
}

public interface HelpDesk {

    @SequenceAgent(outputKey = "answer", subAgents = { TeamRouter.class, Desks.class })
    String handle(@V("request") String request);
}

public interface Desks {

    @ConditionalAgent(outputKey = "answer", subAgents = { BillingExpert.class, SupportExpert.class })
    String answer(@V("request") String request);

    @ActivationCondition(BillingExpert.class)
    static boolean billing(@V("team") Team team) {
        return team == Team.BILLING;
    }

    @ActivationCondition(SupportExpert.class)
    static boolean support(@V("team") Team team) {
        return team == Team.SUPPORT;
    }
}

The return type of the method determines the questions asked:

  • boolean: a yes/no question, answered true when the probability of "yes" reaches the threshold, see Thresholds

  • YesNoAnswer: a yes/no question, answered with the probability of "yes"

  • an enum: a choice among its constants, described to the model by their @Description, if any

  • Choice<E>: a choice among the constants of the enum E, answered with the probability of each of them

  • Scale<E>: a scale whose levels are the constants of the enum E, in declaration order

  • a record or a class whose fields are annotated with @Decide and of the types above: one question per field, all asked in a single call

  • any of the above wrapped in DecisionResult, to also get the response of the model

public record Triage(
        @Decide("Which team should handle this ticket?") Team team,
        @Decide("Does this ticket need attention today?") boolean urgent) {
}

public interface TicketTriage {

    @Agent(description = "Triages a ticket", outputKey = "triage")
    Triage triage(@V("ticket") String ticket);
}

When it returns such an object, the @Agent method is not annotated with @Decide, and the questions are the ones of its fields.

Decision agents are @ApplicationScoped beans that can be injected and used as sub-agents of any workflow, like AI agents. A CompletableFuture return type is not supported: use @Agent(async = true) to run a decision agent asynchronously inside a workflow.

A decision agent has no prompt, chat memory, tools, retrieval augmentor or guardrails, so the build fails if it uses @UserMessage, @SystemMessage, @ChatModelSupplier, @ToolBox, @McpToolBox or @Skills. An application whose only agents are decision agents doesn’t need a chat model.

An injected decision agent can be invoked directly, outside of an agentic system, but each such invocation logs a warning. To ask a decision model a question from application code, use a Decision Service instead.

Configuring the Decision Model

By default, a decision agent uses the default DecisionModel bean, configured through the decision model provider, for instance OpenAI or TypeSafe.

Use @ModelName on the @Agent method to select a named decision model:

public interface FraudGate {

    @Decide("Does this transaction look fraudulent?")
    @Agent(description = "Checks a transaction for fraud", outputKey = "fraud")
    @ModelName("fraud")
    boolean check(@V("transaction") Transaction transaction);
}
quarkus.langchain4j.openai.fraud.api-key=sk-...
quarkus.langchain4j.openai.fraud.decision-model.model-name=gpt-6-luna

A static method annotated with @DecisionModelSupplier provides the model programmatically. Its parameters can be CDI beans, see Using CDI Beans in Static Agent Methods, and values read from the AgenticScope, in which case the method is invoked at each invocation of the agent to select the model:

public interface FraudGate {

    @Decide("Does this transaction look fraudulent?")
    @Agent(description = "Checks a transaction for fraud", outputKey = "fraud")
    boolean check(@V("transaction") Transaction transaction);

    @DecisionModelSupplier
    static DecisionModel decisionModel(@V("amount") double amount, @CdiBean FraudModels models) {
        return amount > 10_000 ? models.accurate() : models.fast();
    }
}

@ModelName and @DecisionModelSupplier can’t be used on the same agent.

Thresholds

A boolean answer is true when the probability of "yes" is at least the threshold, which is 0.5 by default. Thresholds are specific to a decision model and to its version, so they can be configured for each agent, and for each model answering it:

quarkus.langchain4j.agentic.decision-agent."spamGate".threshold=0.7
quarkus.langchain4j.agentic.decision-agent."spamGate".threshold-by-model."gpt-6-luna"=0.6

The key is the name of the agent: the name of @Agent, or the name of the method. The threshold of the model that answered takes precedence over the one of the agent.

The configuration is read once at startup. For a threshold that changes at runtime, declare a static method annotated with @DecisionThresholdSupplier instead, which is invoked at each invocation and takes precedence over the configuration:

public interface SpamGate {

    @Decide("Is this message spam?")
    @Agent(description = "Detects spam", outputKey = "spam")
    boolean isSpam(@V("message") String message);

    @DecisionThresholdSupplier
    static double threshold(ThresholdContext context, @CdiBean SpamSettings settings) {
        return settings.threshold(context.modelName());
    }
}

The application fails to start when a threshold is not between 0 and 1, or when it is configured for an agent that has no boolean answer or that declares a @DecisionThresholdSupplier method, since it would have no effect. A key that matches no decision agent logs a warning.

Listeners, Monitoring and Dev UI

An AgentListener bean, which must be @ApplicationScoped or @Singleton, is registered on every agent of the application, without any annotation on the agents: the AI agents, the decision agents, the workflows, the supervisor and planner agents, the non-AI and human-in-the-loop agents, and the A2A and MCP client agents. A non-AI, human-in-the-loop, A2A or MCP client agent declaring its own @AgentListenerSupplier method is the exception: such an agent has a single listener supplier, so it keeps the listener it supplies and is not given the listener beans.

The AgentListener beans receive the response of the decision model with AgentResponse.decisionResponse(), which carries the probabilities of the answers, the name of the model that answered and the token usage. The AgentMonitor of a MonitoredAgent records it as well.

In the Dev UI, decision agents are listed with the DecisionAgent type, the Topology page marks them as decisions, and the Executions page shows the model, the token usage and the answers of each decision.

Interceptor bindings, like @Retry from SmallRye Fault Tolerance, can be applied to the @Agent method of a decision agent, and they are honored inside workflows too.

Routing and Cascading with a Decision Model

The langchain4j-agentic-patterns library provides planners based on a decision model:

  • DecisionRouterPlanner lets the decision model choose the sub-agents that handle a request

  • ConfidenceCascadePlanner tries its sub-agents from the cheapest to the most capable, until the decision model accepts an answer

They get the DecisionModel bean through a @CdiBean parameter of the @PlannerSupplier method:

<dependency>
    <groupId>dev.langchain4j</groupId>
    <artifactId>langchain4j-agentic-patterns</artifactId>
</dependency>
public interface ExpertRouter {

    @PlannerAgent(outputKey = "answer", subAgents = { BillingExpert.class, SupportExpert.class })
    String route(@V("request") String request);

    @PlannerSupplier
    static Planner planner(@CdiBean DecisionModel decisionModel) {
        return new DecisionRouterPlanner(decisionModel);
    }
}

public interface AnswerCascade {

    @PlannerAgent(outputKey = "answer", subAgents = { SmallModelExpert.class, LargeModelExpert.class })
    String answer(@V("request") String request);

    @PlannerSupplier
    static Planner planner(@CdiBean DecisionModel decisionModel) {
        return new ConfidenceCascadePlanner(decisionModel, 0.6);
    }
}

Both planners report their decisions, so each of them is notified to the listeners with onPlannerModelResponse, and the Executions page of the Dev UI shows their tokens on the row of the planner agent.

Discovering A2A Agents with Apicurio Registry

Apicurio Registry can act as a catalog of A2A agents. With the Apicurio Registry A2A extension, an application can publish its own agent card to the registry at startup, and discover the agents other applications have published there.

This feature is experimental and may change in future releases.

Dependencies

<dependency>
    <groupId>io.quarkiverse.langchain4j</groupId>
    <artifactId>quarkus-langchain4j-a2a-apicurio-registry</artifactId>
</dependency>

Configuration

quarkus.langchain4j.a2a.apicurio-registry.url=http://localhost:8080/apis/registry/v3
# Optional: a bearer token for the registry
quarkus.langchain4j.a2a.apicurio-registry.auth-token=my-token

Discovering Agents

The extension provides an ApicurioAgentsRegistry bean, a LangChain4j AgentsRegistry backed by the registry’s AGENT_CARD artifacts:

@Inject
ApicurioAgentsRegistry agents;

public String describe(String name) {
    AgentInstance agent = agents.getAgent(name);
    return agent.description();
}

Each call to allAgents() or getAgent(…​) queries the registry again, so newly published agents are found without a restart. Discovery works as follows:

  • It reads every AGENT_CARD artifact in every group, paging through the full result set.

  • An agent is registered under the name in its card. When two artifacts declare the same name, neither is registered under that name. Each is registered under <groupId>/<artifactId> instead, and getAgent with the shared name fails with an error that lists both qualified names.

  • The agent’s URL comes from the artifact’s a2a-agent-url label. Without that label, the first JSONRPC entry in the card’s supportedInterfaces is used. An agent with neither is skipped, with a warning in the log.

  • Discovery does not contact the agents. The card of an agent is fetched from the agent itself the first time it is invoked, so an agent that cannot be reached is still listed, and fails when it is invoked. Its description is the one stored in the registry or, when the artifact has none, the one of its card.

  • The inputs an agent expects are read from the comma-separated a2a-input-keys label, or default to quarkus.langchain4j.a2a.apicurio-registry.default-input-keys (input).

Publishing an Agent Card

Annotate a class with @PublishToAgentRegistry to publish this application’s agent card to the registry at startup:

import io.quarkiverse.langchain4j.a2a.runtime.apicurio.PublishToAgentRegistry;

@PublishToAgentRegistry(
        name = "Translator",
        description = "Translates text between languages",
        version = "1.0.0",
        skills = {
                @PublishToAgentRegistry.Skill(id = "translate", name = "Translate", description = "Translates text")
        })
public class TranslatorCard {
}

The card is published as an AGENT_CARD artifact:

  • It is published in the group set by quarkus.langchain4j.a2a.apicurio-registry.group-id (default). Its artifact ID is the agent name in lower case, with characters other than letters, digits and - replaced by -.

  • The agent’s URL is quarkus.langchain4j.a2a.apicurio-registry.agent-url, which defaults to http://localhost:8080. Set it to the URL other applications should use to reach this agent.

  • Restarting with an unchanged card adds no version. A changed card adds a new version, even when version is unchanged.

  • The artifact’s labels are updated with the agent URL (a2a-agent-url) and skill names (a2a-agent-skills).

Publishing is best-effort. If it fails, for example because the registry cannot be reached or a registry rule rejects the new card, the failure is logged at ERROR level and the application starts anyway. A card that a rule rejects is not stored, so the previously published version stays the latest one. Configure rules in the registry, such as a COMPATIBILITY rule on the group, to reject card changes that would break the agent’s callers, for example removing a skill.

Agent Interfaces and Static Helpers

An agent can be declared as an interface, the form shared with plain LangChain4j: an interface with the agentic method and, as static methods, the helpers. The extension implements the interface with a synthetic bean, @ApplicationScoped unless the interface declares a scope, see Scoped Agents.

public interface StyleReviewLoop {

    @LoopAgent(outputKey = "story", maxIterations = 5, subAgents = { StyleScorer.class, StyleEditor.class })
    String review(@V("story") String story);

    @ExitCondition
    static boolean exit(@V("score") double score) {
        return score >= 0.8;
    }
}

Every example of this guide written as a class can be written as an interface, with static helper methods instead of instance ones.

Using CDI Beans in Static Agent Methods

Agent interfaces can’t have injected fields. Their static methods, however, can declare parameters resolved from CDI, by annotating them with @CdiBean or with a CDI qualifier, such as @ModelName. These parameters can be mixed with the ones read from the AgenticScope and with the ones provided by the agentic framework, like the AgenticScope itself or the ErrorContext:

public interface StyleReviewLoop {

    @LoopAgent(outputKey = "story", maxIterations = 5, subAgents = { StyleScorer.class, StyleEditor.class })
    String review(@V("story") String story);

    @ExitCondition
    static boolean exit(@V("score") double score, @CdiBean ReviewPolicy policy) {
        return score >= policy.minimumScore();
    }

    @Output
    static String output(@V("story") String story, @CdiBean StoryRepository repository) {
        repository.save(story);
        return story;
    }
}

The same works on the static method of a non-AI agent and on a @HumanInTheLoop method:

public class OrderLookup {

    @Agent(description = "Find the status of an order", outputKey = "orderStatus")
    public static String status(@V("orderId") String orderId, @CdiBean OrderService orders) {
        return orders.statusOf(orderId);
    }
}

public interface RefundApprover {

    @HumanInTheLoop(description = "Ask a manager to approve the refund", outputKey = "approved")
    static boolean approve(@V("orderId") String orderId, @CdiBean ApprovalService approvals) {
        return approvals.waitForApproval(orderId);
    }
}

CDI parameters can be declared on the methods annotated with:

  • any supplier annotation: @ChatModelSupplier, @StreamingChatModelSupplier, @ChatMemorySupplier, @ChatMemoryProviderSupplier, @ToolsSupplier, @ToolProviderSupplier, @ContentRetrieverSupplier, @RetrievalAugmentorSupplier, @AgentListenerSupplier, @SystemMessageProviderSupplier, @UserMessageProviderSupplier, @McpClientSupplier, @PlannerSupplier, @A2AServerUrlSupplier, @ParallelExecutor, @DecisionModelSupplier and @DecisionThresholdSupplier

  • @ExitCondition, @ActivationCondition, @Output, @BeforeCall, @ErrorHandler, @SupervisorRequest and @A2AClientCustomizer

  • @Agent, on the static method of a non-AI agent, and @HumanInTheLoop

The methods can be declared on the agent type or on one of its parent interfaces.

A CDI parameter:

  • is looked up at each invocation of the method, so a @RequestScoped bean is the one of the current request. The CDI parameters of a @A2AClientCustomizer method are instead looked up when the agent is created, like the ones of the supplier methods, although the method itself runs later, when the remote agent is first invoked. A @McpClientSupplier method also runs later, when the MCP client is first needed, on the first invocation of the agent: a @McpClientName client that it returns connects to its server at that moment, unless something else already used it

  • of type ChatModel, DecisionModel, ModerationModel or ImageModel, without qualifier or with @ModelName, gets the bean of the configured model provider, even if nothing else injects it

  • is not an argument of the agent: it is not read from the AgenticScope, not reported to listeners, and not described to a supervisor

  • must resolve to exactly one bean, otherwise the build fails

The bean is looked up on the thread invoking the method. The subagents of a parallel workflow and the async agents run on the threads of the executor of the extension, which propagates the request context, so their methods can use a @RequestScoped bean too. The executor that a workflow provides with @ParallelExecutor propagates the request context only if the application makes it do so. An async agent can however run after the request that invoked the workflow has returned, see Asynchronous Agents, so a bean it uses can’t depend on that request. A @Dependent bean is created at each invocation and never destroyed: prefer a normal scope, like @ApplicationScoped.

The methods stay static: an agent interface can’t have injected fields, constructor injection or @PostConstruct callbacks, and interceptor bindings like @Transactional have no effect on these methods. To use them, declare the agent as a class, see Agents as CDI Beans.

Build-Time Validation

Quarkus validates agent configurations at build time, catching errors before the application starts:

  • All helper methods, the suppliers like @ToolsSupplier, the conditions, @Output, @BeforeCall, @ErrorHandler and @SupervisorRequest, must be static methods of the agent type or instance methods of an agent class, with correct return types

  • @ChatModelSupplier methods must return ChatModel (parameters are allowed for dynamic model selection)

  • An agent class must be concrete and non-final, with a no-arg constructor, a scope other than @Dependent and exactly one agentic method, neither private, static nor final; a workflow, supervisor, planner or decision method of a class must be native

  • An agent class can’t declare both a static and an instance method with the same helper annotation, and an instance helper method can’t be private or final

  • A @RegisterAiService attribute can’t configure the same feature as an agentic supplier method, like tools with @ToolsSupplier

  • @ExitCondition and @ActivationCondition methods must return boolean

  • @ErrorHandler methods must take ErrorContext and return ErrorRecoveryResult

  • @BeforeCall methods must take AgenticScope and @ChatMemoryProviderSupplier methods must take the memory id as an Object

  • @ParallelExecutor methods must return Executor, and neither they nor @A2AServerUrlSupplier methods can have parameters

  • In all the rules above, the parameters annotated with @CdiBean or with a CDI qualifier are not counted, and each of them must resolve to exactly one bean

  • @ModelName and @ChatModelSupplier cannot be used on the same agent

  • @DecisionModelSupplier and @DecisionThresholdSupplier methods can only be declared on decision agents, and return DecisionModel, and double or Double, respectively

  • @DecisionThresholdSupplier methods must take a ThresholdContext, and can’t be declared on a decision agent that has no boolean answer

  • A decision agent can’t use @UserMessage, @SystemMessage, @ChatModelSupplier, @StreamingChatModelSupplier, @ToolBox, @McpToolBox or @Skills, nor both @ModelName and @DecisionModelSupplier

Annotations Reference

Annotation Target Purpose Parameters

@Agent

method

Declares a basic AI agent method, native on a class, or the method of a non-AI agent, an instance method of a bean or a static method.

Agent arguments. On a non-AI agent, also CDI beans.

@SequenceAgent

method

Sequential workflow of sub-agents.

Agent arguments.

@LoopAgent

method

Iterative workflow with exit condition.

Agent arguments.

@ParallelAgent

method

Parallel execution of sub-agents.

Agent arguments.

@ParallelMapperAgent

method

Maps one sub-agent over a collection.

Agent arguments.

@ConditionalAgent

method

Conditional routing to sub-agents.

Agent arguments.

@SupervisorAgent

method

LLM-driven dynamic orchestration.

Agent arguments.

@PlannerAgent

method

Custom planner-driven orchestration.

Agent arguments.

@HumanInTheLoop

method of a bean, or static method

Pauses for human input.

Values from the AgenticScope, and CDI beans.

@ExitCondition

helper method

Loop exit predicate (returns boolean).

Values from the AgenticScope, the loop counter, and CDI beans.

@ActivationCondition

helper method

Conditional routing predicate (returns boolean).

Values from the AgenticScope, and CDI beans.

@ErrorHandler

helper method

Error recovery (takes ErrorContext, returns ErrorRecoveryResult).

The ErrorContext, and CDI beans.

@Output

helper method

Custom output combiner for parallel workflows.

Values from the AgenticScope, and CDI beans.

@ChatModelSupplier

helper method

Provides per-agent ChatModel.

Values from the AgenticScope, and CDI beans.

@SupervisorRequest

helper method

Custom prompt builder for supervisor.

Values from the AgenticScope, and CDI beans.

@ParallelExecutor

helper method

Provides Executor for parallel workflows.

CDI beans only.

@Decide

method, field

The question of a decision agent, on its @Agent method, or on the fields of the object it returns.

-

@DecisionModelSupplier

helper method

Provides the DecisionModel of a decision agent.

Values from the AgenticScope, and CDI beans.

@DecisionThresholdSupplier

helper method

Provides the threshold of the boolean answers of a decision agent.

The ThresholdContext, and CDI beans.

@CdiBean

parameter

Resolves the parameter of a static agent method from CDI, see Using CDI Beans in Static Agent Methods.

-

A helper method is an instance method of an agent class, invoked on the bean, or a static method of an agent interface.

Configuration Reference

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

The threshold of the boolean answers of this agent, between 0 and 1: an answer is true when the probability of "yes" is at least the threshold. 0.5 when absent.

Environment variable: QUARKUS_LANGCHAIN4J_AGENTIC_DECISION_AGENT__AGENT_NAME__THRESHOLD

double

The threshold to use when the given decision model answered, keyed by model name, overriding threshold. Thresholds are specific to a decision model and to its version.

Environment variable: QUARKUS_LANGCHAIN4J_AGENTIC_DECISION_AGENT__AGENT_NAME__THRESHOLD_BY_MODEL__MODEL_NAME_

Map<String,Double>

Apicurio Registry A2A Integration

Configuration property fixed at build time - All other configuration properties are overridable at runtime

Configuration property

Type

Default

Whether the Apicurio Registry A2A agent discovery integration is enabled.

Environment variable: QUARKUS_LANGCHAIN4J_A2A_APICURIO_REGISTRY_ENABLED

boolean

true

The base URL of the Apicurio Registry instance (e.g. http://localhost:8080/apis/registry/v3).

Environment variable: QUARKUS_LANGCHAIN4J_A2A_APICURIO_REGISTRY_URL

string

Optional authentication token for the registry.

Environment variable: QUARKUS_LANGCHAIN4J_A2A_APICURIO_REGISTRY_AUTH_TOKEN

string

Group ID to use when publishing and searching agent cards.

Environment variable: QUARKUS_LANGCHAIN4J_A2A_APICURIO_REGISTRY_GROUP_ID

string

default

The base URL of this application’s A2A server endpoint, used when publishing the agent card.

Environment variable: QUARKUS_LANGCHAIN4J_A2A_APICURIO_REGISTRY_AGENT_URL

string

The input keys used for agents discovered from the registry whose agent card artifact does not declare an a2a-input-keys label.

A2A agent cards carry no input schema, so discovered agents are built as untyped agents and these keys define both the arguments exposed to a supervisor or planner and the keys read from the AgenticScope when invoking the remote agent.

Environment variable: QUARKUS_LANGCHAIN4J_A2A_APICURIO_REGISTRY_DEFAULT_INPUT_KEYS

list of string

input