Agentic Systems
在最近的一篇研究出版物 Building Effective Agents 中,Anthropic 分享了关于构建有效大型语言模型 (LLM) 代理的宝贵见解。这项研究特别有趣的原因在于它强调了简单性和可组合性,而不是复杂的框架。让我们探讨这些原则如何使用 Spring AI 转化为实际实现。
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.

虽然模式描述和图表来源于 Anthropic 的原始出版物,但我们将重点关注如何使用 Spring AI 的功能实现这些模式,以实现模型可移植性和结构化输出。我们建议您先阅读原始论文。
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-ai-examples 存储库中的 agentic-patterns 目录包含所有示例的代码。
The agentic-patterns directory in the spring-ai-examples repository contains all the code for the examples that follow.
Agentic Systems
该研究出版物在两种类型的代理系统之间做出了重要的架构区分:
The research publication makes an important architectural distinction between two types of agentic systems:
-
Workflows :LLM 和工具通过预定义代码路径(例如,规定性系统)进行编排的系统
-
Workflows: Systems where LLMs and tools are orchestrated through predefined code paths (e.g., prescriptive systems)
-
Agents :LLM 动态指导其自身进程和工具使用的系统
-
Agents: Systems where LLMs dynamically direct their own processes and tool usage
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 AI如何通过五种基本模式实现这些概念,每种模式都服务于特定的用例:
Let’s examine how Spring AI implements these concepts through five fundamental patterns, each serving specific use cases:
1. Chain Workflow
链式工作流模式阐明了将复杂任务分解为更简单、更易于管理的步骤的原则。
The Chain Workflow pattern exemplifies the principle of breaking down complex tasks into simpler, more manageable steps.

When to Use: - 具有明确顺序步骤的任务 - 当您想用延迟换取更高准确性时 - 当每个步骤都建立在前一个步骤的输出之上时
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 output
以下是Spring AI实现中的一个实际示例:
Here’s a practical example from Spring AI’s implementation:
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:
-
* 每个步骤都有一个集中的职责
-
Each step has a focused responsibility
-
* 一个步骤的输出成为下一个步骤的输入
-
Output from one step becomes input for the next
-
* 该链易于扩展和维护
-
The chain is easily extensible and maintainable
2. Parallelization Workflow
LLMs(大型语言模型)可以同时处理任务,并对其输出进行程序化聚合。
LLMs can work simultaneously on tasks and have their outputs aggregated programmatically.

When to Use: - 处理大量相似但独立的项 - 需要多个独立视角的任务 - 当处理时间至关重要且任务可并行化时
When to Use: - Processing large volumes of similar but independent items - Tasks requiring multiple independent perspectives - When processing time is critical and tasks are parallelizable
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.

When to Use: - 具有不同输入类别的复杂任务 - 当不同输入需要专门处理时 - 当分类可以准确处理时
When to Use: - Complex tasks with distinct categories of input - When different inputs require specialized processing - When classification can be handled accurately
@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

When to Use: - 无法预先预测子任务的复杂任务 - 需要不同方法或视角的任务 - 需要自适应问题解决的情况
When to Use: - Complex tasks where subtasks can’t be predicted upfront - Tasks requiring different approaches or perspectives - Situations needing adaptive problem-solving
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:
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

When to Use: - 存在明确的评估标准 - 迭代式改进提供可衡量价值 - 任务受益于多轮批评
When to Use: - Clear evaluation criteria exist - Iterative refinement provides measurable value - Tasks benefit from multiple rounds of critique
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:
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对这些模式的实现提供了多项益处,与Anthropic的建议相符:
Spring AI’s implementation of these patterns offers several benefits that align with Anthropic’s recommendations:
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
-
* 跨不同LLM提供商的统一接口
-
Uniform interface across different LLM providers
-
* 内置错误处理和重试
-
Built-in error handling and retries
-
Flexible prompt management
Best Practices and Recommendations
-
Start Simple
-
在增加复杂性之前,先从基本工作流开始
-
Begin with basic workflows before adding complexity
-
使用满足您需求的最简单模式。
-
Use the simplest pattern that meets your requirements
-
只在必要时增加复杂性。
-
Add sophistication only when needed
-
Design for Reliability
-
Implement clear error handling
-
尽可能使用类型安全的响应。
-
Use type-safe responses where possible
-
在每个步骤中都内置验证。
-
Build in validation at each step
-
Consider Trade-offs
-
Balance latency vs. accuracy
-
评估何时使用并行处理。
-
Evaluate when to use parallel processing
-
在固定工作流和动态代理之间进行选择。
-
Choose between fixed workflows and dynamic agents
Future Work
这些指南将更新,以探讨如何构建更高级的代理,这些代理将这些基础模式与复杂功能相结合:
These guides will be updated to explore how to build more advanced Agents that combine these foundational patterns with sophisticated features:
Pattern Composition - 结合多种模式以创建更强大的工作流 - 构建利用每种模式优点的混合系统 - 创建能够适应不断变化需求的灵活架构
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 requirements
Advanced Agent Memory Management - 在对话中实现持久内存 - 有效管理上下文窗口 - 开发长期知识保留策略
Advanced Agent Memory Management - Implementing persistent memory across conversations - Managing context windows efficiently - Developing strategies for long-term knowledge retention
Tools and Model-Context Protocol (MCP) Integration - 通过标准化接口利用外部工具 - 实现 MCP 以增强模型交互 - 构建可扩展的代理架构
Tools and Model-Context Protocol (MCP) Integration - Leveraging external tools through standardized interfaces - Implementing MCP for enhanced model interactions - Building extensible agent architectures
Conclusion
Anthropic 的研究见解与 Spring AI 的实际实现相结合,为构建有效的基于 LLM 的系统提供了强大的框架。
The combination of Anthropic’s research insights and Spring AI’s practical implementations provides a powerful framework for building effective LLM-based systems.
通过遵循这些模式和原则,开发人员可以创建健壮、可维护、有效的 AI 应用程序,在避免不必要的复杂性的同时提供真正的价值。
By following these patterns and principles, developers can create robust, maintainable, and effective AI applications that deliver real value while avoiding unnecessary complexity.
关键是记住,有时最简单的解决方案是最有效的。从基本模式开始,彻底理解您的用例,并且只有在明显改善系统性能或功能时才增加复杂性。
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.