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

Langchain ConversationalRetrievalChain问答机器人:追问回答含前置无关问题

问答机器人异常问题排查与解决

问题现象

  • 首次提问what is pql?时,机器人回答正常
  • 输入tell me more进行追问时,回答内容准确,但开头会附加无关问题(例如Where can I find more information about PQL?)

相关代码

conversation = ConversationalRetrievalChain.from_llm(
                llm=ChatOpenAI(model_name="gpt-3.5-turbo",temperature=0, streaming=True, callbacks=[StreamingStdOutCallbackHandler()]),
                retriever=vectorstore.as_retriever(search_kwargs={"k": 1}),
                memory=self.memory
            )
conversation({"question": self.question, 'chat_history': self.memory})

问题原因与解决方案

原因

ConversationalRetrievalChain默认会将追问重构为完整独立问题,在流式输出场景下,这个重构的问题可能被错误混入最终回答内容中。

解决方案

  1. 自定义提示模板:修改链的提示模板,明确要求直接回答,避免多余的问题重构内容输出
from langchain.prompts import PromptTemplate

# 自定义提示模板,移除冗余的问题重构逻辑
prompt_template = """基于对话历史和后续问题,结合上下文直接给出答案,不要附加额外疑问:
对话历史: {chat_history}
后续问题: {question}
上下文: {context}
回答:"""

PROMPT = PromptTemplate(
    template=prompt_template, input_variables=["chat_history", "question", "context"]
)

conversation = ConversationalRetrievalChain.from_llm(
    llm=ChatOpenAI(model_name="gpt-3.5-turbo",temperature=0, streaming=True, callbacks=[StreamingStdOutCallbackHandler()]),
    retriever=vectorstore.as_retriever(search_kwargs={"k": 1}),
    memory=self.memory,
    combine_docs_chain_kwargs={"prompt": PROMPT}
)
  1. 调整链参数:初始化链时,确保memory正确传递,避免历史对话格式干扰输出;若使用流式输出,可通过回调函数过滤输出内容,剔除无关的重构问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 22:36:27