Agent 架构模式详解 概述 AI Agent(智能体) 是能够自主感知环境、做出决策并执行行动的 AI 系统。与普通的 LLM 对话不同,Agent 能够调用外部工具、访问数据库、执行代码,真正完成任务。
💡 提示: 核心区别 普通 LLM :只能生成文本Agent :能思考 + 行动 + 获取反馈 + 继续思考
Agent 核心组件 graph TB
subgraph Agent
A[LLM 大脑] --> B[规划模块]
A --> C[记忆模块]
A --> D[工具模块]
end
D --> E[搜索工具]
D --> F[代码执行]
D --> G[数据库]
D --> H[API调用]
C --> I[短期记忆]
C --> J[长期记忆]
组件
功能
技术实现
LLM 大脑
理解、推理、决策
GPT-4、Claude、通义千问
规划模块
任务分解、执行策略
ReAct、Plan-and-Execute
记忆模块
存储上下文、历史经验
向量数据库、Redis
工具模块
与外部世界交互
Function Calling
一、ReAct 模式 1.1 核心思想 ReAct = Reasoning(推理) + Acting(行动)
交替进行思考和行动,每一步都根据上一步的结果决定下一步。
1.2 执行流程 graph TD
A[用户问题] --> B[Thought: 我需要做什么?]
B --> C[Action: 调用工具]
C --> D[Observation: 观察结果]
D --> E{任务完成?}
E -->|否| B
E -->|是| F[Final Answer: 最终回答]
1.3 Prompt 模板 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 你是一个能使用工具的 AI 助手。 可用工具: 1. search(query) - 搜索网络信息 2. calculator(expression) - 计算数学表达式 3. get_weather(city) - 获取城市天气 4. run_code(code) - 执行 Python 代码 请严格按照以下格式回答: Thought : 思考当前应该做什么 Action : 工具名称 Action Input : 工具参数(JSON格式) Observation : [系统返回工具执行结果] ...(重复 Thought/Action/Observation 直到任务完成) Thought : 我已经获得了足够的信息 Final Answer : 最终答案 注意:- 每次只能调用一个工具 - 必须等待 Observation 后再继续思考 - 不要编造 Observation,等待系统返回 用户问题:{question}
1.4 执行示例 用户问 :”帮我查一下上海今天的天气,如果气温超过30度,帮我计算需要喝多少水(体重70kg,每公斤40ml)”
1 2 3 4 5 6 7 8 9 10 11 12 Thought : 我需要先查询上海的天气,获取温度信息Action : get_weatherAction Input: {"city" : "上海" }Observation : {"city" : "上海" , "temperature" : 35 , "humidity" : 75 , "condition" : "晴" }Thought : 上海气温35 度,超过30 度了。现在我需要计算喝水量:70 kg × 40 ml = 2800 mlAction : calculatorAction Input: {"expression" : "70 * 40" }Observation : 2800 Thought : 我已经获得了所有需要的信息Final Answer: 上海今天天气晴朗,气温35 °C,湿度75 %。由于气温超过30 度,建议您多补充水分。按照您的体重70 kg计算,今天建议饮水量为2800 ml(约2 .8 升)。
1.5 Spring AI 实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 @Configuration public class AgentConfig { @Bean public ChatClient chatClient (ChatClient.Builder builder, WeatherTool weatherTool, CalculatorTool calculatorTool) { return builder .defaultSystem(""" 你是一个智能助手,可以使用工具来帮助用户。 请仔细分析用户的问题,选择合适的工具来获取信息。 """ ) .defaultTools(weatherTool, calculatorTool) .build(); } }@Component public class WeatherTool { @Tool(description = "获取指定城市的天气信息,返回温度、湿度等") public WeatherInfo getWeather ( @ToolParam(description = "城市名称,如:北京、上海") String city ) { return weatherApi.query(city); } }@Component public class CalculatorTool { @Tool(description = "计算数学表达式,支持加减乘除") public Double calculator ( @ToolParam(description = "数学表达式,如:70 * 40") String expression ) { ScriptEngine engine = new ScriptEngineManager () .getEngineByName("JavaScript" ); return ((Number) engine.eval(expression)).doubleValue(); } }@RestController public class AgentController { private final ChatClient chatClient; @PostMapping("/agent/chat") public String chat (@RequestBody String question) { return chatClient.prompt() .user(question) .call() .content(); } }
1.6 ReAct 优缺点
优点
缺点
实现简单直观
可能走弯路,效率不高
灵活性高,可随时调整
复杂任务容易迷失方向
适合探索性任务
Token 消耗较多
中间过程可观察
长任务容易超出上下文
二、Plan-and-Execute 模式 2.1 核心思想 先规划,后执行 。将复杂任务分解为多个子任务,然后按计划逐步执行。
2.2 执行流程 graph TD
A[用户问题] --> B[Planner: 分析任务]
B --> C[生成执行计划]
C --> D[Executor: 执行步骤1]
D --> E[Executor: 执行步骤2]
E --> F[Executor: 执行步骤N]
F --> G{执行结果符合预期?}
G -->|否| H[Replanner: 调整计划]
H --> C
G -->|是| I[汇总结果]
I --> J[Final Answer]
2.3 双 Agent 架构 graph LR
subgraph Planner Agent
A[任务分析] --> B[计划生成]
B --> C[计划优化]
end
subgraph Executor Agent
D[接收步骤] --> E[执行工具]
E --> F[返回结果]
end
C --> D
F --> G{需要重新规划?}
G -->|是| A
G -->|否| H[完成]
2.4 Planner Prompt 模板 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 你是一个任务规划专家。请根据用户的问题,制定详细的执行计划。1 . 将复杂任务分解为简单的子步骤2 . 每个步骤应该是原子性的、可执行的3 . 步骤之间要有清晰的依赖关系4 . 考虑可能的失败情况和备选方案 - search(query): 搜索网络信息 - read_file(path): 读取文件内容 - write_file(path, content): 写入文件 - run_code(language, code): 执行代码 - api_call(url, method , data ): 调用 API ## 输出格式 请以 JSON 格式输出计划: ```json { "goal" : "任务目标描述" , "steps" : [ { "id" : 1 , "description" : "步骤描述" , "tool" : "工具名称" , "params" : {"参数" : "值" }, "depends_on" : [], "expected_output" : "预期输出" } ], "success_criteria" : "成功标准" }
用户问题:{question}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 ### 2.5 执行示例 **用户问**:"帮我调研 Spring AI 框架,写一份技术选型报告" #### Planner 输出 ```json { "goal" : "完成 Spring AI 框架技术选型报告" , "steps" : [ { "id" : 1 , "description" : "搜索 Spring AI 官方文档和基本介绍" , "tool" : "search" , "params" : {"query" : "Spring AI official documentation introduction" }, "depends_on" : [], "expected_output" : "Spring AI 基本概念和特性" }, { "id" : 2 , "description" : "搜索 Spring AI 最新版本和更新内容" , "tool" : "search" , "params" : {"query" : "Spring AI latest version features 2024" }, "depends_on" : [], "expected_output" : "版本信息和新特性" }, { "id" : 3 , "description" : "搜索 Spring AI 与 LangChain4j 对比" , "tool" : "search" , "params" : {"query" : "Spring AI vs LangChain4j comparison" }, "depends_on" : [], "expected_output" : "框架对比分析" }, { "id" : 4 , "description" : "搜索 Spring AI 实际应用案例" , "tool" : "search" , "params" : {"query" : "Spring AI production use cases" }, "depends_on" : [], "expected_output" : "企业应用案例" }, { "id" : 5 , "description" : "整合所有信息,生成技术选型报告" , "tool" : "generate_report" , "params" : {"template" : "tech_selection" }, "depends_on" : [1 , 2 , 3 , 4 ], "expected_output" : "完整的技术选型报告" } ], "success_criteria" : "报告包含框架介绍、特性分析、对比评估、应用建议" }
Executor 执行 1 2 3 4 5 6 7 8 === 执行步骤 1-4(可并行)=== Step 1 结果: Spring AI 是 Spring 官方的 AI 集成框架... Step 2 结果: 最新版本 1.0.0,支持多种模型提供商... Step 3 结果: Spring AI 更注重 Spring 生态集成... Step 4 结果: 某电商公司使用 Spring AI 构建智能客服...=== 执行步骤 5 === [生成完整报告]
2.6 Java 实现框架 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 @Service public class PlanAndExecuteAgent { private final ChatClient plannerClient; private final ChatClient executorClient; private final ToolRegistry toolRegistry; public String execute (String question) { Plan plan = generatePlan(question); Map<Integer, StepResult> results = new HashMap <>(); for (Step step : plan.getSteps()) { if (!checkDependencies(step, results)) { continue ; } StepResult result = executeStep(step, results); results.put(step.getId(), result); if (result.needsReplan()) { plan = replan(question, plan, results); } } return summarize(question, results); } private Plan generatePlan (String question) { String response = plannerClient.prompt() .system(PLANNER_PROMPT) .user(question) .call() .content(); return parseJson(response, Plan.class); } private StepResult executeStep (Step step, Map<Integer, StepResult> context) { Tool tool = toolRegistry.get(step.getTool()); return tool.execute(step.getParams(), context); } }@Data public class Plan { private String goal; private List<Step> steps; private String successCriteria; }@Data public class Step { private Integer id; private String description; private String tool; private Map<String, Object> params; private List<Integer> dependsOn; private String expectedOutput; }
2.7 Plan-and-Execute 优缺点
优点
缺点
全局视角,不易迷失
初始规划可能不够准确
可并行执行独立步骤
需要额外的规划开销
复杂任务效率高
灵活性相对较低
易于追踪和调试
实现复杂度较高
三、其他 Agent 模式 3.1 Reflexion(反思模式) 核心思想 :执行后进行自我反思,从错误中学习。
graph TD
A[执行任务] --> B[评估结果]
B --> C{成功?}
C -->|是| D[完成]
C -->|否| E[反思: 为什么失败?]
E --> F[总结经验教训]
F --> G[改进策略]
G --> A
Prompt 示例 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ## 任务 {task} ## 上次尝试 {previous_attempt} ## 执行结果 {result} ## 反思 请分析上次尝试为什么没有达到预期效果:1. 哪些步骤是正确的?2. 哪些步骤需要改进?3. 有什么遗漏的信息? ## 改进计划 基于反思,制定新的执行计划:
3.2 LATS(Language Agent Tree Search) 核心思想 :结合蒙特卡洛树搜索(MCTS),探索多个执行路径。
graph TD
A[根节点: 问题] --> B[方案A]
A --> C[方案B]
A --> D[方案C]
B --> E[A1]
B --> F[A2]
C --> G[B1]
C --> H[B2]
style E fill:#90EE90
style H fill:#90EE90
执行流程 :
选择 :选择最有希望的节点
扩展 :生成可能的下一步
模拟 :模拟执行到结束
回溯 :更新路径上节点的评分
3.3 Multi-Agent(多智能体) 核心思想 :多个专业 Agent 协作完成任务。
graph TB
A[用户问题] --> B[Orchestrator]
B --> C[Research Agent]
B --> D[Coding Agent]
B --> E[Review Agent]
C --> F[搜索/阅读]
D --> G[编写代码]
E --> H[代码审查]
F --> B
G --> B
H --> B
B --> I[最终结果]
角色分工示例 :
Agent
职责
工具
Orchestrator
任务分发、结果汇总
无
Research Agent
信息收集、调研
search、read_url
Coding Agent
代码编写
code_interpreter
Review Agent
代码审查、质量检查
static_analysis
Test Agent
编写和运行测试
test_runner
Spring AI 多 Agent 实现 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 @Service public class MultiAgentOrchestrator { private final Map<String, Agent> agents; public String orchestrate (String task) { List<AgentTask> agentTasks = analyzeTask(task); Map<String, CompletableFuture<String>> futures = new HashMap <>(); for (AgentTask agentTask : agentTasks) { Agent agent = agents.get(agentTask.getAgentType()); futures.put(agentTask.getId(), CompletableFuture.supplyAsync(() -> agent.execute(agentTask.getPrompt()) ) ); } Map<String, String> results = futures.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, e -> e.getValue().join() )); return synthesize(task, results); } }public interface Agent { String execute (String prompt) ; }@Component("research") public class ResearchAgent implements Agent { private final ChatClient chatClient; private final SearchTool searchTool; @Override public String execute (String prompt) { return chatClient.prompt() .system("你是一个研究专家,善于收集和整理信息" ) .user(prompt) .tools(searchTool) .call() .content(); } }
3.4 AutoGPT 模式 核心思想 :全自动任务执行,最少人工干预。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 目标:{goal} 约束:1. 每次只能执行一个动作2. 必须在 10 步内完成3. 遇到不确定时询问用户 当前状态:{current_state} 已完成步骤:{completed_ steps} 可用工具:{tools} 请决定下一步动作:1. 思考当前进度2. 选择下一个动作3. 执行并观察结果4. 判断是否完成目标
四、模式选择指南 4.1 场景匹配
场景
推荐模式
原因
简单问答 + 单工具
ReAct
直接高效
多步骤复杂任务
Plan-and-Execute
需要全局规划
需要试错的任务
Reflexion
从错误中学习
有多种解决方案
LATS
探索最优路径
大型复杂项目
Multi-Agent
专业分工协作
4.2 决策流程图 graph TD
A[任务类型?] --> B{单步骤?}
B -->|是| C[直接调用 LLM]
B -->|否| D{步骤数量?}
D -->|2-5步| E[ReAct]
D -->|5+步| F{需要并行?}
F -->|是| G[Plan-and-Execute]
F -->|否| H{可能失败?}
H -->|是| I[Reflexion]
H -->|否| E
五、最佳实践 5.1 工具设计原则 1 2 3 4 5 6 7 8 9 10 @Tool(description = "搜索指定城市的天气信息,返回温度(摄氏度)、湿度、天气状况") public WeatherInfo getWeather ( @ToolParam(description = "城市名称,支持中文,如:北京、上海") String city ) { ... }@Tool(description = "获取天气") public Object weather (String c) { ... }
工具设计要点 :
描述清晰,包含输入输出说明
参数命名有意义
返回类型明确
单一职责
5.2 记忆管理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 @Service public class AgentMemory { private final VectorStore vectorStore; private final List<Message> shortTermMemory = new ArrayList <>(); public void addToShortTerm (Message message) { shortTermMemory.add(message); if (shortTermMemory.size() > MAX_SHORT_TERM) { summarizeAndArchive(); } } public void addToLongTerm (String content, Map<String, Object> metadata) { Document doc = new Document (content, metadata); vectorStore.add(List.of(doc)); } public List<Document> recall (String query, int topK) { return vectorStore.similaritySearch( SearchRequest.query(query).withTopK(topK) ); } }
5.3 错误处理 1 2 3 4 5 6 7 8 9 10 11 12 13 @Tool(description = "执行网络搜索") public SearchResult search (String query) { try { return searchApi.search(query); } catch (RateLimitException e) { return SearchResult.error("搜索服务繁忙,请稍后重试" ); } catch (NetworkException e) { return SearchResult.error("网络连接失败,请检查网络" ); } catch (Exception e) { log.error("搜索异常" , e); return SearchResult.error("搜索失败:" + e.getMessage()); } }
5.4 监控与追踪 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 @Aspect @Component public class AgentTracingAspect { @Around("@annotation(Tool)") public Object traceToolCall (ProceedingJoinPoint pjp) throws Throwable { String toolName = pjp.getSignature().getName(); Object[] args = pjp.getArgs(); long start = System.currentTimeMillis(); try { Object result = pjp.proceed(); log.info("Tool: {}, Args: {}, Result: {}, Time: {}ms" , toolName, args, result, System.currentTimeMillis() - start); return result; } catch (Exception e) { log.error("Tool: {} failed" , toolName, e); throw e; } } }
六、实战项目 6.1 智能代码助手 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @Service public class CodeAssistantAgent { private final ChatClient chatClient; @Tool(description = "读取项目中的源代码文件") public String readCode (String filePath) { ... } @Tool(description = "在项目中搜索代码") public List<SearchHit> searchCode (String query) { ... } @Tool(description = "执行单元测试") public TestResult runTests (String testClass) { ... } @Tool(description = "静态代码分析") public List<Issue> analyzeCode (String filePath) { ... } public String assist (String question) { return chatClient.prompt() .system(""" 你是一个专业的代码助手,可以: 1. 阅读和理解代码 2. 搜索相关代码片段 3. 运行测试验证 4. 分析代码质量 请根据用户问题,合理使用工具来提供帮助。 """ ) .user(question) .call() .content(); } }
6.2 自动化运维 Agent 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Service public class OpsAgent { @Tool(description = "查询服务器指标:CPU、内存、磁盘使用率") public ServerMetrics getMetrics (String serverIp) { ... } @Tool(description = "查看应用日志,支持时间范围和关键字过滤") public List<LogEntry> getLogs (String app, String keyword, int minutes) { ... } @Tool(description = "重启指定服务") public RestartResult restartService (String serviceName) { ... } @Tool(description = "执行 SQL 查询(只读)") public QueryResult queryDatabase (String sql) { ... } }
相关笔记
大模型学习路线
Prompt Engineering详解
RAG技术详解