惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 司徒正美
大猫的无限游戏
大猫的无限游戏
腾讯CDC
J
Java Code Geeks
博客园 - 【当耐特】
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
人人都是产品经理
人人都是产品经理
博客园 - Franky
博客园 - 聂微东
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
云风的 BLOG
云风的 BLOG
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
U
Unit 42
雷峰网
雷峰网
B
Blog RSS Feed
博客园_首页
量子位
F
Fortinet All Blogs
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog

人人都是产品经理

为什么你的产品找不到差异化?90%的失败都卡在第一步上(下) – 人人都是产品经理, 3年从30万到1300万用户、获2200万美元融资,这个AI教育产品用“抽卡”破解了获客难题 – 人人都是产品经理, 园区招商系统怎么做才能真正帮到去化?我加了这一个功能,推广链接转发400次阅读过万 – 人人都是产品经理, AI大事件:OpenAI发完网络安全模型又搞药物研发,小鹏汽车要抓”DeepSeek时刻” – 人人都是产品经理, 电商不是卖货,是一场更残酷的产品经理实战 – 人人都是产品经理, 没想到,活动营销又回来了! – 人人都是产品经理, 为何All-in海外KOC:一场关于AI时代窗口期的豪赌 – 人人都是产品经理, 重新理解企业的内部协作 – 人人都是产品经理, 苹果的 AI 战略到底是什么? – 人人都是产品经理, 医疗智能体·第2讲——合规护城河:等保、PIPL与HIPAA的架构实战 – 人人都是产品经理, 向量知识库五步法:从“答非所问”到“精准回复” – 人人都是产品经理, 鸿蒙PC三方库构建总指挥HPKBUILD(sha)库为例 – 人人都是产品经理, 何时该用LLM?AI产品经理的LLM设计指南 – 人人都是产品经理, 医疗信息领域的需求方、决策方、准入方以及关注点(二) – 人人都是产品经理, 即梦涨价:一场被误读的「傲慢」 – 人人都是产品经理, 面试AI PM必答题:Hermes和OpenClaw的区别,如何讲清楚业务价值 – 人人都是产品经理, AI的下一张船票:世界模型——AI产品经理必须理解的技术拐点 – 人人都是产品经理, 小红书做GEO,怎么让AI信你?记住这 3 个重要信息 – 人人都是产品经理, 5 家印度 AI 初创公司,看看印度 AI 再做什么 – 人人都是产品经理, AI项目跨团队协作:产品技术业务如何不打架 – 人人都是产品经理, Agentic Workflow(智能体工作流):让AI从”答案生成器”变成”数字员工” – 人人都是产品经理, lycium_plusplus 项目全景解读:OpenHarmony 三方库构建的“大管家” – 人人都是产品经理, 从爆单救火到前置履约:两套预采策略,把生鲜大促履约效率拉满 – 人人都是产品经理, 什么时候该补货?我用一轮数据做了一个决定 – 人人都是产品经理, 从“机械兜底”到“动态分流”:AI客服重复进线治理的4大底层逻辑 – 人人都是产品经理, 抖音拼效率,红书拼洞察 – 人人都是产品经理, 全民狂欢与退潮——为什么龙虾这波热潮冷却得如此之快? – 人人都是产品经理, Stripe押注!MPP重塑全球支付 – 人人都是产品经理, 小红书GEO:AI引用你的内容,不是因为你对,而是因为你看起来可信 – 人人都是产品经理, 前百度副总裁押注办公Agent,日韩付费爆发,Manus迎来强劲对手 – 人人都是产品经理,
AI大模型实战篇:AI Agent设计模式 – Plan and Execute
风叔 · 2024-09-05 · via 人人都是产品经理

本文深入探讨了Plan-and-Execute的设计原理、实现方法及其在实际中的应用,为读者揭示了如何构建一个灵活且高效的AI系统。

在上篇文章《AI大模型实战篇:AI Agent设计模式 – REWOO》中,风叔结合原理和具体源代码,详细介绍了ReWOO这种非常有效的AI Agent设计模式。

ReWOO发源于ReAct,加入了规划器以减少Token的消耗。但是ReWOO的规划器完成规划之后,执行器就只负责执行,即使计划存在错误,执行器也只是机械式地执行命令,这就导致ReWOO这种模式非常依赖于规划器的准确性。

为了优化这个问题,我们需要为规划器增加一种Replan机制,即在计划执行的过程中,根据实际的条件和反馈,重新调整计划。这个也很符合人类做计划的模式,比如你之前计划要去自驾游,但是突然看到新闻说前往目的地的主干道路发生了泥石流,因此你肯定会调整计划,取消自驾游或者换一个目的地。

这就是本篇文章风叔将为大家介绍的AI Agent设计模式,Plan-and-Execute。

一、Plan-and-Execute的概念

Plan-and-Execute这个方法的本质是先计划再执行,即先把用户的问题分解成一个个的子任务,然后再执行各个子任务,并根据执行情况调整计划。Plan-and-Execute相比ReWOO,最大的不同就是加入了Replan机制,其架构上包含规划器、执行器和重规划器:

  • 规划器Planner负责让 LLM 生成一个多步计划来完成一个大任务,在书籍运行中,Planner负责第一次生成计划;
  • 执行器接收规划中的步骤,并调用一个或多个工具来完成该任务;
  • 重规划器Replanner负责根据实际的执行情况和信息反馈来调整计划

下图是Plan-and-Execute的原理:

  • Planner接收来自用户的输入,输出具体的任务清单;
  • 将任务清单给到Single-Task Agent,即执行器,执行器会在循环中逐个处理任务;
  • 执行器每处理一个任务,就将处理结果和状态同步给Replanner,Replanner一方面会输出反馈给用户,另一方面会更新任务清单;
  • 任务清单再次给到执行器进行执行。

二、Plan-and-Execute的实现过程

Plan-and-Execute的实现过程

下面,风叔通过实际的源码,详细介绍Plan-and-Execute模式的实现方法。大家可以关注公众号【风叔云】,回复关键词【PAE源码】,获取Plan-and-Execute设计模式的完整源代码。

第一步 构建执行器

下面,我们先创建要用来执行任务的执行器。在这个示例中,为了简单起见,我们将为每个任务使用相同的执行器,即搜索工具。但实际情况下,可以为不同的任务使用不同的执行器。

from langchain import hub
from langchain_openai import ChatOpenA
from langgraph.prebuilt import create_react_agent
from langchain_community.tools.tavily_search import TavilySearchResults
tools = [TavilySearchResults(max_results=3)]

# Get the prompt to use – you can modify this!
prompt = hub.pull(“wfh/react-agent-executor”)
prompt.pretty_print()

# Choose the LLM that will drive the agent
llm = ChatOpenAI(model=”gpt-4-turbo-preview”)
agent_executor = create_react_agent(llm, tools, messages_modifier=prompt)

第二步 定义系统状态

为什么要定义系统状态?因为在处理复杂的不确定性问题时,一个非常有效的方法是将执行阶段拆分为状态机和执行器的循环。

执行器将外部事件输入状态机,状态机告诉执行器必须采取的操作,而原始计划则成为状态机起始状态的初始化程序。这样做的优点在于状态机不依赖于混乱的执行细节,因此我们可以对其进行详尽而彻底的测试。

首先,我们需要跟踪当前计划,将其表示为字符串列表;然后跟踪先前执行的步骤,将其表示为元组列表;最后,还需要状态来表示最终响应以及原始输入。因此,整个状态机定义如下:

import operator
from typing import Annotated, List, Tuple, TypedDict
class PlanExecute(TypedDict):
input: str
plan: List[str]
past_steps: Annotated[List[Tuple], operator.add]
response: str

第三步 定义Planner

Planner的主要任务就是接收输入,并输出初始的Task List。

相比ReWOO的Planner,这里的Planner的Prompt会有所不同,“对于给定的目标,制定一个简单的分步计划。该计划涉及单个任务,如果正确执行,将产生正确的答案,不要添加任何多余的步骤,最后一步的结果应该是最终答案。确保每一步都包含所需的所有信息,不要跳过步骤。”

from langchain_core.pydantic_v1 import BaseModel, Field

class Plan(BaseModel):
“””Plan to follow in future”””
steps: List[str] = Field(
description=”different steps to follow, should be in sorted order”
)

from langchain_core.prompts import ChatPromptTemplate

planner_prompt = ChatPromptTemplate.from_messages(
[
(
“system”,
“””For the given objective, come up with a simple step by step plan.
This plan should involve individual tasks, that if executed correctly will yield the correct answer. Do not add any superfluous steps.
The result of the final step should be the final answer. Make sure that each step has all the information needed – do not skip steps.”””,
),
(“placeholder”, “{messages}”),
]
)

planner = planner_prompt | ChatOpenAI(
model=”gpt-4o”, temperature=0
).with_structured_output(Plan)

planner.invoke(
{
“messages”: [
(“user”, “what is the hometown of the current Australia open winner?”)
]
}
)

第四步 定义Replanner

Replanner的主要任务是根据子任务的执行结果,更新计划。

Replanner和Planner的prompt模板非常相似,但是约束了Replanner的目标任务、原始Plan、已执行的步骤、以及更新计划。

比如更新计划,我们要求“根据执行的步骤更新计划。如果不需要更多步骤,直接可以返回给用户;否则就填写计划,并向计划中添加仍需完成的步骤,不要将之前完成的步骤作为计划的一部分返回”

from typing import Union
class Response(BaseModel):
“””Response to user.”””
response: str

class Act(BaseModel):
“””Action to perform.”””
action: Union[Response, Plan] = Field(
description=”Action to perform. If you want to respond to user, use Response. ”
“If you need to further use tools to get the answer, use Plan.”
)

replanner_prompt = ChatPromptTemplate.from_template(
“””For the given objective, come up with a simple step by step plan.
This plan should involve individual tasks, that if executed correctly will yield the correct answer. Do not add any superfluous steps.
The result of the final step should be the final answer. Make sure that each step has all the information needed – do not skip steps.
Your objective was this:
{input}
Your original plan was this:
{plan}
You have currently done the follow steps:
{past_steps}
Update your plan accordingly. If no more steps are needed and you can return to the user, then respond with that. Otherwise, fill out the plan. Only add steps to the plan that still NEED to be done. Do not return previously done steps as part of the plan.”””
)

replanner = replanner_prompt | ChatOpenAI(
model=”gpt-4o”, temperature=0
).with_structured_output(Act)

第五步 构建流程图

下面,我们构建流程图,将Planner、Replanner、执行器等节点添加进来,执行并输出结果。

from typing import Literal
async def execute_step(state: PlanExecute):
plan = state[“plan”]
plan_str = “n”.join(f”{i+1}. {step}” for i, step in enumerate(plan))
task = plan[0]
task_formatted = f”””For the following plan: {plan_str}. You are tasked with          executing step {1}, {task}.”””
agent_response = await agent_executor.ainvoke(
{“messages”: [(“user”, task_formatted)]}
)
return {
“past_steps”: (task, agent_response[“messages”][-1].content),
}

async def plan_step(state: PlanExecute):
plan = await planner.ainvoke({“messages”: [(“user”, state[“input”])]})
return {“plan”: plan.steps}

async def replan_step(state: PlanExecute):
output = await replanner.ainvoke(state)
if isinstance(output.action, Response):
return {“response”: output.action.response}
else:
return {“plan”: output.action.steps}
def should_end(state: PlanExecute) -> Literal[“agent”, “__end__”]:
if “response” in state and state[“response”]:
return “__end__”
else:
return “agent”

from langgraph.graph import StateGraph, START

workflow = StateGraph(PlanExecute)
# Add the plan node
workflow.add_node(“planner”, plan_step)
# Add the execution step
workflow.add_node(“agent”, execute_step)
# Add a replan node
workflow.add_node(“replan”, replan_step)
workflow.add_edge(START, “planner”)
# From plan we go to agent
workflow.add_edge(“planner”, “agent”)
# From agent, we replan
workflow.add_edge(“agent”, “replan”)
workflow.add_conditional_edges(“replan”, should_end)
app = workflow.compile()

总结

从原理上看,Plan-and-Execute和ReAct也有一定的相似度,但是Plan-and-Execute的优点是具备明确的长期规划,这一点即使非常强大的LLM也难以做到。同时可以只使用较大的模型做规划,而使用较小的模型执行步骤,降低执行成本。

但是Plan-and-execute的局限性在于,每个任务是按顺序执行的,下一个任务都必须等上一个任务完成之后才能执行,这可能会导致总执行时间的增加。

一种有效改进的办法是将每个任务表示为有向无环图DAG,从而实现任务的并行执行。这就是下一篇文章要介绍的AI Agent设计模式,LLM Compiler。

本文由人人都是产品经理作者【风叔】,微信公众号:【风叔云】,原创/授权 发布于人人都是产品经理,未经许可,禁止转载。

题图来自Unsplash,基于 CC0 协议。