|
此版本仍在开发中,尚未被视为稳定版。为了获取最新的快照版本,请使用Spring AI 1.1.3! |
构建高效的Agent
在最近的一篇研究出版物构建高效智能体中,Anthropic 分享了关于构建高效大型语言模型(LLM)智能体的宝贵见解。这项研究特别引人关注的地方在于,它更强调简单性和可组合性,而非复杂的框架。让我们探讨一下如何使用Spring AI将这些原则转化为实际应用。

尽管模式描述和图示来源于 Anthropic 的原始出版物,但我们将重点关注如何使用 Spring AI 的功能来实现这些模式,以实现模型的可移植性和结构化输出。我们建议先阅读原始论文。
spring-ai-examples 仓库中的 agentic-patterns 目录包含了以下示例的所有代码。
智能代理系统
该研究论文在两类代理系统之间做出了重要的架构区分:
-
工作流:通过预定义的代码路径编排大语言模型(LLM)和工具的系统(例如,规范性系统)
-
智能代理:在这些系统中,大语言模型(LLM)动态地指导自身的流程和工具使用
关键在于,尽管完全自主的智能体看似很有吸引力,但对于定义明确的任务,工作流通常能提供更好的可预测性和一致性。这与企业环境中可靠性与可维护性至关重要的需求完美契合。
让我们通过五个基本模式来探讨 Spring AI 如何实现这些概念,每个模式都服务于特定的用例:
1. 链式工作流
链式工作流模式体现了将复杂任务分解为更简单、更易管理的步骤的原则。

适用场景: - 具有明确顺序步骤的任务 - 当您希望以延迟换取更高准确性时 - 当每个步骤都基于前一步骤的输出时
以下是来自 Spring AI 实现的一个实际示例:
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;
}
}
此实现展示了几个关键原则:
-
每个步骤都有明确的职责
-
上一步的输出成为下一步的输入
-
该链易于扩展和维护
2. 并行化工作流
大型语言模型可以同时处理任务,并通过编程方式聚合其输出。

适用场景: - 处理大量相似但相互独立的项目 - 需要多个独立视角的任务 - 处理时间至关重要且任务可并行化时
List<String> parallelResponse = new ParallelizationWorkflow(chatClient)
.parallel(
"Analyze how market changes will impact this stakeholder group.",
List.of(
"Customers: ...",
"Employees: ...",
"Investors: ...",
"Suppliers: ..."
),
4
);
3. 路由工作流程
路由模式实现了智能任务分配,能够针对不同类型的输入进行专门处理。

适用场景: - 具有不同类别输入的复杂任务 - 不同输入需要特殊处理时 - 分类可以被准确处理时
@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. 编排器-工作节点

适用场景: - 复杂任务,且子任务无法预先确定 - 需要采用不同方法或视角的任务 - 需要自适应解决问题的情况
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);
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. 评估器-优化器

适用场景: - 存在明确的评估标准 - 迭代优化能带来可衡量的价值 - 任务能从多轮评审中受益
public class EvaluatorOptimizerWorkflow {
public RefinedResponse loop(String task) {
Generation generation = generate(task, context);
EvaluationResponse evaluation = evaluate(generation.response(), task);
return new RefinedResponse(finalSolution, chainOfThought);
}
}
使用示例:
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 的实现优势
Spring AI 对这些模式的实现提供了多项优势,与 Anthropic 的建议相一致:
模型可移植性
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
结构化输出
EvaluationResponse response = chatClient.prompt(prompt)
.call()
.entity(EvaluationResponse.class);
一致的 API
-
不同大语言模型提供商之间的统一接口
-
内置的错误处理和重试机制
-
灵活的提示词管理
最佳实践和建议
-
从简单开始
-
先从基本的工作流程开始,再逐步增加复杂性
-
使用满足您需求的最简单模式
-
仅在需要时增加复杂性
-
可靠性设计
-
实现清晰的错误处理
-
尽可能使用类型安全的响应
-
在每一步中内置验证
-
考虑权衡
-
在延迟与准确性之间取得平衡
-
评估何时使用并行处理
-
在固定工作流和动态代理之间进行选择
未来工作
这些指南将不断更新,以探讨如何构建更高级的智能体(Agents),将这些基础模式与复杂功能相结合:
模式组合 - 组合多个模式以创建更强大的工作流 - 构建利用每种模式优势的混合系统 - 创建能够适应不断变化需求的灵活架构
高级代理内存管理 - 实现跨会话的持久性内存 - 高效管理上下文窗口 - 制定长期知识保留策略
工具与模型上下文协议 (MCP) 集成 - 通过标准化接口利用外部工具 - 实现MCP以增强模型交互 - 构建可扩展的代理架构
结论
Anthropic 的研究成果与 Spring AI 的实际应用相结合,为构建高效的基于大语言模型(LLM)的系统提供了一个强大的框架。
通过遵循这些模式和原则,开发者可以创建出健壮、可维护且高效的AI应用程序,在避免不必要复杂性的同时提供真正的价值。
关键是记住,有时最简单的解决方案才是最有效的。从基本模式开始,彻底理解你的使用场景,只有在能够明显提升系统性能或能力时才增加复杂性。