← 返回课程列表

AI Agent六大设计模式

学习来源

主要学习资料

概述:从提示工程到流程工程

核心洞察

2026年,Agentic设计模式已从研究探索转变为生产必需品。 Chain-of-thought prompting让位于ReAct风格的交错推理,而框架作者们进一步扩展出能够规划、执行、反思和恢复的完全自主Agent循环。

为什么提示工程达到天花板?

单轮提示优化本质上是脆弱的。一个精心设计的提示在一个输入分布上可能表现优异,在另一个输入上却可能灾难性失败。提示缺乏状态,没有错误恢复机制,也无法根据中间结果调整行为。

根本局限是架构性的:优化LLM调用的内容是有用的,但远远不够。真正的挑战是决定调用什么、以什么顺序、用什么数据,以及当出错时该怎么办。

什么是流程工程(Flow Engineering)?

流程工程是设计LLM调用周围的控制流、状态转换和决策边界的学科。它将Agent构建视为软件架构问题。

"掌握少数可组合的设计模式,比掌握任何单一框架重要得多。框架会变,模式永存。"
— SitePoint

六大核心设计模式一览

模式 复杂度 核心用途 关键风险
ReAct 推理-行动-观察循环 无限循环
Tool Use 低-中 外部世界集成 工具滥用
Reflection 自我修正 迭代成本
Planning 多步骤任务 计划漂移
Multi-Agent 复杂工作流 协调开销
Human-in-the-Loop 安全阀机制 过度依赖人工

1 ReAct模式(Reasoning + Acting)

思考-行动-观察循环

ReAct将推理和行动结合,通过"思考-行动-观察"的循环实现复杂任务求解。这是AI Agent最基础也最重要的模式。

解决的核心问题

  • 盲目行动:无计划地执行操作,缺乏推理过程
  • 推理与行动脱节:Chain-of-Thought只推理不行动,无法与外部环境交互

ReAct将推理和行动融合,形成闭环反馈。每次观察的结果都会影响下一轮的思考和行动,实现动态调整策略。

执行流程

# ReAct 核心循环
for iteration in range(max_iterations):
    # 1. Thought - 分析当前状态,决定下一步行动
    thought = llm.invoke(f"分析: {context}\n决定下一步:")
    
    # 2. Action - 调用工具执行操作
    if "Action:" in thought:
        action = parse_action(thought)
        observation = execute_tool(action)
        context += f"\n行动: {action}\n观察: {observation}"
    
    # 3. Observation - 获取结果作为下一轮输入
    # 循环持续,直到任务完成或达到最大步数
    
    # 4. 判断是否结束
    if "Answer:" in thought:
        return extract_answer(thought)

闭环终止条件

实际案例:发送邮件

用户请求:"帮我发邮件给FanOne,让他快点更新视频"

优缺点分析

优点

  • 可解释性强:过程透明,便于调试
  • 能集成多工具
  • 能处理多步推理场景
  • 适应性强,能应对未知情况

缺点

适用场景

⚠ 实现提示:在LangGraph中实现ReAct,使用create_react_agent或自定义状态图,配合工具定义和条件边。

2 Tool Use模式(Function Calling)

🔌 连接外部世界

Tool Use让Agent能够调用外部工具、API和数据库,将LLM的能力扩展到现实世界。

四阶段循环

  1. 定义工具:使用结构化schema定义可用工具
  2. 选择调用:LLM根据任务选择并参数化工具
  3. 执行工具:调用外部系统获取结果
  4. 整合结果:将结果合并回对话上下文

2026年技术状态

当前主流包括OpenAI、Anthropic和开源模型都支持结构化工具调用,LLM返回匹配定义schema的JSON,而非需要解析的自由文本。

TypeScript实现示例

import { StateGraph, END, Annotation } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
import { ToolNode } from "@langchain/langgraph/prebuilt";

// 定义网络搜索工具
const webSearch = tool(async ({ query }) => {
    return `搜索结果: ${query}`;
}, {
    name: "web_search",
    description: "搜索网络",
    schema: z.object({ query: z.string() })
});

// 定义数据库查询工具(安全限制)
const dbQuery = tool(async ({ sql }) => {
    // 安全:仅允许SELECT语句
    if (!ALLOWED_SQL_PATTERN.test(sql.trim())) {
        return "Error: 仅允许简单SELECT查询";
    }
    return `查询结果: ${sql}`;
}, {
    name: "db_query",
    description: "查询数据库(仅SELECT)",
    schema: z.object({ sql: z.string().max(500) })
});

// 绑定工具到LLM
const tools = [webSearch, dbQuery];
const model = new ChatOpenAI({ model: "gpt-4o" })
    .bindTools(tools);

// 创建工具节点
const toolNode = new ToolNode(tools);

// 判断是否使用工具
function shouldUseTool(state) {
    const last = state.messages[state.messages.length - 1];
    return last?.tool_calls?.length > 0 ? "tools" : END;
}

// 构建状态图
const graph = new StateGraph(AgentAnnotation)
    .addNode("agent", agent)
    .addNode("tools", toolNode)
    .setEntryPoint("agent")
    .addConditionalEdges("agent", shouldUseTool, 
        { tools: "tools", [END]: END })
    .addEdge("tools", "agent")
    .compile();

安全最佳实践

⚠ 安全警告

定义数据库工具时,必须

大规模工具选择

当Agent有50+工具时,将所有schema传入每个请求变得不切实际。解决方案:

适用场景

3 Reflection模式(自我反思)

自我审视与修正

Reflection模式让Agent成为自己的评审者,通过自我评估和反馈循环迭代改进输出质量。

两种实现方式

  1. Self-Reflection:Agent自我审查自己的工作
  2. Producer-Critic Model:一个Agent生成,另一个专门Agent评审(效果更好)

核心流程

# Reflection 核心循环
# Generate → Critique → Refine

class ReflectionState:
    task: str          # 任务描述
    draft: str         # 当前草稿
    critique: str     # 评审意见
    score: int         # 质量评分(1-10)
    iteration: int     # 当前迭代次数

def generate(state):
    # 生成器:基于反馈生成/改进内容
    feedback = f"Feedback: {state['critique']}" if state["critique"] else ""
    msg = llm.invoke(f"Write: {state['task']}{feedback}")
    return {"draft": msg.content, "iteration": state["iteration"] + 1}

def critique(state):
    # 评审器:评分并提供改进建议
    msg = llm.invoke(f"Score 1-10 and critique: {state['draft']}")
    score = extract_score(msg.content)
    return {"critique": msg.content, "score": score}

def should_continue(state):
    # 终止条件:分数达标或达到最大迭代
    if state["score"] >= 8 or state["iteration"] >= 3:
        return END
    return "generate"

惊人效果

研究数据

使用Reflection模式的GPT-3.5在HumanEval基准测试中:

反思是提升输出质量最简单有效的方式。

Reflexion:Reflection的进化版

Reflexion在Reflection基础上引入强化学习外部数据

优缺点分析

优点

  • 显著提高输出质量
  • 减少错误和幻觉
  • 无需人工干预
  • 可叠加到任何Agent

缺点

适用场景

⚠ 重要提示:每次迭代都会线性增加成本。建议设置Token预算跟踪和硬性迭代上限(通常3次)。

4 Planning模式(规划-执行)

任务拆解与执行

Planning模式将复杂任务分解为可管理的步骤,创建一个执行路线图,确保任务有序高效完成。

与ReAct的对比

维度 ReAct Plan-Execute
流程定义 运行时动态生成 先规划,后固定执行
灵活性 中等
适用场景 探索性任务 固定流程任务
决策者 LLM每步决定 规划器预先决定
比喻 "探险家" "按图施工的建筑工人"

核心角色

  1. Planner(规划器):根据用户目标生成结构化任务计划
  2. Executor(执行器):执行当前计划中的步骤
  3. Replanner(重规划器):评估进度,决定是否修正计划

Python实现示例

class PlanState(TypedDict):
    objective: str              # 目标
    steps: List[dict]           # 步骤列表
    current_index: int           # 当前步骤索引
    final_result: str           # 最终结果

def planner(state):
    # 规划器:生成任务计划
    msg = llm.invoke(
        f"Break into 3-5 steps. Return ONLY numbered list.\n{state['objective']}"
    )
    # 解析步骤(只接受编号行)
    steps = [{"description": line, "status": "pending"} 
             for line in msg.content.strip().split("\n") 
             if re.match(r'^\d+[\.\)]', line)]
    return {"steps": steps, "current_index": 0}

def executor(state):
    # 执行器:执行当前步骤
    idx = state["current_index"]
    step = state["steps"][idx]
    # 累积之前的上下文
    context = "\n".join(s["result"] for s in 
                   state["steps"][:idx] if s["result"])
    msg = llm.invoke(f"Execute: {step['description']}\nContext: {context}")
    # 更新步骤状态
    steps = list(state["steps"])
    steps[idx] = {"status": "done", "result": msg.content}
    return {"steps": steps, "current_index": idx + 1}

def replanner(state):
    # 重规划器:失败时调整计划
    completed = [s for s in state["steps"] if s["status"] == "done"]
    msg = llm.invoke(f"Revise remaining steps:\n{formatted(completed)}")
    # ... 解析并更新步骤
    return new_state

def route_after_execute(state):
    if state["current_index"] >= len(state["steps"]):
        return "aggregator"  # 完成
    if state["steps"][state["current_index" - 1].get("status") == "failed":
        return "replanner"   # 失败,重规划
    return "executor"      # 继续执行

实际案例:购物比价

用户请求:"帮我看看哪个平台买iPhone 17便宜"

处理计划漂移

计划执行中,上下文可能偏离初始假设。应对策略:

优缺点分析

优点

  • 结构清晰,可视化为工作流图
  • Planner和Executor可分别优化
  • 易于调试和监控
  • 适合明确流程的任务

缺点

适用场景

5 Multi-Agent模式(多智能体协作)

专业Agent协同

Multi-Agent模式让多个拥有不同角色和专长的Agent互相通信、协作,解决单体Agent难以处理的超复杂任务。

三种主要拓扑

1. Supervisor模式(集中式协调)

一个Supervisor Agent统一管理多个SubAgent:

2. Peer-to-Peer模式(对等协作)

Agents作为平等节点,通过消息总线协作:

3. Debate模式(对抗辩论)

多个Agent针对同一问题提出不同观点:

CrewAI实现示例

from crewai import Agent, Task, Crew, Process

# 定义专业Agent
researcher = Agent(
    role="资深研究员",
    goal="为给定的主题进行深入调研,发现准确可靠的信息",
    backstory="你是在信息检索和事实核查方面经验丰富的专家",
    verbose=True
)

analyst = Agent(
    role="数据分析师",
    goal="分析研究员提供的数据和信息,提炼洞见和趋势",
    backstory="你擅长从复杂信息中提取关键点并进行逻辑推理",
    verbose=True
)

writer = Agent(
    role="技术作家",
    goal="根据研究员和分析师的工作,撰写清晰、引人入胜的报告",
    backstory="你擅长将技术内容转化为易于理解的文章",
    verbose=True
)

# 定义任务
research_task = Task(
    description="调查人工智能在2026年的主要突破",
    expected_output="一份包含关键事实和来源的调研笔记",
    agent=researcher
)

analysis_task = Task(
    description="分析这些突破对医疗、金融、教育行业的潜在影响",
    expected_output="一份趋势分析和风险评估",
    agent=analyst,
    context=[research_task]  # 依赖researcher
)

write_task = Task(
    description="撰写一篇面向科技爱好者的博客文章",
    expected_output="一篇约500字的博客文章",
    agent=writer,
    context=[research_task, analysis_task]
)

# 组建团队
tech_crew = Crew(
    agents=[researcher, analyst, writer],
    tasks=[research_task, analysis_task, write_task],
    process=Process.sequential,  # 顺序执行
    verbose=2
)

# 启动
result = tech_crew.kickoff()
print(result)

LangGraph实现Supervisor模式

class MultiAgentState(TypedDict):
    messages: Annotated[List[dict], operator.add]  # 累积消息
    turn_count: int
    consensus: bool

def researcher(state):
    history = format_messages(state["messages"])
    msg = llm.invoke(f"You are a Researcher. Provide analysis.\n{history}")
    return {"messages": [{"role": "researcher", "content": msg.content}]}

def critic(state):
    history = format_messages(state["messages"])
    msg = llm.invoke(f"You are a Critic. Challenge weaknesses.\n{history}")
    return {"messages": [{"role": "critic", "content": msg.content}]}

def supervisor(state):
    # 评估是否达成共识
    msg = llm.invoke(f"Have these agents reached consensus? Reply YES or NO.\n{history}")
    consensus = "YES" in msg.content.upper()
    return {"consensus": consensus}

def route(state):
    if state["consensus"] or state["turn_count"] >= 6:
        return END
    return "researcher"

# 构建图
graph = StateGraph(MultiAgentState)
graph.add_node("researcher", researcher)
graph.add_node("critic", critic)
graph.add_node("supervisor", supervisor)
graph.set_entry_point("researcher")
graph.add_edge("researcher", "critic")
graph.add_edge("critic", "supervisor")
graph.add_conditional_edges("supervisor", route, {END: END, "researcher": "researcher"})

实际案例:代码开发团队

用户请求:"帮我写一个贪吃蛇游戏,并确保没有Bug"

协调挑战

优缺点分析

优点

  • 专业分工,专注力强
  • 能处理超复杂任务
  • 模拟人类团队工作流
  • 可扩展性强

缺点

适用场景

6 Human-in-the-Loop模式(人机协同)

🛡 安全阀机制

Human-in-the-Loop不追求完全自动化,而是将人类决策者嵌入关键链路,确保系统安全、可控、负责任。

为什么需要HITL?

  1. 安全性:防止Agent执行不可逆或有害的操作
  2. 质量保证:允许人类审核和批准生成的内容
  3. 处理歧义:当Agent遇到无法自主解决的情况时提供指导

三种常见形式

1. 多候选方案 + 人工选择

Agent输出多个选项,人类选一并可修改

2. 自动初审 + 人工复审

Agent做风险初筛,标记可疑项;人类只处理高风险项

3. 人工反馈驱动改进

人类对Agent输出给出评价,作为后续优化依据

LangGraph实现:静态中断

# 静态中断:在预定节点前暂停
from langgraph.checkpoint.memory import MemorySaver

# 编译图时设置中断点
graph = builder.compile(
    interrupt_before=["assistant"],  # 在assistant节点前中断
    checkpointer=MemorySaver()
)

# 人工干预:更新状态
graph.update_state(
    config,
    {"messages": [HumanMessage(content="补充:查找量子计算专利")]}
)

LangGraph实现:动态中断

# 动态中断:在节点内基于状态暂停
from langgraph.types import interrupt

def human_in_the_loop(state):
    # 从用户获取输入
    value = interrupt("您想修改输入还是继续?")
    return {"messages": value}

# 构建新图
new_builder = StateGraph(AgentState)
new_builder.add_node("human_in_the_loop", human_in_the_loop)
# ... 添加其他节点
new_builder.add_edge("guardian", "human_in_the_loop")
new_builder.add_edge("human_in_the_loop", "assistant")

ARIA:自改进Agent框架

ARIA(Adaptive Reflective Interactive Agent)是TikTok Pay部署的框架:

在TikTok Pay(服务1.5亿月活用户)上验证,显著提升适应性和准确性。

实际案例:专利检索助手

典型工作流

  1. Guardian节点:检测有害内容
  2. 安全内容:传递给Assistant → 执行工具调用
  3. 关键决策点:触发Human-in-the-Loop
  4. 人类审核:确认/修改/拒绝
  5. 继续执行:基于人类反馈继续

优缺点分析

优点

  • 显著降低风险
  • 业务团队更易接受AI
  • 利于积累高质量反馈数据
  • 适合高风险/高责任场景

缺点

适用场景

最佳实践

不要追求完全自动化。在关键链路中嵌入人工检查点,既保证安全性,又能利用AI的效率优势。

六大模式对比总结

模式 复杂度 核心问题 最佳拍档 适用场景
ReAct 动态推理决策 Tool Use 探索性任务、复杂问答
Tool Use 低-中 连接外部世界 ReAct API调用、数据库查询
Reflection 自我质量提升 任意模式 代码生成、内容创作
Planning 结构化执行 Replanner 固定流程、长链路任务
Multi-Agent 复杂协作 Supervisor 多领域专家协作
Human-in-the-Loop 安全可控 任意模式 高风险决策、内容审核

决策树:如何选择?

# 模式选择决策树
if 任务需要外部数据:
    → 使用 Tool Use
    
elif 输出质量是瓶颈:
    → 使用 Reflection
    
elif 任务流程明确固定:
    → 使用 Planning
    
elif 需要多领域专家协作:
    → 使用 Multi-Agent
    
elif 高风险/高价值任务:
    → 使用 Human-in-the-Loop
    
else:
    → 使用 ReAct 作为起点

模式组合建议

真实系统很少使用单一模式

一个生产级研究Agent可能组合:

建议:从解决核心问题的最简单模式开始,只有当特定失败模式需要时才叠加额外模式。

💭 对看宝AI项目的实践建议

迁移建议总览

基于六大设计模式,为看宝AI项目提供以下架构升级建议:

1. 基础问答系统 → ReAct + Tool Use

当前痛点:

建议方案:

# 看宝AI 基础Agent架构
# 组合ReAct + Tool Use

# 工具定义
tools = [
    kanbao_search,      # 知识库搜索
    web_search,         # 网络搜索
    user_profile,       # 用户画像查询
    conversation_history # 历史对话检索
]

# ReAct Agent
react_agent = create_react_agent(llm, tools)
agent_executor = AgentExecutor(
    agent=react_agent,
    tools=tools,
    max_iterations=10,
    handle_parsing_errors=True
)

预期收益:

2. 内容生成 → Reflection模式

# 看宝AI 内容生成Agent
# 使用Reflection提升质量

class ContentAgent:
    def generate(self, prompt):
        # 生成 → 评审 → 改进循环
        draft = self.first_draft(prompt)
        for i in range(3):
            critique = self.critique(draft)
            if critique.score >= 8:
                break
            draft = self.improve(draft, critique.feedback)
        return draft

适用场景:

3. 复杂任务 → Planning模式

# 看宝AI 复杂任务处理
# 学习计划制定 → Planning模式

# Plan: [了解水平] → [推荐课程] → [制定计划] → [设置提醒]

class LearningPlanWorkflow:
    def create_plan(self, user_goal):
        # 1. 评估用户当前水平
        current_level = self.assess_user(user_goal)
        
        # 2. 推荐学习路径
        learning_path = self.recommend_path(current_level, user_goal)
        
        # 3. 分解为周计划
        weekly_plan = self.break_down(learning_path)
        
        # 4. 设置里程碑和提醒
        milestones = self.create_milestones(weekly_plan)
        
        return {
            "level": current_level,
            "path": learning_path,
            "plan": weekly_plan,
            "milestones": milestones
        }

4. 团队协作 → Multi-Agent模式

# 看宝AI 多Agent协作

# 角色定义
researcher = Agent(role="学习研究员", goal="收集最新AI知识")
teacher = Agent(role="教学设计师", goal="设计学习内容")
coach = Agent(role="学习教练", goal="跟踪进度和激励")

# 协作流程
def kanbao_team(user_goal):
    # 研究员:调研最新资料
    resources = researcher.research(user_goal)
    
    # 教师:设计学习路径
    curriculum = teacher.design(resources, user_goal)
    
    # 教练:制定执行计划
    plan = coach.plan(curriculum)
    
    return plan

5. 敏感操作 → Human-in-the-Loop

# 看宝AI 高风险操作

# 需要人工确认的场景
high_risk_operations = [
    "删除用户数据",
    "发送外部邮件",
    "修改系统设置",
    "生成公开内容"
]

def check_with_human(operation):
    if operation.type in high_risk_operations:
        # 触发人工确认
        confirm = interrupt(f"即将执行: {operation.description}")
        if not confirm:
            return "CANCELLED"
    return execute(operation)

6. 渐进式架构升级路线

推荐升级路径

  1. Phase 1(立即):为现有Agent添加Tool Use能力
  2. Phase 2(1周):对内容生成添加Reflection循环
  3. Phase 3(2周):实现基础Planning工作流
  4. Phase 4(1月):引入Multi-Agent协作
  5. 持续优化:根据场景添加Human-in-the-Loop

⚠ 注意事项