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

LangChain Agent报错KeyError: {'input', 'agent_scratchpad'} 求助解决及必应搜索配置

问题解决:LangChain Agent KeyError: {'input', 'agent_scratchpad'}

错误原因

直接替换ZERO_SHOT_REACT_DESCRIPTION类型Agent的prompt模板时,自定义的system_template缺少Agent运行必须的{input}和{agent_scratchpad}占位符。LangChain的Agent在格式化prompt时会严格检查变量匹配,缺失这两个变量会触发KeyError。

解决方案

方案1:基于原Agent模板扩展(推荐)

保留原ZERO_SHOT_REACT_DESCRIPTION模板的核心结构,仅添加财务顾问的角色提示,无需手动维护所有占位符:

def langchain_completion(self):
    # 自定义财务顾问角色提示
    financial_advisor_prompt = """Your job is a financial advisor and assistant that must make decisions for users based on the user's data and the questions you ask."""
    
    llm = ChatOpenAI(model_name="gpt-4",
                     temperature=self.TEMPERATURE,
                     max_tokens=self.USER_MAX_TOKENS
                    )

    tools = load_tools(["wikipedia", "llm-math", "bing-search"],
                       llm=llm
                      )
    
    my_agent = initialize_agent(tools,
                                 llm,
                                 agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
                                 verbose=False
                                )

    # 获取原Agent的prompt模板,插入自定义提示
    original_template = my_agent.agent.llm_chain.prompt.template
    updated_template = f"{financial_advisor_prompt}\n\n{original_template}"
    my_agent.agent.llm_chain.prompt.template = updated_template

    while True:
        question = input("Enter your prompt: ")
        if question != "":
            print(my_agent.run(input=question))
        else:
            return "I'm Out"

方案2:自定义完整符合要求的模板

如果需要完全自定义prompt结构,必须包含所有Agent依赖的变量({tools}、{tool_names}、{input}、{agent_scratchpad}):

def langchain_completion(self):
    # 完整自定义模板,包含所有必要变量
    full_system_template = """
Your job is a financial advisor and assistant that must make decisions for users based on the user's data and the questions you ask.

Answer the following questions as best you can. You have access to the following tools:

{tools}

Use the following format:

Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question

Begin!

Question: {input}
Thought:{agent_scratchpad}
    """
    
    llm = ChatOpenAI(model_name="gpt-4",
                     temperature=self.TEMPERATURE,
                     max_tokens=self.USER_MAX_TOKENS
                    )

    tools = load_tools(["wikipedia", "llm-math", "bing-search"],
                       llm=llm
                      )
    
    # 基于自定义模板构建Agent
    from langchain.agents import ZeroShotAgent, AgentExecutor
    from langchain.chains import LLMChain

    prompt = ZeroShotAgent.create_prompt(
        tools,
        prefix=full_system_template.split("Begin!")[0].strip(),
        suffix=full_system_template.split("Begin!")[1].strip(),
        input_variables=["input", "agent_scratchpad"]
    )
    llm_chain = LLMChain(llm=llm, prompt=prompt)
    agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=False)
    my_agent = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=False)

    while True:
        question = input("Enter your prompt: ")
        if question != "":
            print(my_agent.run(input=question))
        else:
            return "I'm Out"

验证说明

两种方案都能确保Agent正常调用必应搜索等工具,同时保留财务顾问的角色设定。运行代码后输入问题,Agent会根据需要触发工具调用,返回符合要求的财务相关解答。

内容的提问来源于stack exchange,提问作者Bilal bAI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 03:16:12