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

基于Llama2与ConversationalRetrievalChain的RAG模型自问答问题求助

Llama2 RAG 自动自问自答问题解决方法

1. 适配Llama2专属对话模板

Llama2有固定的对话格式,默认的ConversationalRetrievalChain模板不匹配会导致模型输出逻辑混乱。自定义符合Llama2规范的prompt,明确约束模型仅回答问题,禁止生成额外内容:

from langchain.prompts import PromptTemplate

# 符合Llama2要求的对话模板
llama2_prompt = """<s>[INST] <<SYS>>
你是基于给定文档回答问题的助手,仅根据提供的文档内容作答,不得生成额外问题。
若无法从文档中找到答案,直接回复“我无法从提供的文档中找到相关答案”。
<</SYS>>

对话历史:
{chat_history}

当前问题:{question}
请给出准确回答:[/INST]"""

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

# 初始化链时绑定自定义prompt
qa_chain = ConversationalRetrievalChain.from_llm(
    llm,
    vectorstore.as_retriever(search_kwargs={'k': 2}),
    combine_docs_chain_kwargs={"prompt": PROMPT}
)

2. 调整模型生成参数

  • temperature=0会让模型输出过于僵化,容易陷入重复或异常逻辑,建议微调至0.1-0.3
  • top_p=0.1限制过严,可提高至0.7-0.9增加输出多样性
  • 添加Llama2专属停止标记stop=["</s>"],避免输出超出预期范围

修改后的模型初始化代码:

llm = LlamaCpp(model_path=model_path,
    temperature=0.2,
    max_tokens=2000,
    top_p=0.8,
    n_ctx=2048,
    stop=["</s>"]
)

3. 优化对话历史管理

过长的对话历史会超出模型上下文窗口,也可能干扰模型判断。限制历史保留轮数,避免上下文过载:

max_history_len = 3  # 最多保留3轮对话历史
chat_history = []  
while True:
    query = input('Prompt: ') 
    if query.lower() in ["exit", "quit", "q"]:  
        print('Exiting')
        sys.exit()
    result = qa_chain({'question': query, 'chat_history': chat_history})  
    print('Answer: ' + result['answer'] + '\n')
    chat_history.append((query, result['answer']))
    # 截断超出长度的历史
    if len(chat_history) > max_history_len:
        chat_history = chat_history[-max_history_len:]

4. 验证检索文档有效性

启用返回源文档功能,检查检索到的内容是否与问题相关,排除因检索无关文档导致的模型异常输出:

qa_chain = ConversationalRetrievalChain.from_llm(
    llm,
    vectorstore.as_retriever(search_kwargs={'k': 2}),
    combine_docs_chain_kwargs={"prompt": PROMPT},
    return_source_documents=True
)

# 执行查询后打印检索到的文档
result = qa_chain({'question': query, 'chat_history': chat_history})
print("检索到的关联文档:", [doc.page_content[:100] + "..." for doc in result['source_documents']])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 11:22:43