跳到主要内容
BM25 (维基百科) 也称为 Okapi BM25,是一种用于信息检索系统的排序函数,用于评估文档与给定搜索查询的相关性。 BM25Retriever 检索器使用 rank_bm25 包。
pip install -qU  rank_bm25
from langchain_community.retrievers import BM25Retriever

使用文本创建新的检索器

retriever = BM25Retriever.from_texts(["foo", "bar", "world", "hello", "foo bar"])

使用文档创建新的检索器

您现在可以使用创建的文档创建一个新的检索器。
from langchain_core.documents import Document

retriever = BM25Retriever.from_documents(
    [
        Document(page_content="foo"),
        Document(page_content="bar"),
        Document(page_content="world"),
        Document(page_content="hello"),
        Document(page_content="foo bar"),
    ]
)

使用检索器

我们现在可以使用检索器了!
result = retriever.invoke("foo")
result
[Document(metadata={}, page_content='foo'),
 Document(metadata={}, page_content='foo bar'),
 Document(metadata={}, page_content='hello'),
 Document(metadata={}, page_content='world')]

预处理函数

向检索器传递自定义预处理函数以改进搜索结果。在单词级别对文本进行分词可以增强检索,尤其是在使用 Chroma、Pinecone 或 Faiss 等向量存储进行分块文档时。
import nltk

nltk.download("punkt_tab")
from nltk.tokenize import word_tokenize

retriever = BM25Retriever.from_documents(
    [
        Document(page_content="foo"),
        Document(page_content="bar"),
        Document(page_content="world"),
        Document(page_content="hello"),
        Document(page_content="foo bar"),
    ],
    k=2,
    preprocess_func=word_tokenize,
)

result = retriever.invoke("bar")
result
[Document(metadata={}, page_content='bar'),
 Document(metadata={}, page_content='foo bar')]

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.