首页 > 基础资料 博客日记
AI开发-python-langchain框架(3-24-Plan-and-Execute Agent)
2026-04-14 19:00:02基础资料围观1次
基于LangChain与DeepSeek实现Plan-and-Execute Agent,让AI学会“先规划后行动”
一、先搞懂:Plan-and-Execute到底是什么?
二、Plan-and-Execute的核心特点:为什么值得用?
1. 任务拆解更清晰,目标更聚焦
2. 工具调用更高效,资源更节省
3. 支持多轮记忆,交互更连贯
4. 容错性更强,执行更稳定
三、实操落地:基于LangChain与DeepSeek的实现思路
1. 模型初始化:搭建核心动力
2. 工具定义:给Agent配备“手脚”
3. 核心组件搭建:规划器与执行器协同工作
4. 对话记忆配置:实现多轮交互
5. 主循环封装:让Agent可直接启动使用
四、实践总结与避坑提示
# -*- coding: utf-8 -*-
"""
Plan-and-Execute Agent using DeepSeek via LangChain
- Planner: 拆解任务为子步骤
- Executor: 逐个执行子步骤(可调用工具)
- 支持多轮对话(通过手动注入历史)
------使用默认提示词
"""
import os
from datetime import datetime
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain.agents import Tool
from langchain.memory import ConversationBufferMemory
from langchain_experimental.plan_and_execute import (
PlanAndExecute,
load_agent_executor,
load_chat_planner,
)
load_dotenv()
# ========================
# 1. 初始化 DeepSeek LLM
# ========================
DEEPSEEK_API_KEY = "123" # 替换为实际的 API Key
llm = ChatOpenAI(
api_key=DEEPSEEK_API_KEY,
base_url="https://xxxxx.cn/v1", # Deepseek 的 API 基础地址
model="deepseek-v3:671b", # Deepseek 对话模型(可选:deepseek-chat-pro 等高级模型)
temperature=0.7, # 温度参数(0-1,越低越稳定)
max_tokens=1024 # 最大生成 tokens
)
# ========================
# 2. 定义本地工具
# ========================
def calculate(expr: str) -> str:
allowed = set("0123456789+-*/(). ")
if not all(c in allowed for c in expr):
return "错误:非法字符"
try:
return str(eval(expr, {"__builtins__": {}}, {}))
except Exception as e:
return f"计算失败: {e}"
def get_current_time(_) -> str:
return datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")
def answer_simple_question(query: str) -> str:
knowledge = {
"你是谁": "我是基于 DeepSeek 的 Plan-and-Execute 智能助手。",
"你能做什么": "我可以制定计划并执行多步任务,比如计算、查时间、逻辑推理等。",
}
return knowledge.get(query.strip("?? "), "这个问题我暂时无法回答。")
tools = [
Tool(name="Calculator", func=calculate, description="执行数学计算,输入如 '2 + 3 * 4'"),
Tool(name="CurrentTime", func=get_current_time, description="获取当前日期和时间"),
Tool(name="SimpleQA", func=answer_simple_question, description="回答简单预设问题"),
]
# ========================
# 3. 创建 Plan-and-Execute Agent
# ========================
planner = load_chat_planner(llm)
executor = load_agent_executor(llm, tools, verbose=True)
agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)
# 添加对话记忆(PlanAndExecute 默认不支持 memory,需手动处理)
memory = ConversationBufferMemory(memory_key="history", input_key="input")
# ========================
# 4. 执行函数(带记忆)
# ========================
def run_with_memory(user_input: str) -> str:
history = memory.load_memory_variables({}).get("history", "")
if history:
full_input = f"之前的对话:\n{history}\n\n现在用户问:\n{user_input}"
else:
full_input = user_input
# 使用 invoke 替代 run
response = agent.invoke({"input": full_input})["output"]
memory.save_context({"input": user_input}, {"output": response})
return response
# ========================
# 5. 主循环
# ========================
if __name__ == "__main__":
print("🧠 Plan-and-Execute Agent 启动!")
print("💡 示例:'先算 12*5,再告诉我现在几点,最后说你好'")
print("🛑 输入 'quit' 退出。\n")
while True:
user_input = input("👤 你: ").strip()
if not user_input or user_input.lower() in ["quit", "exit"]:
print("👋 再见!")
break
try:
response = run_with_memory(user_input)
print(f"🤖 助手: {response}\n")
except Exception as e:
print(f"❌ 错误: {e}\n")
执行结果:
🧠 Plan-and-Execute Agent 启动!
💡 示例:'先算 12*5,再告诉我现在几点,最后说你好'
🛑 输入 'quit' 退出。
👤 你: 先算 12*5,再告诉我现在几点,最后说你好
> Entering new PlanAndExecute chain...
steps=[Step(value='Calculate the product of 12 multiplied by 5.'), Step(value='Determine the current time.'), Step(value='Greet the user with "你好".'), Step(value="Given the above steps taken, please respond to the user's original question.\n")]
> Entering new AgentExecutor chain...
Thought: To calculate the product of 12 multiplied by 5, I will use the Calculator tool.
Action:
```
{
"action": "Calculator",
"action_input": "12 * 5"
}
```
Observation: 60
Thought:Action:
```
{
"action": "Final Answer",
"action_input": "The product of 12 multiplied by 5 is 60."
}
```
> Finished chain.
*****
Step: Calculate the product of 12 multiplied by 5.
Response: The product of 12 multiplied by 5 is 60.
> Entering new AgentExecutor chain...
Action:
```
{
"action": "CurrentTime",
"action_input": ""
}
```
Observation: 2026年04月14日 18:43:00
Thought:{
"action": "Final Answer",
"action_input": "The current time is 2026年04月14日 18:43:00."
}
> Finished chain.
*****
Step: Determine the current time.
Response: {
"action": "Final Answer",
"action_input": "The current time is 2026年04月14日 18:43:00."
}
> Entering new AgentExecutor chain...
```
{
"action": "Final Answer",
"action_input": "你好"
}
```
> Finished chain.
*****
Step: Greet the user with "你好".
Response: 你好
> Entering new AgentExecutor chain...
{
"action": "Final Answer",
"action_input": "你好\n\nThe product of 12 multiplied by 5 is 60.\n\nThe current time is 2026年04月14日 18:43:00."
}
> Finished chain.
*****
Step: Given the above steps taken, please respond to the user's original question.
Response: {
"action": "Final Answer",
"action_input": "你好\n\nThe product of 12 multiplied by 5 is 60.\n\nThe current time is 2026年04月14日 18:43:00."
}
> Finished chain.
🤖 助手: {
"action": "Final Answer",
"action_input": "你好\n\nThe product of 12 multiplied by 5 is 60.\n\nThe current time is 2026年04月14日 18:43:00."
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:

