agent-frameworks
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "agent-frameworks" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-d38c8b276d363ed3e00f3bc64d1cd556b43c622c9e75ff1781b742e763becb4c. Verify the upstream source and version against https://skillhub.cn/skills/user_fa4109f3/agent-frameworks before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Agent design paradigm guide: introduces two mainstream LLM agent approaches—ReAct and Plan-and-Execute—explaining their design principles and applicable scenarios for reference when building and comparing intelligent agents.
Introduction source: third_party · user_fa4109f3 · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Audience
- Translation pending; see source documentation.
- Inputs and outputs
- Translation pending; see source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: agent-frameworks
description: Agent 设计范式指南 - ReAct 和 Plan-and-Execute 两种主流 LLM Agent
架构的原理、实现与选型建议。触发词:Agent 范式、ReAct、Plan-and-Execute、Agent 架构设计、任务规划、工具调用、推理行动循环。
disable: falseAgent 设计范式指南
本 Skill 提供两种主流 LLM Agent 架构的完整实现指南:
- ReAct(Reasoning + Acting):推理与行动交替循环
- Plan-and-Execute:先规划后执行
目录
快速选择决策树
任务类型是什么?
├─ 简单任务(<3步)
│ └─ 直接使用 LLM 或简单 ReAct
│
├─ 中等复杂度(3-10步)
│ ├─ 环境动态变化? → 是:ReAct / 否:Plan-and-Execute
│ └─ 需要实时信息? → 是:ReAct / 否:Plan-and-Execute
│
└─ 高复杂度(>10步)
├─ 步骤间有复杂依赖? → 是:Plan-and-Execute / 否:ReAct + 重规划
└─ 对 Token 效率要求高? → 是:Plan-and-Execute / 否:ReAct
选择建议:
- 任务 <5步 或 高度动态 → ReAct
- 任务 >5步 或 需要全局协调 → Plan-and-Execute
ReAct 范式
核心原理
ReAct = Reasoning (推理) + Acting (行动)
通过 Thought → Action → Observation → 迭代 的闭环,让 LLM:
- 动态调用外部工具(搜索、计算器、API等)
- 根据真实反馈调整推理路径
- 减少幻觉,提高答案准确性
论文信息:
- 标题:ReAct: Synergizing Reasoning and Acting in Language Models
- 作者:Shunyu Yao (姚顺雨), Jeffrey Zhao, Dian Yu 等
- 机构:普林斯顿大学 & 谷歌研究院
- 发表时间:2022年
工作流程
Thought (思考) → Action (行动) → Observation (观察) → 下一轮 Thought
详细步骤:
- Thought:LLM 分析当前状态,计划下一步
- Action:LLM 决定调用哪个工具,并生成参数
- Observation:系统执行 Action,返回真实结果
- 迭代:将 Observation 添加到上下文,继续循环
优点
✅ 减少幻觉:通过调用真实工具获取信息,避免虚构事实
✅ 动态调整:根据 Observation 实时调整策略
✅ 可解释性:Thought 过程透明,便于调试
✅ 探索能力:适合信息不足、需要探索的任务
缺点
❌ Token 消耗高:多轮循环导致大量 Token 消耗
❌ 延迟高:每次 Action 都需要等待工具返回结果
❌ 可能陷入循环:在几个步骤间重复,无法取得进展
❌ 全局视野弱:"走一步看一步",容易在长任务中迷失方向
适用场景
推荐:
- ✅ 需要实时信息的任务(天气、股票、新闻)
- ✅ 探索性、不确定性高的任务(多平台比价、故障排查)
- ✅ 简单问答、单轮工具调用
- ✅ 快速原型开发
不推荐:
- ❌ 长链条、多步骤的复杂任务(>10步)
- ❌ 对响应速度要求极高的场景
Plan-and-Execute 范式
核心原理
Plan-and-Execute = Planning (规划) + Execution (执行)
将复杂任务分解为两个阶段:
- 规划阶段:LLM 生成完整的执行计划(子任务列表)
- 执行阶段:按序执行每个子任务,记录结果
核心组件
| 组件 | 职责 | 输入 | 输出 |
|---|---|---|---|
| Planner(规划器) | 生成结构化执行计划 | 用户目标、可用工具列表 | JSON 格式的计划(steps 列表) |
| Executor(执行器) | 按序执行计划中的步骤 | 计划(Plan)、工具字典 | 每步的结果(dict) |
| Replanner(重规划器) | 监控执行结果,失败时触发重规划 | 执行结果、原计划 | 更新后的计划 |
工作流程
目标接收 → 全局规划 → 分步执行 → 校验结果 → (失败时)重规划 → 汇总结果
计划格式示例
{
"steps": [
{
"id": 1,
"description": "查询上海天气",
"tool_name": "weather_tool",
"arguments": {"city": "上海"}
},
{
"id": 2,
"description": "预订机票",
"tool_name": "book_flight",
"arguments": {
"origin": "北京",
"destination": "上海",
"date": "明天"
}
},
{
"id": 3,
"description": "发送邮件通知",
"tool_name": "send_email",
"arguments": {
"to": "manager@company.com",
"subject": "出差安排",
"body": "{{2}}"
}
}
]
}
注意:{{2}} 是占位符,表示"引用步骤2的结果"。
优点
✅ 全局视野强:规划阶段考虑整体目标,不易偏离
✅ 步骤清晰:计划可审核、可调试、可复用
✅ Token 效率高:计划复用,减少重复推理
✅ 支持并行:无依赖的子任务可并行执行
✅ 局部失败不影响全局:只需重规划失败的步骤
缺点
❌ 初始计划可能过时:环境变化导致计划失效
❌ 分层 LLM 调用增加开销:Planner、Executor、Replanner 都需要调用 LLM
❌ 重规划逻辑复杂:步骤依赖关系复杂时,重规划困难
适用场景
推荐:
- ✅ 长链条、多步骤的复杂任务(>5步)
- ✅ 需要全局协调的任务(如"安排一次出差")
- ✅ 流程固化、需要可视化进度的场景
- ✅ 对 Token 效率要求高的项目
不推荐:
- ❌ 简单、短链路的
任务(<3步)
- ❌ 环境高度动态、需要实时调整的场景
代码实现
ReAct 实现(LangChain)
from langchain.agents import create_react_agent, AgentExecutor
from langchain.tools import tool
from langchain_core.prompts import ChatPromptTemplate
from langchain_deepseek import ChatDeepSeek
# ===================== 工具定义 =====================
@tool
def search_weather(city: str) -> str:
"""获取指定城市的天气信息。
Args:
city: 城市名称,如"上海"、"北京"
"""
weather_data = {
"上海": "晴,气温 18-25°C",
"北京": "多云,气温 10-18°C"
}
return weather_data.get(city, f"{city}的天气信息未知")
# 工具列表
tools = [search_weather]
# ===================== 创建 ReAct Agent =====================
llm = ChatDeepSeek(model="deepseek-chat", temperature=0)
# ReAct Prompt 模板
prompt = ChatPromptTemplate.from_messages([
("system", "你是一个有用的助手,可以使用工具回答问题。"),
("human", "{input}"),
("assistant", "{agent_scratchpad}") # ReAct 的中间步骤
])
# 创建 ReAct Agent
agent = create_react_agent(llm, tools, prompt)
# 创建 Agent 执行器
executor = AgentExecutor(
agent=agent,
tools=tools,
max_iterations=5, # 最大迭代次数
verbose=True # 打印 Thought/Action/Observation
)
# ===================== 执行任务 =====================
if __name__ == "__main__":
result = executor.invoke({"input": "上海今天天气怎么样?"})
print("回答:", result["output"])
完整代码示例:参见 examples/react_example.py
Plan-and-Execute 实现
from typing import List, Dict, Any
from pydantic import BaseModel, Field
from langchain_deepseek import ChatDeepSeek
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import JsonOutputParser
# ===================== 结构化输出模型 =====================
class PlanStep(BaseModel):
id: int = Field(description="步骤ID(从1开始)")
description: str = Field(description="步骤描述")
tool_name: str = Field(description="要调用的工具名称")
arguments: Dict[str, Any] = Field(description="工具参数字典")
class Plan(BaseModel):
steps: List[PlanStep] = Field(description="步骤列表,按执行顺序排列")
# ===================== 工具定义 =====================
def search_weather(city: str) -> str:
"""获取指定城市的天气信息"""
weather_data = {"上海": "晴,气温 18-25°C"}
return weather_data.get(city, f"{city}的天气信息未知")
def book_flight(origin: str, destination: str, date: str) -> str:
"""预订航班"""
return f"已预订 {date} 从 {origin} 到 {destination} 的航班"
# 工具字典
TOOLS = {
"search_weather": search_weather,
"book_flight": book_flight
}
# ===================== Planner(规划器)=====================
class Planner:
def __init__(self, model: str = "deepseek-chat"):
self.llm = ChatDeepSeek(model=model, temperature=0)
self.parser = JsonOutputParser(pydantic_object=Plan)
self.prompt = ChatPromptTemplate.from_messages([
("system", """你是专业任务规划专家。
可用工具如下:
{tools}
要求:
1. 严格使用上述提供的可用工具。
2. 生成一个完整的执行计划,包含多个步骤。
3. 如果后续步骤需要引用前面步骤的结果,使用占位符 {{步骤ID}}。
4. 只输出严格的 JSON 格式,不要任何解释或说明!
"""),
("human", "我的目标是:{goal}")
])
def generate_plan(self, goal: str) -> Plan:
"""生成执行计划"""
response = self.llm.invoke(
self.prompt.format_messages(
goal=goal,
tools="\n".join([f"- {k}: {v.__doc__}" for k, v in TOOLS.items()])
)
)
# 解析 JSON 响应
plan_dict = self.parser.parse(response.content)
return Plan(**plan_dict)
# ===================== Executor(执行器)=====================
class Executor:
def __init__(self, tools: Dict[str, callable]):
self.tools = tools
def _resolve_arguments(self, args: Dict[str, Any], results: Dict[int, str]) -> Dict[str, Any]:
"""解析参数中的占位符(如 {{2}} → results[2])"""
resolved = {}
for key, value in args.items():
if isinstance(value, str) and value.startswith("{{") and value.endswith("}}"):
step_id = int(value.strip("{}"))
resolved[key] = results.get(step_id, "")
else:
resolved[key] = value
return resolved
def execute(self, plan: Plan, max_retries: int = 2) -> Dict[int, str]:
"""执行计划,返回每步的结果"""
results = {} # step_id → result
for step in plan.steps:
tool_func = self.tools.get(step.tool_name)
if not tool_func:
raise ValueError(f"未知工具:{step.tool_name}")
# 解析参数(替换占位符)
args = self._resolve_arguments(step.arguments, results)
# 执行(带重试)
for attempt in range(max_retries + 1):
try:
result = tool_func(**args)
results[step.id] = result
print(f"✅ 步骤 {step.id}: {result}")
break
except Exception as e:
if attempt < max_retries:
print(f"⚠️ 步骤 {step.id} 失败,重试中... ({attempt + 1}/{max_retries})")
else:
raise RuntimeError(f"步骤 {step.id} 执行失败:{e}")
return results
# ===================== 主流程 =====================
def run_plan_and_execute(goal: str):
"""运行 Plan-and-Execute"""
planner = Planner()
executor = Executor(TOOLS)
print(f"🎯 目标:{goal}\n")
# 阶段1:规划
print("📋 正在生成执行计划...")
plan = planner.generate_plan(goal)
print("\n生成计划:")
for step in plan.steps:
print(f" 步骤{step.id}: {step.description} → {step.tool_name}({step.arguments})")
# 阶段2:执行
print("\n🚀 开始执行...")
results = executor.execute(plan)
# 阶段3:汇总结果
print("\n🎉 执行完成!结果汇总:")
for step_id, result in results.items():
print(f" 步骤{step_id}: {result}")
return results
# ===================== 运行示例 =====================
if __name__ == "__main__":
goal = "帮我安排一次从北京到上海的出差:先查上海天气,然后订明天的机票"
results = run_plan_and_execute(goal)
完整代码示例:参见 examples/plan_and_execute_example.py
最佳实践
ReAct 最佳实践
✅ 限制最大迭代次数:避免无限循环(建议 max_iterations=5-10)
✅ 使用 Few-Shot 示例:在 Prompt 中提供 Thought-Action-Observation 示例
✅ 工具描述要清晰:工具名称、参数、返回值都要有明确说明
✅ 实现循环检测:如果检测到重复 Action,强制终止
✅ 记录完整轨迹:便于调试和优化
Plan-and-Execute 最佳实践
✅ 计划要结构化:使用 JSON 格式,便于解析和验证
✅ 实现占位符解析:支持步骤间引用(如 {{2}})
✅ 添加重试机制:失败步骤自动重试(最多 2-3 次)
✅ 实现 Replanner:监控执行结果,失败时触发重规划
✅ 支持并行执行:无依赖的步骤可并行处理(使用 asyncio)
通用最佳实践
✅ 工具设计原则:
- 单一职责:每个工具只做一件事
- 清晰描述:工具名、参数、返回值都要有明确说明
- 错误处理:工具要捕获异常,返回友好错误信息
✅ Prompt 工程:
- 提供 Few-Shot 示例
- 明确输出格式(如"只输出 JSON,不要解释")
- 限制输出长度(避免 Token 浪费)
常见陷阱
ReAct 常见陷阱
❌ 未限制最大迭代次数 → 无限循环
❌ 工具描述不清晰 → LLM 调用错误
❌ 未处理工具异常 → 任务失败
❌ Observation 过长 → Token 溢出
Plan-and-Execute 常见陷阱
❌ 计划过于僵化 → 无法适应环境变化
❌ 未处理步骤依赖 → 执行顺序错误
❌ 重规划逻辑复杂 → 陷入死循环
❌ 未校验计划合理性 → 执行失败
参考文献
- ReAct 论文:Yao, S., et al. (2022). ReAct: Synergizing Reasoning and Acting in Language Models. arXiv:2210.03629.
- LangChain 文档:https://python.langchain.com/docs/modules/agents/
- LangGraph 文档:https://langchain-ai.github.io/langgraph/
版本历史
- v1.0(2026-05-04):初始版本,包含 ReAct 和 Plan-and-Execute 两种范式的完整指南
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供两种主流 LLM Agent 架构的完整实现指南
- 包含详细的选型决策树和适用场景分析
- 面向开发者群体,具有明确的实用价值
Highlights
- 触发词覆盖全面,包括 Agent 范式、ReAct、Plan-and-Execute 等核心概念
- 边界清晰,不易与其他 Skill 重叠
Highlights
- 文档结构完整,包含原理、实现、最佳实践、常见陷阱等全链路内容
- 提供快速选择决策树,便于用户快速定位
- 代码示例规范,有详细注释和说明
Highlights
- 代码实现完整,工具定义清晰
- 包含异常处理和重试机制
- 引用文件存在且内容完整
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- langchain-ai.github.io
- python.langchain.com
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.