
🧠 图解记忆: 长上下文不是无限记忆;关键证据要少、准、放得对,可用重排、压缩、结构化和分步检索缓解。
💡 答案要点
Lost in the Middle 问题:
Prompt结构:
[重要-开头] [不重要] [重要-中间!] [不重要] [重要-结尾]
LLM关注度:
★★★★★ ★☆☆☆☆ ★★★ ★☆☆☆☆ ★★★★★
↑ ↑
└────── 容易被LLM忽略 ──────┘
→ 中间部分的信息容易被LLM"忘记"解决方案:
方案1:逆向序列化(Reverse Process)
python
# 将重要信息放在开头或结尾(LLM更关注的位置)
def reverse_context_window(docs, max_tokens=3000):
"""把检索结果逆序排列,中间放不太重要的"""
if len(docs) <= 3:
return docs
# 按相关性排序:最高放开头,最低放中间,次高放结尾
sorted_docs = sorted(docs, key=lambda x: x['score'], reverse=True)
# 构建上下文:最高 → 最低 → 次高
context = [
sorted_docs[0], # 最高相关性放开头
sorted_docs[-1], # 最低放中间(最容易被忽略)
sorted_docs[1] # 次高放结尾
]
return context方案2:上下文压缩(Context Compression)
python
# 使用 LLMLingua 等工具压缩上下文
from llmlingua import PromptCompressor
compressor = PromptCompressor()
compressed = compressor.compress(
prompt=full_context,
instruction="回答用户关于X的问题",
target_token=2000 # 压缩到2000 tokens
)
# 保留关键信息,去除冗余方案3:滑动窗口 + 重叠分块
python
# 重叠分块确保关键信息不被截断
def sliding_window_chunk(text, chunk_size=500, overlap=100):
chunks = []
for i in range(0, len(text), chunk_size - overlap):
chunks.append(text[i:i+chunk_size])
return chunks
# 重叠100 tokens,防止关键信息被切断方案4:Big Bird(稀疏注意力)
python
# Big Bird 的三种注意力机制:
# 1. 全局注意力(开头/结尾token)
# 2. 随机注意力(随机采样一些token)
# 3. 滑动窗口注意力(局部上下文)
# → 确保中间信息被关注面试话术:
"Lost in the Middle 是 RAG 的经典问题——LLM 对上下文中间部分关注度最低。我的解法是:先把检索结果逆序排列(最高相关→最低→次高),让重要信息尽量靠前或靠后;其次用 LLMLingua 做上下文压缩,去掉冗余保留关键;还有滑动窗口重叠分块,防止信息在 chunk 边界被切断。"
📚 参考:Lost in the Middle: How Language Models Use Long Contexts(原论文)