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

Langchain ConversationalRetrievalChain无法记忆首个问题的技术咨询

问题解决:Langchain ConversationalRetrievalChain无法记住对话历史

问题根源

你的代码中自定义Prompt直接插入原始格式的chat_history(元组列表的字符串形式),导致大语言模型无法识别对话历史的结构,因此第二次输入地点时无法关联之前告知的脑震荡症状。

修复方案

1. 格式化对话历史的Prompt模板

修改系统提示模板,使用Jinja2语法将chat_history转换为模型能理解的自然对话形式:

from langchain.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate, ChatPromptTemplate
from langchain.chat_models import ChatOpenAI

# 修改后的系统提示模板,加入对话历史格式化逻辑
system_template = """you are an AI assistant named aidan. your job is to recommend the best clinicians based 
on the symptoms and locations. ask the user about location preference and then recommend the clinicians based on their symptoms and preferences
        ----------------
        Context
        {context}

        Chat History:
        {% for human, ai in chat_history %}
        Human: {{ human }}
        AI: {{ ai }}
        {% endfor %}
        
        QUESTION:
        {question}
        
        ANSWER:
"""

# 创建聊天提示模板
messages = [
    SystemMessagePromptTemplate.from_template(system_template),
    HumanMessagePromptTemplate.from_template("{question}")
]
qa_prompt = ChatPromptTemplate.from_messages(messages)

# 初始化对话检索链
chain = ConversationalRetrievalChain.from_llm(
    llm=ChatOpenAI(temperature=1, model_name='gpt-3.5-turbo'),
    combine_docs_chain_kwargs={"prompt": qa_prompt},
    return_source_documents=True,
    retriever=vectorstore.as_retriever()
)

# 第一轮对话
chat_history = []
result = chain({"question": "I have Concussion.", "chat_history": chat_history})
print(result)

# 第二轮对话,构造正确的聊天历史
chat_history = [("I have Concussion.", result['answer'])]
result = chain({"question": "Cordova Bay.", "chat_history": chat_history})
print(result)

2. 关键修改说明

  • 通过Jinja2循环{% for human, ai in chat_history %},将元组列表格式化为Human: xxx\nAI: xxx的清晰对话结构,让模型能正确识别历史上下文。
  • 统一对话历史中问题的大小写(与首次提问保持一致),避免不必要的歧义。

效果验证

修改后,模型会读取格式化后的对话历史,第二次输入地点时会关联之前的脑震荡症状,输出符合预期的医生推荐结果。

内容的提问来源于stack exchange,提问作者nir doshi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 18:44:54