In a recent research publication, Building Effective Agents, Anthropic shared valuable insights about building effective Large Language Model (LLM) agents. What makes this research particularly interesting is its emphasis on simplicity and composability over complex frameworks. Let’s explore how these principles translate into practical implementations using Spring AI.spring-doc.cn

Agent Systems

While the pattern descriptions and diagrams are sourced from Anthropic’s original publication, we’ll focus on how to implement these patterns using Spring AI’s features for model portability and structured output. We recommend reading the original paper first.spring-doc.cn

The agentic-patterns directory in the spring-ai-examples repository contains all the code for the examples that follow.spring-doc.cn

Agentic Systems

The research publication makes an important architectural distinction between two types of agentic systems:spring-doc.cn

  1. Workflows: Systems where LLMs and tools are orchestrated through predefined code paths (e.g., prescriptive systems)spring-doc.cn

  2. Agents: Systems where LLMs dynamically direct their own processes and tool usagespring-doc.cn

The key insight is that while fully autonomous agents might seem appealing, workflows often provide better predictability and consistency for well-defined tasks. This aligns perfectly with enterprise requirements where reliability and maintainability are crucial.spring-doc.cn

Let’s examine how Spring AI implements these concepts through five fundamental patterns, each serving specific use cases:spring-doc.cn

1. Chain Workflow

The Chain Workflow pattern exemplifies the principle of breaking down complex tasks into simpler, more manageable steps.spring-doc.cn

Prompt Chaining Workflow

When to Use: - Tasks with clear sequential steps - When you want to trade latency for higher accuracy - When each step builds on the previous step’s outputspring-doc.cn

Here’s a practical example from Spring AI’s implementation:spring-doc.cn

public class ChainWorkflow {
    private final ChatClient chatClient;
    private final String[] systemPrompts;

    public String chain(String userInput) {
        String response = userInput;
        for (String prompt : systemPrompts) {
            String input = String.format("{%s}\n {%s}", prompt, response);
            response = chatClient.prompt(input).call().content();
        }
        return response;
    }
}

This implementation demonstrates several key principles:spring-doc.cn

2. Parallelization Workflow

LLMs can work simultaneously on tasks and have their outputs aggregated programmatically.spring-doc.cn

Parallelization Workflow

When to Use: - Processing large volumes of similar but independent items - Tasks requiring multiple independent perspectives - When processing time is critical and tasks are parallelizablespring-doc.cn

List<String> parallelResponse = new ParallelizationWorkflow(chatClient)
    .parallel(
        "Analyze how market changes will impact this stakeholder group.",
        List.of(
            "Customers: ...",
            "Employees: ...",
            "Investors: ...",
            "Suppliers: ..."
        ),
        4
    );

3. Routing Workflow

The Routing pattern implements intelligent task distribution, enabling specialized handling for different types of input.spring-doc.cn

Routing Workflow

When to Use: - Complex tasks with distinct categories of input - When different inputs require specialized processing - When classification can be handled accuratelyspring-doc.cn

@Autowired
private ChatClient chatClient;

RoutingWorkflow workflow = new RoutingWorkflow(chatClient);

Map<String, String> routes = Map.of(
    "billing", "You are a billing specialist. Help resolve billing issues...",
    "technical", "You are a technical support engineer. Help solve technical problems...",
    "general", "You are a customer service representative. Help with general inquiries..."
);

String input = "My account was charged twice last week";
String response = workflow.route(input, routes);

4. Orchestrator-Workers

Orchestration Workflow

When to Use: - Complex tasks where subtasks can’t be predicted upfront - Tasks requiring different approaches or perspectives - Situations needing adaptive problem-solvingspring-doc.cn

public class OrchestratorWorkersWorkflow {
    public WorkerResponse process(String taskDescription) {
        // 1. Orchestrator analyzes task and determines subtasks
        OrchestratorResponse orchestratorResponse = // ...

        // 2. Workers process subtasks in parallel
        List<String> workerResponses = // ...

        // 3. Results are combined into final response
        return new WorkerResponse(/*...*/);
    }
}

Usage Example:spring-doc.cn

ChatClient chatClient = // ... initialize chat client
OrchestratorWorkersWorkflow workflow = new OrchestratorWorkersWorkflow(chatClient);

WorkerResponse response = workflow.process(
    "Generate both technical and user-friendly documentation for a REST API endpoint"
);

System.out.println("Analysis: " + response.analysis());
System.out.println("Worker Outputs: " + response.workerResponses());

5. Evaluator-Optimizer

Evaluator-Optimizer Workflow

When to Use: - Clear evaluation criteria exist - Iterative refinement provides measurable value - Tasks benefit from multiple rounds of critiquespring-doc.cn

public class EvaluatorOptimizerWorkflow {
    public RefinedResponse loop(String task) {
        Generation generation = generate(task, context);
        EvaluationResponse evaluation = evaluate(generation.response(), task);
        return new RefinedResponse(finalSolution, chainOfThought);
    }
}

Usage Example:spring-doc.cn

ChatClient chatClient = // ... initialize chat client
EvaluatorOptimizerWorkflow workflow = new EvaluatorOptimizerWorkflow(chatClient);

RefinedResponse response = workflow.loop(
    "Create a Java class implementing a thread-safe counter"
);

System.out.println("Final Solution: " + response.solution());
System.out.println("Evolution: " + response.chainOfThought());

Spring AI’s Implementation Advantages

Spring AI’s implementation of these patterns offers several benefits that align with Anthropic’s recommendations:spring-doc.cn

Model Portability

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>

Structured Output

EvaluationResponse response = chatClient.prompt(prompt)
    .call()
    .entity(EvaluationResponse.class);

Consistent API

Best Practices and Recommendations

Future Work

These guides will be updated to explore how to build more advanced Agents that combine these foundational patterns with sophisticated features:spring-doc.cn

Pattern Composition - Combining multiple patterns to create more powerful workflows - Building hybrid systems that leverage the strengths of each pattern - Creating flexible architectures that can adapt to changing requirementsspring-doc.cn

Advanced Agent Memory Management - Implementing persistent memory across conversations - Managing context windows efficiently - Developing strategies for long-term knowledge retentionspring-doc.cn

Tools and Model-Context Protocol (MCP) Integration - Leveraging external tools through standardized interfaces - Implementing MCP for enhanced model interactions - Building extensible agent architecturesspring-doc.cn

Conclusion

The combination of Anthropic’s research insights and Spring AI’s practical implementations provides a powerful framework for building effective LLM-based systems.spring-doc.cn

By following these patterns and principles, developers can create robust, maintainable, and effective AI applications that deliver real value while avoiding unnecessary complexity.spring-doc.cn

The key is to remember that sometimes the simplest solution is the most effective. Start with basic patterns, understand your use case thoroughly, and only add complexity when it demonstrably improves your system’s performance or capabilities.spring-doc.cn