LangChain ConversationalRetrievalChain传入chat_history仍不记忆对话历史问题
问题:LangChain ConversationalRetrievalChain 无法保留对话记忆
我在学习AI和LangChain,尝试构建对话式聊天机器人,目前已经实现基于自定义文本的问答功能,但机器人无法记忆先前的对话内容。根据资料,ConversationalRetrievalChain需要传入chat_history参数来保留记忆,我已经传入该参数且history列表也记录了对话,但问题依然存在。
代码示例
history = [] def ask(question: str): chat = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), memory=memory) answer = chat({"question": question, "chat_history": history})["answer"] history.append((question, answer)) print(answer) return answer ask("Who is Bound by this Agreement?") # 回答正确 ask("What did I ask in previous question?") # 无法记住之前的问题
我已经确认chat_history已经存入history列表,为什么模型还是无法记忆先前的对话?
问题原因
- 每次调用都重新创建链实例:在
ask函数内部每次都新建ConversationalRetrievalChain对象,相当于每次对话都是一个全新的机器人实例,之前的对话状态不会被保留。 - memory参数与手动传入chat_history冲突:你同时传入了
memory=memory参数和手动的chat_history参数,ConversationalRetrievalChain在配置了memory的情况下,会优先使用内部的记忆管理机制,忽略手动传入的chat_history参数。
解决方案
方案1:使用Memory对象管理对话历史(推荐)
将链的初始化移到ask函数外部,只执行一次,让memory对象自动维护对话历史:
from langchain.memory import ConversationBufferMemory # 仅初始化一次memory和对话链 memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True) chat_chain = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever(), memory=memory) def ask(question: str): answer = chat_chain({"question": question})["answer"] print(answer) return answer ask("Who is Bound by this Agreement?") # 正确回答 ask("What did I ask in previous question?") # 可正常回忆之前的问题
方案2:手动维护chat_history,不使用memory参数
同样将链的初始化移到函数外部,避免重复创建实例,同时不配置memory参数,手动传入维护的chat_history:
history = [] # 仅初始化一次对话链,不传入memory参数 chat_chain = ConversationalRetrievalChain.from_llm(llm, vectorstore.as_retriever()) def ask(question: str): global history answer = chat_chain({"question": question, "chat_history": history})["answer"] history.append((question, answer)) print(answer) return answer ask("Who is Bound by this Agreement?") # 正确回答 ask("What did I ask in previous question?") # 可正常回忆之前的问题
内容的提问来源于stack exchange,提问作者Владислав Король
相关产品推荐
相关产品推荐

