跳到主要內容
Open In ColabOpen on GitHub

如何使用父文檔檢索器

當分割文檔以進行檢索時,通常存在衝突的需求

  1. 您可能希望擁有小文檔,以便它們的嵌入可以最準確地反映其含義。如果太長,則嵌入可能會失去意義。
  2. 您希望文檔足夠長,以保留每個區塊的上下文。

ParentDocumentRetriever 通過分割和儲存小數據塊來平衡這種情況。在檢索期間,它首先獲取小塊,然後查找這些塊的父 ID 並返回那些較大的文檔。

請注意,「父文檔」是指小塊文檔的來源文檔。這可以是整個原始文檔,也可以是較大的塊。

from langchain.retrievers import ParentDocumentRetriever
from langchain.storage import InMemoryStore
from langchain_chroma import Chroma
from langchain_community.document_loaders import TextLoader
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
loaders = [
TextLoader("paul_graham_essay.txt"),
TextLoader("state_of_the_union.txt"),
]
docs = []
for loader in loaders:
docs.extend(loader.load())

檢索完整文檔

在此模式下,我們希望檢索完整文檔。因此,我們僅指定子分割器

# This text splitter is used to create the child documents
child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)
# The vectorstore to use to index the child chunks
vectorstore = Chroma(
collection_name="full_documents", embedding_function=OpenAIEmbeddings()
)
# The storage layer for the parent documents
store = InMemoryStore()
retriever = ParentDocumentRetriever(
vectorstore=vectorstore,
docstore=store,
child_splitter=child_splitter,
)
retriever.add_documents(docs, ids=None)

這應該產生兩個鍵,因為我們添加了兩個文檔。

list(store.yield_keys())
['9a63376c-58cc-42c9-b0f7-61f0e1a3a688',
'40091598-e918-4a18-9be0-f46413a95ae4']

現在調用向量儲存搜尋功能 - 我們應該看到它返回小塊(因為我們儲存的是小塊)。

sub_docs = vectorstore.similarity_search("justice breyer")
print(sub_docs[0].page_content)
Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. 

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.

現在從整體檢索器中檢索。這應該返回大文檔 - 因為它返回的是小塊所在的文檔。

retrieved_docs = retriever.invoke("justice breyer")
len(retrieved_docs[0].page_content)
38540

檢索較大塊

有時,完整文檔可能太大而無法按原樣檢索。在這種情況下,我們真正想做的是首先將原始文檔分割成較大的塊,然後再分割成較小的塊。然後我們索引較小的塊,但在檢索時我們檢索較大的塊(但仍然不是完整文檔)。

# This text splitter is used to create the parent documents
parent_splitter = RecursiveCharacterTextSplitter(chunk_size=2000)
# This text splitter is used to create the child documents
# It should create documents smaller than the parent
child_splitter = RecursiveCharacterTextSplitter(chunk_size=400)
# The vectorstore to use to index the child chunks
vectorstore = Chroma(
collection_name="split_parents", embedding_function=OpenAIEmbeddings()
)
# The storage layer for the parent documents
store = InMemoryStore()
retriever = ParentDocumentRetriever(
vectorstore=vectorstore,
docstore=store,
child_splitter=child_splitter,
parent_splitter=parent_splitter,
)
retriever.add_documents(docs)

我們可以看到現在有遠遠超過兩個文檔 - 這些是較大的塊。

len(list(store.yield_keys()))
66

讓我們確保底層向量儲存仍然檢索小塊。

sub_docs = vectorstore.similarity_search("justice breyer")
print(sub_docs[0].page_content)
Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service. 

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.
retrieved_docs = retriever.invoke("justice breyer")
len(retrieved_docs[0].page_content)
1849
print(retrieved_docs[0].page_content)
In state after state, new laws have been passed, not only to suppress the vote, but to subvert entire elections. 

We cannot let this happen.

Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.

Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.

A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.

And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system.

We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling.

We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers.

We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster.

We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.

此頁面是否有幫助?