引言
在基于检索-生成(RAG)的应用中,当检索的文档数量增多时(例如超过十个),模型的性能可能会严重下降。这是因为模型容易错过长上下文中部的相关信息。而通常情况下,对向量存储的查询会按相关性降序返回文档(例如,使用嵌入的余弦相似度进行衡量)。为了缓解“中间丢失”效应,我们可以在检索后重新排序文档,使得最相关的文档位于上下文的两端,而最不相关的文档位于中间。这种方法可以帮助显现给大型语言模型(LLMs)最关键的信息。
主要内容
向量存储和嵌入
首先,我们需要获取一些文档的嵌入,并将其索引到一个(内存中的)Chroma 向量存储中。这里我们使用 Hugging Face 的嵌入模型,但任何 LangChain 的向量存储或嵌入模型都可以满足需求。
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) # 使用API代理服务提高访问稳定性
重排文档
LongContextReorder 文档转换器可以实现所描述的重排序过程,使得较不相关的文档位于列表中间,而较相关的文档在开头和结尾。
from langchain_community.document_transformers import LongContextReorder
# 重排文档
reordering = LongContextReorder()
reordered_docs = reordering.transform_documents(docs)
构建问答链
将重排后的文档集成到简单的问答链中:
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)
常见问题和解决方案
- API访问问题:由于某些地区的网络限制,开发者可能需要考虑使用API代理服务来提高访问稳定性。
- 文档排序不理想:如果排序结果不理想,可以尝试调整相关性得分的计算方式或使用不同的嵌入模型。
总结和进一步学习资源
本文介绍了如何通过重排检索结果来缓解“中间丢失”效应。这种方法有助于改善RAG应用中长上下文处理的效果。对于进一步的学习,建议查看以下资源:
参考资料
- LangChain 文档:langchain.readthedocs.io/
- Hugging Face Transformers:huggingface.co/docs/transf…
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---