mirror of
https://github.com/hwchase17/langchain.git
synced 2026-03-18 11:07:36 +00:00
nb
This commit is contained in:
@@ -7,12 +7,12 @@
|
||||
"source": [
|
||||
"# Contextual Compression Retriever\n",
|
||||
"\n",
|
||||
"This notebook introduces the concept of DocumentFilter's and the ContextualCompressionRetriever. The core idea is simple: given a specific query, we should be able to return only the documents relevant to that query, and only the parts of those documents that are relevant. The ContextualCompressionsRetriever is a wrapper for another retriever that iterates over the initial output of the base retriever and filters and compresses those initial documents, so that only the most relevant information is returned."
|
||||
"This notebook introduces the concept of DocumentCompressors and the ContextualCompressionRetriever. The core idea is simple: given a specific query, we should be able to return only the documents relevant to that query, and only the parts of those documents that are relevant. The ContextualCompressionsRetriever is a wrapper for another retriever that iterates over the initial output of the base retriever and filters and compresses those initial documents, so that only the most relevant information is returned."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"execution_count": 21,
|
||||
"id": "28e8dc12",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
@@ -27,12 +27,12 @@
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Using a vanilla vector store retriever\n",
|
||||
"Let's start by initializing a simple vector store retriever. We can see that on an example question, it returns one or two relevant docs and a few irrelevant docs. And even the relevant docs have a lot of irrelevant information in them."
|
||||
"Let's start by initializing a simple vector store retriever and storing the 2023 State of the Union speech (in chunks). We can see that given an example question our retriever returns one or two relevant docs and a few irrelevant docs. And even the relevant docs have a lot of irrelevant information in them."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"execution_count": 22,
|
||||
"id": "9fbcc58f",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
@@ -118,30 +118,15 @@
|
||||
"id": "b7648612",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Adding contextual compression\n",
|
||||
"Now let's wrap our base retriever with a ContextualCompressionRetriever. We'll add an LLMChainDocumentCompressor to this compression retriever, which will iterate over the initially returned documents and extract from each only the content that is relevant to the query."
|
||||
"## Adding contextual compression with an `LLMChainExtractor`\n",
|
||||
"Now let's wrap our base retriever with a `ContextualCompressionRetriever`. We'll add an `LLMChainExtractor`, which will iterate over the initially returned documents and extract from each only the content that is relevant to the query."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"execution_count": 23,
|
||||
"id": "9a658023",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langchain.llms import OpenAI\n",
|
||||
"from langchain.retrievers import ContextualCompressionRetriever\n",
|
||||
"from langchain.retrievers.document_filters import LLMChainExtractionDocumentFilter\n",
|
||||
"\n",
|
||||
"_filter = LLMChainExtractionDocumentFilter.from_llm(OpenAI(temperature=0))\n",
|
||||
"compression_retriever = ContextualCompressionRetriever(base_filter=_filter, base_retriever=retriever)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "398622c5",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
@@ -160,6 +145,128 @@
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from langchain.llms import OpenAI\n",
|
||||
"from langchain.retrievers import ContextualCompressionRetriever\n",
|
||||
"from langchain.retrievers.document_compressors import LLMChainExtractor\n",
|
||||
"\n",
|
||||
"llm = OpenAI(temperature=0)\n",
|
||||
"compressor = LLMChainExtractor.from_llm(llm)\n",
|
||||
"compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever=retriever)\n",
|
||||
"\n",
|
||||
"compressed_docs = compression_retriever.get_relevant_documents(\"What did the president say about Ketanji Jackson Brown\")\n",
|
||||
"pretty_print_docs(compressed_docs)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "f3189dfd",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## More built-in compressors: filters\n",
|
||||
"### `LLMChainFilter`\n",
|
||||
"The `LLMChainFilter` is slightly simpler but more robust compressor that uses an LLM chain to decide which of the initially retrieved documents to filter out and which ones to return, without manipulating the document contents."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 24,
|
||||
"id": "65c47bee",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Document 1:\n",
|
||||
"\n",
|
||||
"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. \n",
|
||||
"\n",
|
||||
"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. \n",
|
||||
"\n",
|
||||
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
||||
"\n",
|
||||
"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.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from langchain.retrievers.document_compressors import LLMChainFilter\n",
|
||||
"\n",
|
||||
"_filter = LLMChainFilter.from_llm(llm)\n",
|
||||
"compression_retriever = ContextualCompressionRetriever(base_compressor=_filter, base_retriever=retriever)\n",
|
||||
"\n",
|
||||
"compressed_docs = compression_retriever.get_relevant_documents(\"What did the president say about Ketanji Jackson Brown\")\n",
|
||||
"pretty_print_docs(compressed_docs)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "b728e6d0",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"### `EmbeddingsFilter`\n",
|
||||
"\n",
|
||||
"Making an extra LLM call over each retrieved document is expensive and slow. The `EmbeddingsFilter` provides a cheaper and faster option by embedding the documents and query and only returning those documents which have sufficiently similar embeddings to the query."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 25,
|
||||
"id": "57382aa1",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Document 1:\n",
|
||||
"\n",
|
||||
"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. \n",
|
||||
"\n",
|
||||
"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. \n",
|
||||
"\n",
|
||||
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
||||
"\n",
|
||||
"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.\n",
|
||||
"----------------------------------------------------------------------------------------------------\n",
|
||||
"Document 2:\n",
|
||||
"\n",
|
||||
"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. \n",
|
||||
"\n",
|
||||
"And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system. \n",
|
||||
"\n",
|
||||
"We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling. \n",
|
||||
"\n",
|
||||
"We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers. \n",
|
||||
"\n",
|
||||
"We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster. \n",
|
||||
"\n",
|
||||
"We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.\n",
|
||||
"----------------------------------------------------------------------------------------------------\n",
|
||||
"Document 3:\n",
|
||||
"\n",
|
||||
"And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n",
|
||||
"\n",
|
||||
"As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. \n",
|
||||
"\n",
|
||||
"While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice. \n",
|
||||
"\n",
|
||||
"And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things. \n",
|
||||
"\n",
|
||||
"So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together. \n",
|
||||
"\n",
|
||||
"First, beat the opioid epidemic.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from langchain.embeddings import OpenAIEmbeddings\n",
|
||||
"from langchain.retrievers.document_compressors import EmbeddingsFilter\n",
|
||||
"\n",
|
||||
"embeddings = OpenAIEmbeddings()\n",
|
||||
"embeddings_filter = EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.76)\n",
|
||||
"compression_retriever = ContextualCompressionRetriever(base_compressor=embeddings_filter, base_retriever=retriever)\n",
|
||||
"\n",
|
||||
"compressed_docs = compression_retriever.get_relevant_documents(\"What did the president say about Ketanji Jackson Brown\")\n",
|
||||
"pretty_print_docs(compressed_docs)"
|
||||
]
|
||||
@@ -169,85 +276,64 @@
|
||||
"id": "07365d36",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Stringing together filters\n",
|
||||
"There are a number of built-in DocumentFilters that you can use, that can do things like identify the documents most relevant to the query or drop redundant documents. In fact, you can even combine several filters in sequence to create a pipeline of extraction and filtering. Here's an example:"
|
||||
"# Stringing compressors and document transformers together\n",
|
||||
"Using the `DocumentCompressorPipeline` we can also easily combine multiple compressors in sequence. Along with compressors we can add `BaseDocumentTransformer`s to our pipeline, which don't perform any contextual compression but simply perform some transformation on a set of documents. For example `TextSplitter`s can be used as document transformers to split documents into smaller pieces, and the `EmbeddingsRedundantFilter` can be used to filter out redundant documents based on embedding similarity between documents.\n",
|
||||
"\n",
|
||||
"Below we create a compressor pipeline by first splitting our docs into smaller chunks, then removing redundant documents, and then filtering based on relevance to the query."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"execution_count": 26,
|
||||
"id": "2a150a63",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from langchain.embeddings import OpenAIEmbeddings\n",
|
||||
"from langchain.retrievers.document_filters import (\n",
|
||||
" DocumentFilterPipeline,\n",
|
||||
" EmbeddingRedundantDocumentFilter,\n",
|
||||
" EmbeddingRelevancyDocumentFilter,\n",
|
||||
" SplitterDocumentFilter,\n",
|
||||
")\n",
|
||||
"from langchain.retrievers.document_filters.base import _RetrievedDocument\n",
|
||||
"from langchain.document_transformers import EmbeddingsRedundantFilter\n",
|
||||
"from langchain.retrievers.document_compressors import DocumentCompressorPipeline\n",
|
||||
"from langchain.text_splitter import CharacterTextSplitter\n",
|
||||
"embeddings = OpenAIEmbeddings()\n",
|
||||
"# 'Filter' that is just a wrapper for a text splitter\n",
|
||||
"splitter_filter = SplitterDocumentFilter(\n",
|
||||
" splitter=CharacterTextSplitter(chunk_size=300, chunk_overlap=0, separator=\". \")\n",
|
||||
")\n",
|
||||
"# Filter out redundant documents by comparing embeddings\n",
|
||||
"redundant_filter = EmbeddingRedundantDocumentFilter(embeddings=embeddings)\n",
|
||||
"# Filter out irrelevant documents by comparing document embeddings to the embedded query\n",
|
||||
"relevant_filter = EmbeddingRelevancyDocumentFilter(\n",
|
||||
" embeddings=embeddings, similarity_threshold=0.76\n",
|
||||
")\n",
|
||||
"pipeline_filter = DocumentFilterPipeline(\n",
|
||||
" filters=[splitter_filter, redundant_filter, relevant_filter]\n",
|
||||
"\n",
|
||||
"splitter = CharacterTextSplitter(chunk_size=300, chunk_overlap=0, separator=\". \")\n",
|
||||
"redundant_filter = EmbeddingsRedundantFilter(embeddings=embeddings)\n",
|
||||
"relevant_filter = EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.76)\n",
|
||||
"pipeline_compressor = DocumentCompressorPipeline(\n",
|
||||
" transformers=[splitter, redundant_filter, relevant_filter]\n",
|
||||
")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"execution_count": 27,
|
||||
"id": "3ceab64a",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Document 1:\n",
|
||||
"\n",
|
||||
"One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court. \n",
|
||||
"\n",
|
||||
"And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson\n",
|
||||
"----------------------------------------------------------------------------------------------------\n",
|
||||
"Document 2:\n",
|
||||
"\n",
|
||||
"As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential. \n",
|
||||
"\n",
|
||||
"While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year\n",
|
||||
"----------------------------------------------------------------------------------------------------\n",
|
||||
"Document 3:\n",
|
||||
"\n",
|
||||
"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\n"
|
||||
"ename": "ValidationError",
|
||||
"evalue": "1 validation error for ContextualCompressionRetriever\nbase_compressor\n Can't instantiate abstract class BaseDocumentCompressor with abstract methods acompress_documents, compress_documents (type=type_error)",
|
||||
"output_type": "error",
|
||||
"traceback": [
|
||||
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
|
||||
"\u001b[0;31mValidationError\u001b[0m Traceback (most recent call last)",
|
||||
"Cell \u001b[0;32mIn[27], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m compression_retriever \u001b[38;5;241m=\u001b[39m \u001b[43mContextualCompressionRetriever\u001b[49m\u001b[43m(\u001b[49m\u001b[43mbase_compressor\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mpipeline_compressor\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mbase_retriever\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43mretriever\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 3\u001b[0m compressed_docs \u001b[38;5;241m=\u001b[39m compression_retriever\u001b[38;5;241m.\u001b[39mget_relevant_documents(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mWhat did the president say about Ketanji Jackson Brown\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 4\u001b[0m pretty_print_docs(compressed_docs)\n",
|
||||
"File \u001b[0;32m~/langchain/.venv/lib/python3.9/site-packages/pydantic/main.py:341\u001b[0m, in \u001b[0;36mpydantic.main.BaseModel.__init__\u001b[0;34m()\u001b[0m\n",
|
||||
"\u001b[0;31mValidationError\u001b[0m: 1 validation error for ContextualCompressionRetriever\nbase_compressor\n Can't instantiate abstract class BaseDocumentCompressor with abstract methods acompress_documents, compress_documents (type=type_error)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"compression_retriever = ContextualCompressionRetriever(base_filter=pipeline_filter, base_retriever=retriever)\n",
|
||||
"compression_retriever = ContextualCompressionRetriever(base_compressor=pipeline_compressor, base_retriever=retriever)\n",
|
||||
"\n",
|
||||
"compressed_docs = compression_retriever.get_relevant_documents(\"What did the president say about Ketanji Jackson Brown\")\n",
|
||||
"pretty_print_docs(compressed_docs)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "87dcc583",
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "66beaded",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Results\n",
|
||||
"Here we create a sequence where we first split the initial documents into smaller documents, then we drop redundant documents, and finally we drop any documents not relevant to the query. The results aren't quite as good as the LLM-powered filter above, but we were able to do all this filtering much more quickly and cheaply by only using Embedding models."
|
||||
]
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
|
||||
Reference in New Issue
Block a user