Recuperadores e compressão contextual
Transforme um armazenamento vetorial em um recuperador ajustável, controle quantos documentos retornam e use compressão contextual para remover textos irrelevantes antes que cheguem ao LLM.
Recuperadores e compressão contextual é uma aula grátis de AI Agents with LangChain & Autonomous Workflows no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de AI Agents with LangChain & Autonomous Workflows, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Agents with LangChain & Autonomous Workflows inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Aprenda AI Agents with LangChain & Autonomous Workflows com um tutor de IA — grátis
Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.
- Cursos
- 12
- Aulas
- 50
Perguntas Frequentes
A aula “Recuperadores e compressão contextual” é grátis?
Sim — o texto completo de “Recuperadores e compressão contextual” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de AI Agents with LangChain & Autonomous Workflows, atualize para CoddyKit PRO. O curso de AI Agents with LangChain & Autonomous Workflows inclui 4 aulas no total.
O que vou aprender em “Recuperadores e compressão contextual”?
Transforme um armazenamento vetorial em um recuperador ajustável, controle quantos documentos retornam e use compressão contextual para remover textos irrelevantes antes que cheguem ao LLM. Você pratica AI Agents with LangChain & Autonomous Workflows com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar AI Agents with LangChain & Autonomous Workflows?
Nenhuma experiência prévia é necessária. AI Agents with LangChain & Autonomous Workflows no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Recuperadores e compressão contextual”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de AI Agents with LangChain & Autonomous Workflows?
Sim. Cada aula de AI Agents with LangChain & Autonomous Workflows inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Explicação dos carregadores de documentos
- Divisores de texto e incorporações
- Armazenamentos vetoriais para recuperação
- Recuperadores e compressão contextual