LangChain中ChatAgent引入agent_scratchpad触发ValueError问题求助
解决LangChain ChatAgent引入agent_scratchpad的输入键冲突问题
问题核心
ChatAgent与ZeroshotAgent的prompt结构、输入变量逻辑差异较大,结合ConversationBufferMemory时,若prompt变量配置、记忆组件参数不匹配,就会触发输入键数量冲突的报错。
正确配置方案
以下是可直接复用的步骤和代码示例:
- 定义适配ChatAgent的自定义Prompt
ChatAgent基于聊天模型,需用MessagesPlaceholder来处理对话历史和agent思考过程,不能直接用字符串占位符。确保prompt包含chat_history、input、agent_scratchpad三个核心变量:
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder # 自定义系统提示词可根据需求修改 prompt = ChatPromptTemplate.from_messages([ ("system", "你是一个专业的会话助手,结合对话历史和当前提问给出准确回答。"), MessagesPlaceholder(variable_name="chat_history"), # 绑定对话记忆 ("user", "{input}"), # 接收用户输入 MessagesPlaceholder(variable_name="agent_scratchpad"), # 自动注入agent思考过程 ])
- 配置对话记忆组件
指定记忆存储的键名与prompt中的chat_history一致,同时开启return_messages=True,确保返回格式匹配Chat模型的消息结构:
from langchain.memory import ConversationBufferMemory memory = ConversationBufferMemory( memory_key="chat_history", return_messages=True, output_key="output" )
- 初始化ChatAgent与执行器
通过ChatAgent.from_llm_and_tools绑定模型、工具(可先传空列表后续添加)和自定义prompt,再用AgentExecutor整合记忆与agent:
from langchain.agents import ChatAgent, AgentExecutor from langchain.chat_models import ChatOpenAI # 初始化大语言模型,可替换为其他兼容的Chat模型 llm = ChatOpenAI(temperature=0) # 初始化ChatAgent,tools参数后续可添加自定义工具 agent = ChatAgent.from_llm_and_tools(llm=llm, tools=[], prompt=prompt) # 整合agent、记忆、工具,创建执行器 agent_executor = AgentExecutor( agent=agent, tools=[], memory=memory, verbose=True, handle_parsing_errors=True # 可选,处理解析错误 )
关键注意事项
- 禁止手动在prompt中写
{agent_scratchpad}字符串占位符,必须用MessagesPlaceholder,ChatAgent会自动将思考流程转化为消息格式注入。 - 记忆组件的
memory_key必须与prompt中对话历史的变量名完全一致,且return_messages=True是必填项,否则会出现格式不兼容问题。 - 无需手动指定Agent的
input_keys,AgentExecutor会自动处理输入变量的传递逻辑。
内容的提问来源于stack exchange,提问作者Roman
相关产品推荐
相关产品推荐

