|
最新快照版本请使用Spring AI 1.1.0! |
打造高效的代理
在最近的研究出版物《构建有效代理》中,Anthropic分享了关于构建高效大型语言模型(LLM)代理的宝贵见解。这项研究特别有趣的是它强调简洁性和可组合性,而非复杂框架。让我们一起探讨这些原则如何转化为使用 Spring AI 的实际实现。
虽然图案描述和图表均来自Anthropic的原始出版物,但我们将重点讲述如何利用Spring AI的模型可移植性和结构化输出功能实现这些图案。我们建议先阅读原始论文。
spring-ai-examples 仓库中的 agentic-patterns 目录包含了以下示例的所有代码。
代理系统
该研究出版物在结构上对两种智能系统类型做出了重要区分:
-
工作流程:通过预定义代码路径(例如规范性系统)编排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. 并行化工作流程
LLM可以同时处理任务,并以程序化方式汇总输出。
使用时机:- 处理大量相似但独立的项目- 需要多个独立视角的任务- 处理时间关键且任务可并行化时
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
-
不同LLM提供者间的统一接口
-
内置错误处理与重试
-
灵活的提示管理
最佳实践与建议
-
从简单开始
-
先从基础工作流程开始,再增加复杂度
-
使用最简单的图案,满足你的需求
-
只有在需要时才添加复杂性
-
可靠性设计
-
实现清晰的错误处理
-
尽可能使用类型安全响应
-
在每个步骤都内置验证
-
考虑权衡
-
平衡延迟与准确性
-
评估何时使用并行处理
-
在固定工作流程和动态客服之间选择
未来工作
本指南将不断更新,探索如何构建更高级的代理,将这些基础模式与复杂功能结合起来:
模式组合- 结合多种模式以创建更强大的工作流程- 构建利用每种模式优势的混合系统- 创建能够适应不断变化需求的灵活架构
高级代理内存管理- 跨对话实现持久内存- 高效管理上下文窗口- 制定长期知识保留策略
工具与模型-上下文协议(MCP)集成- 通过标准化接口利用外部工具- 实现MCP以增强模型交互- 构建可扩展代理架构
结论
Anthropic的研究见解与Spring AI的实际实现相结合,为构建高效的基于LLM的系统提供了强大的框架。
遵循这些模式和原则,开发者可以创建稳健、可维护且高效的AI应用,既能带来真正的价值,又避免不必要的复杂性。
关键是记住,有时最简单的解决方案反而是最有效的。从基本模式开始,彻底理解你的用例,只有当复杂度明显提升了系统的性能或能力时才添加。