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

使用Langchain ConversationalRetrievalChain无法保留聊天历史的问题

问题原因及修复方案

核心问题分析

你的代码无法留存聊天历史,主要有3个关键问题:

  • 自定义Prompt模板结构混乱:重复定义了包含chat_history的系统消息,导致模板变量传递逻辑冲突
  • 记忆组件配置与Prompt不兼容:return_messages=True时,chat_history是消息对象列表,但你的模板直接输出,LLM无法正确解析格式
  • 链参数配置不完整:未明确指定输入输出键与记忆组件的关联关系

修复后的完整代码

def get_conversation_chain(self, vetorestore, prompt):
    # 整合自定义prompt、上下文与聊天历史的模板
    general_system_template = f"""
    {prompt}
    ----
    上下文信息:
    {context}
    ----
    历史对话记录:
    {chat_history}
    ----
    请结合上下文和历史对话,准确回答用户的问题。
    """
    
    general_user_template = "问题:```{question}```"
    
    # 构建标准的Prompt消息序列:系统消息 + 用户消息
    messages = [
        SystemMessagePromptTemplate.from_template(general_system_template),
        HumanMessagePromptTemplate.from_template(general_user_template)
    ]
    qa_prompt = ChatPromptTemplate.from_messages(messages)
    
    llm = ChatOpenAI(
        model_name="gpt-4-1106-preview",
        temperature=0,
    )
    
    # 调整记忆组件配置:输出字符串格式历史,明确关联回答键
    memory = ConversationBufferMemory(
        memory_key="chat_history",
        return_messages=False,
        output_key="answer"
    )
    
    conversation = ConversationalRetrievalChain.from_llm(
        llm=llm,
        retriever=vetorestore.as_retriever(),
        memory=memory,
        chain_type="stuff",
        combine_docs_chain_kwargs={
            "prompt": qa_prompt,
        },
        # 明确输入输出键,确保记忆与链的逻辑关联
        question_key="question",
        answer_key="answer"
    )
    return conversation

关键修复点说明

  • 简化Prompt结构:删除重复的Chat_system_template,仅保留系统消息+用户消息的标准结构,确保chat_history、context、question三个变量正确传递
  • 适配记忆组件:将return_messages改为False,让记忆返回字符串格式的历史记录,适配自定义Prompt的解析需求;添加output_key="answer"确保回答被正确存入记忆
  • 补全链参数:添加question_key和answer_key,明确链的输入输出与记忆组件的关联逻辑,保证聊天历史被正常留存和调用

内容的提问来源于stack exchange,提问作者nitin kalra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 04:26:30