领先一步
VMware 提供培训和认证,助您加速进步。
了解更多在最近的一篇研究论文《构建高效代理》中,Anthropic 分享了关于构建高效大型语言模型 (LLM) 代理的宝贵见解。这项研究特别有趣的是,它强调了简单性和可组合性,而非复杂的框架。让我们探讨一下这些原则如何使用 Spring AI 转化为实际实现。
虽然模式描述和图表来源于 Anthropic 的原始出版物,但我们将重点介绍如何使用 Spring AI 的特性来实现这些模式,以实现模型可移植性和结构化输出。我们建议首先阅读原始论文。
agentic-patterns 项目实现了下面讨论的模式。
这项研究出版物在两种类型的代理系统之间做出了重要的架构区分:
关键的见解是,虽然完全自主的代理可能看起来很有吸引力,但工作流通常为明确定义的任务提供更好的可预测性和一致性。这与对可靠性和可维护性至关重要的企业要求完美契合。
让我们通过五种基本模式来研究 Spring AI 如何实现这些概念,每种模式都服务于特定的用例:
链式工作流模式是分解复杂任务为更简单、更易管理步骤的原则的典范。

何时使用
以下是 Spring AI 实现中的一个实际示例:
public class ChainWorkflow {
private final ChatClient chatClient;
private final String[] systemPrompts;
// Processes input through a series of prompts, where each step's output
// becomes input for the next step in the chain.
public String chain(String userInput) {
String response = userInput;
for (String prompt : systemPrompts) {
// Combine the system prompt with previous response
String input = String.format("{%s}\n {%s}", prompt, response);
// Process through the LLM and capture output
response = chatClient.prompt(input).call().content();
}
return response;
}
}
此实现演示了几个关键原则:
LLM 可以同时处理任务,并以编程方式聚合其输出。并行化工作流以两种主要变体体现:

何时使用
并行化工作流模式演示了多个大型语言模型(LLM)操作的高效并发处理。此模式特别适用于需要并行执行 LLM 调用并自动聚合输出的场景。
以下是使用并行化工作流的基本示例:
List<String> parallelResponse = new ParallelizationWorkflow(chatClient)
.parallel(
"Analyze how market changes will impact this stakeholder group.",
List.of(
"Customers: ...",
"Employees: ...",
"Investors: ...",
"Suppliers: ..."
),
4
);
此示例演示了利益相关者分析的并行处理,其中每个利益相关者组都同时进行分析。
路由模式实现智能任务分发,为不同类型的输入提供专门的处理。

此模式专为复杂任务而设计,其中不同类型的输入通过专门的流程进行更好地处理。它使用 LLM 分析输入内容并将其路由到最合适的专门提示或处理程序。
何时使用
以下是使用路由工作流的基本示例:
@Autowired
private ChatClient chatClient;
// Create the workflow
RoutingWorkflow workflow = new RoutingWorkflow(chatClient);
// Define specialized prompts for different types of input
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..."
);
// Process input
String input = "My account was charged twice last week";
String response = workflow.route(input, routes);
此模式演示了如何在保持控制的同时实现更复杂的代理类行为

何时使用
该实现使用 Spring AI 的 ChatClient 进行 LLM 交互,并包括
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(/*...*/);
}
}
ChatClient chatClient = // ... initialize chat client
OrchestratorWorkersWorkflow workflow = new OrchestratorWorkersWorkflow(chatClient);
// Process a task
WorkerResponse response = workflow.process(
"Generate both technical and user-friendly documentation for a REST API endpoint"
);
// Access results
System.out.println("Analysis: " + response.analysis());
System.out.println("Worker Outputs: " + response.workerResponses());
评估器-优化器模式实现了一个双 LLM 过程,其中一个模型生成响应,而另一个模型在迭代循环中提供评估和反馈,类似于人类作者的精炼过程。该模式由两个主要组件组成:

何时使用
该实现使用 Spring AI 的 ChatClient 进行 LLM 交互,并包括
public class EvaluatorOptimizerWorkflow {
public RefinedResponse loop(String task) {
// 1. Generate initial solution
Generation generation = generate(task, context);
// 2. Evaluate the solution
EvaluationResponse evaluation = evaluate(generation.response(), task);
// 3. If PASS, return solution
// 4. If NEEDS_IMPROVEMENT, incorporate feedback and generate new solution
// 5. Repeat until satisfactory
return new RefinedResponse(finalSolution, chainOfThought);
}
}
ChatClient chatClient = // ... initialize chat client
EvaluatorOptimizerWorkflow workflow = new EvaluatorOptimizerWorkflow(chatClient);
// Process a task
RefinedResponse response = workflow.loop(
"Create a Java class implementing a thread-safe counter"
);
// Access results
System.out.println("Final Solution: " + response.solution());
System.out.println("Evolution: " + response.chainOfThought());
Spring AI 对这些模式的实现提供了与 Anthropic 建议相符的几项优势:
<!-- Easy model switching through dependencies -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
// Type-safe handling of LLM responses
EvaluationResponse response = chatClient.prompt(prompt)
.call()
.entity(EvaluationResponse.class);
基于 Anthropic 的研究和 Spring AI 的实现,以下是构建基于 LLM 的有效系统的关键建议:
从简单开始
设计可靠性
考虑权衡
在本系列的第 2 部分中,我们将探讨如何构建更高级的代理,将这些基础模式与复杂功能结合起来:
模式组合
高级代理内存管理
工具和模型上下文协议 (MCP) 集成
敬请关注这些高级功能的详细实现和最佳实践。
VMware Tanzu Platform 10 Tanzu AI Server,由 Spring AI 提供支持,提供:
有关使用 Tanzu AI Server 部署 AI 应用程序的更多信息,请访问 VMware Tanzu AI 文档。
Anthropic 的研究洞察与 Spring AI 的实际实现相结合,为构建基于 LLM 的有效系统提供了强大的框架。通过遵循这些模式和原则,开发人员可以创建健壮、可维护和有效的 AI 应用程序,在避免不必要的复杂性的同时提供真正的价值。
关键是记住,有时最简单的解决方案最有效。从基本模式开始,彻底理解您的用例,并且仅在可证明地提高系统性能或功能时才增加复杂性。