CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-dev-langchain4j--langchain4j-agentic

LangChain4j Agentic Framework provides a comprehensive Java library for building multi-agent AI systems with support for workflow orchestration, supervisor agents, planning-based execution, declarative configuration, agent-to-agent communication, and human-in-the-loop workflows.

Overview
Eval results
Files

annotations.mddocs/declarative/

Declarative Annotations

Annotation-based approach for defining agents using @Agent and workflow annotations for clean declarative agent system definitions.

Overview

Declarative API enables:

  • Clean interface-based agent definitions
  • Automatic agent system creation
  • Annotation-driven configuration
  • Type-safe agent interfaces
  • Reduced boilerplate

Creating Agent Systems

static <T> T createAgenticSystem(Class<T> agentServiceClass);
static <T> T createAgenticSystem(Class<T> agentServiceClass, ChatModel chatModel);
static <T> T createAgenticSystem(Class<T> agentServiceClass, Consumer<DeclarativeAgentCreationContext> configurator);
static <T> T createAgenticSystem(Class<T> agentServiceClass, ChatModel chatModel, Consumer<DeclarativeAgentCreationContext> configurator);

Quick Start:

interface Assistant {
    @Agent(name = "assistant", description = "General purpose assistant")
    String assist(String query);
}

Assistant assistant = AgenticServices.createAgenticSystem(Assistant.class, chatModel);
String response = assistant.assist("Hello!");

Core Annotations

@Agent

Full @Agent Reference

Examples:

interface MyAgents {
    @Agent(
        name = "researcher",
        description = "Researches topics using web search",
        outputKey = "research_results",
        async = false
    )
    String research(String topic);

    @Agent(
        name = "writer",
        description = "Writes articles based on research",
        summarizedContext = {"researcher"}
    )
    String write(String topic);
}

Workflow Annotations

@SequenceAgent

Full @SequenceAgent Reference

Example:

interface Pipeline {
    @SequenceAgent(
        name = "data-pipeline",
        description = "Processes data through multiple stages",
        subAgents = {Fetcher.class, Processor.class, Validator.class}
    )
    String processPipeline(String input);
}

@ParallelAgent

Full @ParallelAgent Reference

Example:

interface ParallelProcessing {
    @ParallelAgent(
        name = "multi-source",
        description = "Fetches data from multiple sources simultaneously",
        subAgents = {ApiSource.class, DatabaseSource.class, FileSource.class}
    )
    String fetchAllSources(String query);
}

@LoopAgent

Full @LoopAgent Reference

Example:

interface IterativeRefinement {
    @LoopAgent(
        name = "refiner",
        description = "Iteratively refines output until quality threshold met",
        maxIterations = 5,
        subAgents = {Generator.class, Evaluator.class}
    )
    String refine(String input);

    @ExitCondition
    boolean isQualityMet(AgenticScope scope) {
        return scope.hasState("quality_score") &&
               (Integer) scope.readState("quality_score") >= 8;
    }
}

@ConditionalAgent

Full @ConditionalAgent Reference

Example:

interface ConditionalProcessing {
    @ConditionalAgent(
        name = "router",
        description = "Routes to different processors based on input type",
        subAgents = {TextProcessor.class, ImageProcessor.class}
    )
    String process(String input);
}

interface TextProcessor {
    @Agent(name = "text-processor")
    String process(String input);

    @ActivationCondition
    boolean shouldActivate(AgenticScope scope) {
        return scope.readState("input_type").equals("text");
    }
}

@SupervisorAgent

Full @SupervisorAgent Reference

Example:

interface SupervisedSystem {
    @SupervisorAgent(
        name = "orchestrator",
        description = "Coordinates specialized agents",
        subAgents = {Researcher.class, Analyst.class, Writer.class},
        maxAgentsInvocations = 15,
        contextStrategy = SupervisorContextStrategy.FULL,
        responseStrategy = SupervisorResponseStrategy.SUMMARY
    )
    String complete(String task);
}

@PlannerAgent

Full @PlannerAgent Reference

Example:

interface PlannedExecution {
    @PlannerAgent(
        name = "dynamic-planner",
        subAgents = {Agent1.class, Agent2.class}
    )
    String execute(String goal);

    @PlannerSupplier
    Planner getPlanner();
}

@A2AClientAgent

Full @A2AClientAgent Reference

Example:

interface DistributedAgents {
    @A2AClientAgent(
        name = "remote-analyzer",
        description = "Connects to remote analysis service",
        serverUrl = "http://analysis-service:8080"
    )
    String analyze(String data);
}

@HumanInTheLoop

Full @HumanInTheLoop Reference

Example:

interface ApprovalWorkflow {
    @Agent(name = "drafter")
    String draft(String topic);

    @HumanInTheLoop(
        name = "approval",
        description = "Human reviews and approves draft",
        inputKey = "draft",
        outputKey = "approved_draft"
    )
    String getApproval();

    @Agent(name = "publisher")
    String publish();
}

Supplier Annotations

Configuration Suppliers

Examples:

interface ConfiguredAgents {
    @ChatModelSupplier
    ChatModel getChatModel();

    @ToolsSupplier
    List<Object> getTools();

    @Agent(name = "assistant")
    String assist(String query);
}

Control Annotations

@ErrorHandler

Full @ErrorHandler Reference

Example:

interface RobustAgent {
    @Agent(name = "processor")
    String process(String input);

    @ErrorHandler
    ErrorRecoveryResult handleError(Throwable error, AgenticScope scope);
}

@Output

Full @Output Reference

Example:

interface CustomOutput {
    @Agent(name = "processor")
    String process(String input);

    @Output
    String customizeOutput(AgenticScope scope);
}

@ActivationCondition

Full @ActivationCondition Reference

Example:

interface ConditionalPipeline {
    @SequenceAgent(
        subAgents = {Agent1.class, OptionalAgent.class, Agent3.class}
    )
    String process(String input);

    default boolean shouldRunOptional(AgenticScope scope) {
        return (Boolean) scope.readState("feature_enabled", false);
    }
}

interface OptionalAgent {
    @Agent(name = "optional")
    @ActivationCondition(conditionMethod = "shouldRunOptional")
    String process(AgenticScope scope);
}

@ExitCondition

Full @ExitCondition Reference

Example:

interface LoopWorkflow {
    @LoopAgent(maxIterations = 10, subAgents = {Worker.class})
    String work(String input);

    @ExitCondition
    boolean shouldExit(AgenticScope scope) {
        return scope.hasState("done");
    }
}

@SupervisorRequest

Full @SupervisorRequest Reference

Example:

interface SupervisorSystem {
    @SupervisorAgent(subAgents = {Agent1.class, Agent2.class})
    String coordinate(String task);

    @SupervisorRequest
    String generateRequest(AgenticScope scope) {
        String task = (String) scope.readState("user_input");
        return "Coordinate agents to solve: " + task;
    }
}

@HumanInTheLoopResponseSupplier

Full @HumanInTheLoopResponseSupplier Reference

Example:

interface HITLWorkflow {
    @SequenceAgent(
        subAgents = {Generator.class, HumanReview.class, Publisher.class}
    )
    String workflow(String input);

    @HumanInTheLoopResponseSupplier
    String getHumanFeedback() {
        Scanner scanner = new Scanner(System.in);
        return scanner.nextLine();
    }
}

@ParallelExecutor

Full @ParallelExecutor Reference

Example:

interface ParallelSystem {
    @ParallelAgent(
        subAgents = {Worker1.class, Worker2.class, Worker3.class}
    )
    List<String> processInParallel(String input);

    @ParallelExecutor
    static Executor executor() {
        return Executors.newFixedThreadPool(3);
    }
}

Parameter Annotations

@K (State Injection)

Full @K Reference

Example:

interface UserName extends TypedKey<String> {
    @Override
    default String name() {
        return "UserName";
    }
}

interface PersonalizedAgent {
    @Agent(name = "greeter")
    String greet(@K(UserName.class) String name, @K(UserAge.class) int age);
}

@LoopCounter

Full @LoopCounter Reference

Example:

interface LoopingAgent {
    @LoopAgent(maxIterations = 10, subAgents = {Processor.class})
    String processUntilDone(String input);
}

interface Processor {
    @Agent(name = "processor")
    String process(String input, @LoopCounter int iteration);
}

Complete Example

interface ComprehensiveSystem {
    // Chat model configuration
    @ChatModelSupplier
    ChatModel getChatModel() {
        return OpenAiChatModel.builder()
            .apiKey(System.getenv("OPENAI_API_KEY"))
            .modelName("gpt-4")
            .build();
    }

    // Tools configuration
    @ToolsSupplier
    List<Object> getTools() {
        return List.of(new WebSearchTool(), new CalculatorTool());
    }

    // Agent listener for observability
    @AgentListenerSupplier
    AgentListener getListener() {
        return new LoggingListener();
    }

    // Sequential workflow
    @SequenceAgent(
        name = "main-workflow",
        subAgents = {DataCollector.class, Analyzer.class, Reporter.class}
    )
    String processRequest(String input);

    // Error handler
    @ErrorHandler
    ErrorRecoveryResult handleError(Throwable error, AgenticScope scope) {
        if (error instanceof RetryableException) {
            return ErrorRecoveryResult.retry();
        }
        return ErrorRecoveryResult.throwException();
    }

    // Custom output
    @Output
    String formatOutput(AgenticScope scope) {
        return Map.of(
            "result", scope.readState("final_result"),
            "metadata", scope.readState("metadata")
        ).toString();
    }
}

See Also

Install with Tessl CLI

npx tessl i tessl/maven-dev-langchain4j--langchain4j-agentic@1.11.0

docs

declarative

annotations.md

typed-keys.md

index.md

tile.json