You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain+Streamlit聊天机器人报错:期望1个输入键却获['input','agent_scratchpad']

问题修复方案

错误根源

  1. 同时在LLMChain和AgentExecutor上绑定了ConversationBufferMemory,导致输入变量冲突:AgentExecutor自动传入agent_scratchpad和input,加上LLMChain从memory加载的chat_history,触发输入键数量不匹配报错。
  2. 手动在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 09:55:06