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

如何在LangChain中限制LLM仅检索自定义文档内容

问题:LLM查询脱离自定义文档上下文的解决方法

我希望限制大语言模型(LLM)仅基于自定义文档回答查询,但目前仍会出现脱离上下文的结果。

生成索引代码

max_input_size = 4096
num_outputs = 512
max_chunk_overlap = 20
chunk_size_limit = 600
gpt_model_name='text-davinci-003'
        
prompt_helper = PromptHelper(max_input_size, num_outputs, max_chunk_overlap, chunk_size_limit=chunk_size_limit)
llm_predictor = LLMPredictor(llm=OpenAI(temperature=0, model_name=gpt_model_name, max_tokens=num_outputs))
documents = SimpleDirectoryReader('./static/').load_data()
index = GPTSimpleVectorIndex(documents, llm_predictor=llm_predictor, prompt_helper=prompt_helper)
index.save_to_disk('./static/dump/story.json')

查询代码

new_index = GPTSimpleVectorIndex.load_from_disk('./static/dump/story.json')
response = new_index.query("Only answer from provided content:"+ques,response_mode="compact")

解决方法

  • 强化Prompt约束:修改查询语句,明确要求模型仅使用文档内容回答,无相关信息时直接说明,避免编造。示例:
    response = new_index.query(f"请严格仅基于提供的自定义文档内容回答问题,若文档中无相关信息,直接回复'无法从提供的文档中找到相关信息'。问题:{ques}", response_mode="compact")
    
  • 验证LLM参数有效性:确认temperature=0已正确生效,该参数能最大化降低模型输出的随机性,让结果更贴合给定上下文。
  • 切换查询响应模式:尝试使用response_mode="tree_summarize",该模式会逐层整合文档片段信息,减少模型自行发挥的空间;或先用"no_text"模式获取相关文档片段,再基于片段构建精准回答。
  • 检查文档加载完整性:打印documents的长度和内容片段,确认SimpleDirectoryReader已完整加载./static/下的所有目标文档,无遗漏或加载错误。
  • 调整文档分块参数:当前分块可能导致上下文断裂,可尝试将chunk_size_limit调至1000、max_chunk_overlap调至50,让每个文档块包含更完整的语义信息,提升检索匹配度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 01:25:22