此版本仍在开发中,尚未被视为稳定版。如需最新的快照版本,请使用 Spring AI 1.1.3spring-doc.cadn.net.cn

构建有效的代理

在最近的一篇研究出版物中,构建有效的代理,Anthropic 分享了关于构建有效大型语言模型(LLM)代理的宝贵见解。这项研究之所以特别有趣,是因为它强调简单性和可组合性,而非复杂的框架。让我们探讨这些原则如何使用 Spring AI 转化为实际实现。spring-doc.cadn.net.cn

Agent Systems

虽然模式描述和图表来源于 Anthropic 的原始出版物,但我们将重点介绍如何使用 Spring AI 的模型可移植性和结构化输出功能来实现这些模式。我们建议先阅读原始论文。spring-doc.cadn.net.cn

spring-ai-examples 仓库中的 agentic-patterns 目录包含了以下所有示例的代码。spring-doc.cadn.net.cn

智能系统

该研究出版物在两种代理系统之间做出了重要的架构区分:spring-doc.cadn.net.cn

  1. 工作流:通过预定义代码路径编排 LLM 和工具的系统(例如,规定性系统)spring-doc.cadn.net.cn

  2. 代理:大语言模型(LLM)动态指导自身流程和工具使用的系统spring-doc.cadn.net.cn

关键在于,虽然完全自主的智能体可能看起来很吸引人,但对于定义明确的任务,工作流通常能提供更好的可预测性和一致性。这与企业需求完美契合,因为可靠性和可维护性对企业至关重要。spring-doc.cadn.net.cn

让我们看看Spring AI如何通过五种基本模式来实现这些概念,每种模式都服务于特定的用例:spring-doc.cadn.net.cn

1. 链式工作流

链式工作流模式体现了将复杂任务分解为更简单、更易于管理的步骤的原则。spring-doc.cadn.net.cn

Prompt Chaining Workflow

何时使用: - 具有明确顺序步骤的任务 - 当您希望以延迟换取更高准确性时 - 当每个步骤都建立在前一个步骤的输出之上时spring-doc.cadn.net.cn

这是 Spring AI 实现中的一个实际示例:spring-doc.cadn.net.cn

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;
    }
}

此实现展示了几个关键原则:spring-doc.cadn.net.cn

2. 并行化工作流

LLM 可以同时处理任务,并以编程方式汇总其输出。spring-doc.cadn.net.cn

Parallelization Workflow

何时使用: - 处理大量相似但独立的项目 - 需要多个独立视角的任务 - 当处理时间至关重要且任务可并行化时spring-doc.cadn.net.cn

List<String> parallelResponse = new ParallelizationWorkflow(chatClient)
    .parallel(
        "Analyze how market changes will impact this stakeholder group.",
        List.of(
            "Customers: ...",
            "Employees: ...",
            "Investors: ...",
            "Suppliers: ..."
        ),
        4
    );

3. 路由工作流

路由模式实现了智能任务分发,能够针对不同类型的输入进行专门处理。spring-doc.cadn.net.cn

Routing Workflow

何时使用: - 具有不同输入类别的复杂任务 - 当不同输入需要专门处理时 - 当分类可以准确处理时spring-doc.cadn.net.cn

@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

Orchestration Workflow

何时使用: - 子任务无法预先预测的复杂任务 - 需要不同方法或视角的任务 - 需要适应性问题解决的情况spring-doc.cadn.net.cn

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(/*...*/);
    }
}

使用示例:spring-doc.cadn.net.cn

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

Evaluator-Optimizer Workflow

何时使用: - 存在明确的评估标准 - 迭代优化可提供可衡量的价值 - 任务可从多轮批评中受益spring-doc.cadn.net.cn

public class EvaluatorOptimizerWorkflow {
    public RefinedResponse loop(String task) {
        Generation generation = generate(task, context);
        EvaluationResponse evaluation = evaluate(generation.response(), task);
        return new RefinedResponse(finalSolution, chainOfThought);
    }
}

使用示例:spring-doc.cadn.net.cn

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 建议的优势:spring-doc.cadn.net.cn

模型可移植性

<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

最佳实践和建议

未来工作

这些指南将进行更新,以探讨如何构建更高级的代理,这些代理将结合这些基础模式与复杂功能:spring-doc.cadn.net.cn

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

高级代理内存管理 - 在对话中实现持久化内存 - 高效管理上下文窗口 - 开发长期知识保留策略spring-doc.cadn.net.cn

工具和模型上下文协议 (MCP) 集成 - 通过标准化接口利用外部工具 - 实现 MCP 以增强模型交互 - 构建可扩展的代理架构spring-doc.cadn.net.cn

结论

Anthropic 的研究见解与 Spring AI 的实际实现相结合,为构建基于 LLM 的有效系统提供了强大的框架。spring-doc.cadn.net.cn

通过遵循这些模式和原则,开发者可以创建健壮、可维护且高效的AI应用程序,这些应用程序能够提供真正的价值,同时避免不必要的复杂性。spring-doc.cadn.net.cn

关键是要记住,有时最简单的解决方案是最有效的。从基本模式开始,彻底理解你的用例,只有在明显提高系统性能或能力时才增加复杂性。spring-doc.cadn.net.cn