跳到主要内容
版本:2.0.1

构建有效的 Agents

QWen Max 中英对照 Building Effective Agents

在最近发布的一篇研究文章 Building Effective Agents 中,Anthropic 分享了关于构建高效大型语言模型 (LLM) 智能体的宝贵见解。这项研究特别值得关注的一点是,它强调简单性和可组合性,而非复杂框架。让我们探讨如何将这些原则转化为使用 Spring AI 的实际实现。

Agent 系统

虽然模式描述和图示来自 Anthropic 的原始出版物,但我们将重点介绍如何使用 Spring AI 的模型可移植性和结构化输出特性来实现这些模式。我们建议先阅读原始论文。

spring-ai-examples 仓库中的 agentic-patterns 目录包含以下所有示例的代码。

智能体系统​

该研究论文对两种类型的智能体系统作出了重要的架构区分:

  1. Workflows:LLMs 和工具通过预定义代码路径进行编排的系统(例如,prescriptive systems)

  2. Agents:LLMs 动态控制自身流程和工具使用的系统

关键洞察在于,虽然完全自主的 agents 可能看起来很有吸引力,但对于定义明确的任务,workflows 通常能提供更好的可预测性和一致性。这与企业级需求高度契合,在这些需求中,可靠性和可维护性至关重要。

让我们看看 Spring AI 如何通过五种基本模式实现这些概念,每种模式都服务于特定用例:

1.​

Chain Workflow 模式体现了将复杂任务分解为更简单、更易管理步骤的原则。

Prompt Chaining 工作流

何时使用: - 具有明确顺序步骤的任务 - 当你想以延迟换取更高准确率时 - 当每个步骤都基于前一个步骤的输出时

以下是 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.​

LLMs 可以同时在多个任务上工作,并且其输出可以通过程序进行聚合。

并行化工作流

适用场景: - 处理大量相似但相互独立的项目 - 需要多个独立视角的任务 - 当处理时间至关重要且任务可并行化时

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 pattern 实现了智能任务分发,使不同类型的输入能够得到专门处理。

路由工作流

适用场景: - 具有明显不同输入类别的复杂任务 - 当不同输入需要专门处理时 - 当分类可以准确处理时

@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.​

Evaluator-Optimizer 工作流

适用场景: - 存在明确的评估标准 - 迭代优化能带来可衡量的价值 - 任务能从多轮评审中受益

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-starter-model-openai</artifactId>
</dependency>

​

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

​

  • 跨不同 LLM 提供商的统一接口

  • 内置错误处理和重试

  • 灵活的 prompt 管理

最佳实践与建议​

  • 从简单开始

  • 在增加复杂性之前,先从基本工作流开始

  • 使用满足需求的最简单模式

  • 仅在需要时增加复杂度

  • 为可靠性而设计

  • 实现清晰的错误处理

  • 尽可能使用类型安全的响应

  • 在每个步骤中加入校验

  • 考虑权衡

  • 平衡延迟与准确性

  • 评估何时使用并行处理

  • 在固定工作流与动态代理之间做出选择

未来工作​

这些指南将更新,以探索如何构建更高级的 Agents,并将这些基础模式与复杂特性相结合:

模式组合 - 组合多个模式以创建更强大的工作流 - 构建混合系统,以利用每个模式的优势 - 创建能够适应需求变化的灵活架构

高级 Agent 记忆管理 - 实现跨对话的持久记忆 - 高效管理上下文窗口 - 制定长期知识保留策略

工具与 Model-Context Protocol (MCP) 集成 - 通过标准化接口利用外部工具 - 实现 MCP 以增强模型交互 - 构建可扩展的 agent 架构

结论​

Anthropic 的研究洞察与 Spring AI 的实践实现相结合,为构建有效的基于 LLM 的系统提供了强大框架。

通过遵循这些模式和原则,开发者可以构建健壮、可维护且有效的 AI 应用,在避免不必要的复杂性的同时交付实际价值。

关键是要记住,有时候最简单的解决方案才是最有效的。从基本模式开始,充分理解你的使用场景,只有在确实能提升系统性能或能力时,才增加复杂性。