LangChain自定义ReAct代理无限循环问题求助(报错:Missing 'Action:' after 'Thought:')
我看了你的代码和终端报错,这个无限循环+格式错误的问题,核心是自定义的ReAct Prompt模板没对齐LangChain ReAct Agent的格式要求,再加上几个参数传递的小失误导致的。下面给你一步步拆解修复:
问题1:Prompt模板格式不符合LangChain的解析规则
LangChain的ReAct Agent对LLM的输出格式有严格约定,必须明确输出Action: 工具名和Action Input: 参数这样的标准标记。你的模板里的示例写法(比如[Action]: I should use the get_weather tool...)太口语化,解析器根本识别不出合规的Action标记,所以才会一直报错“Missing 'Action:' after 'Thought:'”,进而陷入循环。
修复后的Prompt模板:
要明确告诉LLM必须遵循的格式,把示例改成标准写法,同时简化思考流程的描述:
react_template = """ Answer the following questions as best you can, using the tools provided. Tools: {tools} Use the following format: Question: the input question you must answer Thought: Do I need to use a tool? Yes/No Action: the tool to use, should be one of [{tool_names}] Action Input: the input to give the tool Observation: the result of the tool ... (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: {question} {agent_scratchpad} """
问题2:Prompt的input_variables遗漏了agent_scratchpad
你定义的react_prompt里,input_variables只包含了question、tools、tool_names,但agent_scratchpad是Agent用来记录历史思考/操作的关键变量,没加的话Agent无法迭代更新状态,也是循环的诱因之一。
修复:
react_prompt = PromptTemplate( template=react_template, input_variables=["question", "tools", "tool_names", "agent_scratchpad"], # 补上agent_scratchpad )
问题3:调用AgentExecutor时手动传入了多余参数
你在invoke的时候手动传了tools、tool_names、agent_scratchpad,但这些参数已经由create_react_agent自动绑定到Prompt里了,手动传入会覆盖正确的工具信息,导致Agent无法正确识别可用工具。
修复:
invoke只需要传question即可:
if __name__ == "__main__": response = agent_exexcutor.invoke( input={"question": "What is the weather in france ?"} ) print(response["output"])
可选优化:降低LLM温度减少随机性
你用的是llama3.2:1b小模型,即使temperature=0.1,偶尔还是会输出不符合格式的内容,可以把温度调到0.0,进一步约束输出的一致性:
llm = ChatOllama( model="llama3.2:1b", temperature=0.0, # 改成0.0 )
完整修复后的代码
把上面的修改整合后,完整代码如下:
from langchain_ollama import ChatOllama from langchain.tools import Tool from langchain.agents import create_react_agent, AgentExecutor from langchain_core.prompts import PromptTemplate llm = ChatOllama( model="llama3.2:1b", temperature=0.0, ) react_template = """ Answer the following questions as best you can, using the tools provided. Tools: {tools} Use the following format: Question: the input question you must answer Thought: Do I need to use a tool? Yes/No Action: the tool to use, should be one of [{tool_names}] Action Input: the input to give the tool Observation: the result of the tool ... (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: {question} {agent_scratchpad} """ react_prompt = PromptTemplate( template=react_template, input_variables=["question", "tools", "tool_names", "agent_scratchpad"], ) def get_weather_func(location: str) -> str: location = location.lower().strip() if location == "france": return "cloudy" elif location == "italy": return "sunny" else: return "unknown weather" weather_tool = Tool( name= "get_weather", func=get_weather_func, description="Useful for getting the weather of a location" ) tools = [weather_tool] agent = create_react_agent( llm=llm, tools=tools, prompt=react_prompt ) agent_exexcutor = AgentExecutor( agent=agent, tools=tools, verbose=True, handle_parsing_errors=True ) if __name__ == "__main__": response = agent_exexcutor.invoke( input={"question": "What is the weather in france ?"} ) print(response["output"])
为什么这样能解决问题?
调整后的Prompt严格遵循了LangChain ReAct Agent的格式规范,解析器能准确识别Action和Action Input标记,拿到工具返回的结果后,LLM会按照模板判断是否已经得到最终答案,从而跳出循环返回结果,不会再出现格式错误的情况。
备注:内容来源于stack exchange,提问作者Lakshdeep Singh

