LangChain+Streamlit聊天机器人报错:期望1个输入键却获['input','agent_scratchpad']
问题修复方案
错误根源
- 同时在
LLMChain和AgentExecutor上绑定了ConversationBufferMemory,导致输入变量冲突:AgentExecutor自动传入agent_scratchpad和input,加上LLMChain从memory加载的chat_history,触发输入键数量不匹配报错。 - 手动在
ZeroShotAgent.create_prompt的input_variables里添加了agent_scratchpad,但这个变量是Agent内部自动注入的,手动声明会引发重复冲突。
修复代码
1. 调整Prompt定义
prompt = ZeroShotAgent.create_prompt( tools, prefix=template, suffix=suffix, input_variables=["input", "chat_history"] # 移除agent_scratchpad )
2. 分离LLMChain与Memory的绑定
# LLMChain不再绑定memory,仅负责prompt和大模型的调用 llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True, return_intermediate_steps=True)
3. 复用AgentExecutor实例(关键:保证记忆不丢失)
把AgentExecutor的初始化移到查询分支外,用Streamlit会话状态保存,避免每次输入都重建实例:
# 在页面初始化时创建一次AgentExecutor,存入session_state if "agent_executor" not in st.session_state: memory = ConversationBufferMemory(memory_key="chat_history") st.session_state.agent_executor = AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, memory=memory, verbose=True ) with textcontainer: query = st.text_input("Query: ", key="input") if query: with st.spinner("typing..."): # 直接复用session_state里的agent_executor response = st.session_state.agent_executor.run(input=query) st.session_state.requests.append(query) st.session_state.responses.append(str(response))
修复逻辑说明
- AgentExecutor会自动处理
agent_scratchpad的传递,无需在prompt里手动声明; - 仅让AgentExecutor管理对话记忆,避免LLMChain和AgentExecutor的输入变量冲突;
- 复用AgentExecutor实例,确保对话记忆能在多次查询间正常累积。
内容的提问来源于stack exchange,提问作者ML Ops
相关产品推荐
相关产品推荐

