如何阻止LangChain中Agent Chain自动生成新输入?
解决LangChain CONVERSATIONAL_REACT_DESCRIPTION Agent自动生成"New input:"的问题
问题详情
使用LangChain的CONVERSATIONAL_REACT_DESCRIPTION类型Agent开发对话式Chatbot时,运行代码后出现以下问题:
- Agent自动连续生成大量"New input:"及对应响应内容,设置
stop=["New input:"]参数无效,与文档预期输出不符 - 希望Agent能根据接收的问题自动选择对应工具运行,已补充日常对话工具代码
原始代码
llm = AzureOpenAI(deployment_name = "gpt35_0301", model_name = "gpt-35-turbo", max_tokens = 1000, top_p = 0, temperature = 0) db = SQLDatabase.from_databricks(catalog = "hive_metastore", schema = "AISchema") db_chain = SQLDatabaseChain.from_llm(llm, db, verbose = False) tools = [Tool(name = "SQL Database Chain", func=db_chain.run, description="Useful when you need to answer questions that need to form a query and get result from database")] memory = ConversationBufferMemory(memory_key="chat_history") agent_chain = initialize_agent(tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory, stop=["New input:"]) print(agent_chain.run(input="Hi, nice to meet you!"))
补充工具代码
tools = [Tool(name = "SQL Database Chain", func=db_chain.run, description="Useful when you need to answer questions that need to form a query and get result from database"), Tool(name = "Conversation", func=conversation.run, description="Useful when it is just normal communication and does not required to get answer from SQL Database")]
问题原因
- LLM类型不匹配:
AzureOpenAI类针对Completion模型设计,而gpt-35-turbo是Chat模型,两者输出格式差异导致stop参数无法生效 - Memory配置错误:
ConversationBufferMemory未启用return_messages=True,不符合CONVERSATIONAL_REACT_DESCRIPTION Agent对记忆格式的要求 - 工具覆盖不全(初始代码):缺少日常对话工具时,Agent无法处理闲聊类问题,触发异常循环生成逻辑
- Stop参数匹配度不足:模型输出的"New input:"可能带有换行或其他符号,单一的
"New input:"无法完全匹配终止条件
解决方案
1. 替换为Chat模型适配的LLM类
将AzureOpenAI替换为AzureChatOpenAI(Chat模型专属封装):
from langchain.chat_models import AzureChatOpenAI llm = AzureChatOpenAI( deployment_name="gpt35_0301", model_name="gpt-35-turbo", max_tokens=1000, top_p=0, temperature=0 )
2. 修正Memory配置
启用return_messages=True,确保记忆以消息对象格式存储:
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
3. 优化Stop参数
增加换行匹配项,覆盖模型可能的输出格式:
agent_chain = initialize_agent( tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory, stop=["New input:", "\nNew input:"] )
4. 完善Conversation工具实现
确保日常对话工具能直接处理输入,避免内部逻辑异常:
def conversation_run(input_text): # 可根据需求扩展日常对话响应逻辑 if "nice to meet you" in input_text.lower(): return "我也很高兴认识你!😊" return f"收到你的消息:{input_text}" tools = [ Tool( name="SQL Database Chain", func=db_chain.run, description="仅在需要查询数据库获取答案时使用,比如数据统计、业务指标查询等问题" ), Tool( name="Conversation", func=conversation_run, description="用于问候、日常聊天、自我介绍等不需要访问数据库的场景" ) ]
优化建议
- 精准工具描述:工具描述越具体,Agent判断工具选择的准确率越高,避免模糊描述导致的误判
- 调试verbose模式:开启
verbose=True后,观察Agent的思考链,定位触发"New input:"生成的具体环节 - 微调LLM参数:若问题仍存在,可将
temperature微调至0.1,避免模型过度僵化导致的格式输出异常
内容的提问来源于stack exchange,提问作者weizer
相关产品推荐
相关产品推荐

