检索器与上下文压缩
将向量存储转化为可调节的检索器,控制返回的文档数量,并使用上下文压缩在内容到达 LLM 之前去除无关文本。
检索器与上下文压缩 是 CoddyKit 上的免费 AI Agents with LangChain & Autonomous Workflows 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Agents with LangChain & Autonomous Workflows 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Agents with LangChain & Autonomous Workflows 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
From Vector Store to Retriever
A vector store knows how to search, but agents talk to a retriever — a thin interface with one job: given a query, return relevant documents.
Any vector store exposes as_retriever() to produce one.
retriever = vectorstore.as_retriever()
docs = retriever.invoke('How do I reset my password?')Controlling k
The k parameter sets how many documents to return. Too few misses context; too many wastes tokens and adds noise.
retriever = vectorstore.as_retriever(
search_kwargs={'k': 4}
)Similarity Score Thresholds
Instead of a fixed count, you can return only documents above a relevance score. This avoids forcing irrelevant chunks when nothing good matches.
retriever = vectorstore.as_retriever(
search_type='similarity_score_threshold',
search_kwargs={'score_threshold': 0.7}
)Maximal Marginal Relevance
MMR balances relevance with diversity, avoiding near-duplicate chunks. It is great when documents repeat similar text.
retriever = vectorstore.as_retriever(
search_type='mmr',
search_kwargs={'k': 4, 'fetch_k': 20}
)Metadata Filtering
Documents carry metadata (source, date, category). You can filter retrieval to a subset, e.g. only the current product version.
retriever = vectorstore.as_retriever(
search_kwargs={'filter': {'version': 'v2'}}
)The Noise Problem
Even relevant chunks often contain unrelated sentences. Sending that noise to the LLM dilutes the answer and burns tokens.
Contextual compression shrinks each retrieved document to only the parts that matter for the query.
ContextualCompressionRetriever
This wrapper sits in front of a base retriever and post-processes its results with a compressor.
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(
base_compressor=compressor,
base_retriever=retriever
)How Extraction Works
LLMChainExtractor asks the LLM to pull only the sentences from each document that are relevant to the query, discarding the rest before it reaches the final prompt.
docs = compression_retriever.invoke(
'What is the refund window?'
)Cheaper Filters
LLM extraction costs tokens. EmbeddingsFilter is a faster, cheaper alternative that drops documents below a similarity threshold using embeddings only — no extra LLM call.
from langchain.retrievers.document_compressors import EmbeddingsFilter
compressor = EmbeddingsFilter(
embeddings=embeddings,
similarity_threshold=0.76
)Chaining Compressors
Combine steps in a DocumentCompressorPipeline: first a cheap embeddings filter, then LLM extraction on what survives. This keeps quality high while controlling cost.
from langchain.retrievers.document_compressors import DocumentCompressorPipeline
pipeline = DocumentCompressorPipeline(
transformers=[embeddings_filter, extractor]
)Plugging Into RAG
Because a compression retriever has the same interface as any retriever, you swap it into your RAG chain without changing the rest of the pipeline. Cleaner context usually means better, cheaper answers.
Quick Check
Test your retriever knowledge.
Recap
You learned to tune and refine retrieval:
- Convert a store with
as_retriever()and tunek - Use score thresholds, MMR, and metadata filters
- Contextual compression removes noisy text
EmbeddingsFilteris a cheap alternative to LLM extraction- Chain compressors for quality plus efficiency
Better retrieval is often the biggest lever for RAG quality.
用 AI 导师学习 AI Agents with LangChain & Autonomous Workflows — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 12
- 课程
- 50
常见问题解答
「检索器与上下文压缩」课时是免费的吗?
是的 — 「检索器与上下文压缩」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Agents with LangChain & Autonomous Workflows 课程的其余内容,请升级到 CoddyKit PRO。 AI Agents with LangChain & Autonomous Workflows 课程共包含 4 节课。
「检索器与上下文压缩」这节课中我会学到什么?
将向量存储转化为可调节的检索器,控制返回的文档数量,并使用上下文压缩在内容到达 LLM 之前去除无关文本。 你通过在浏览器中直接运行的动手代码来练习 AI Agents with LangChain & Autonomous Workflows,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Agents with LangChain & Autonomous Workflows 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Agents with LangChain & Autonomous Workflows 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「检索器与上下文压缩」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Agents with LangChain & Autonomous Workflows 课中编写并运行代码吗?
能。每节 AI Agents with LangChain & Autonomous Workflows 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。