0Pricing
AI Agents with LangChain & Autonomous Workflows · Lección

Retrievers y compresión contextual

Convierta un almacén vectorial en un retriever configurable, controle cuántos documentos se devuelven y use la compresión contextual para eliminar el texto irrelevante antes de que llegue al LLM.

Retrievers y compresión contextual es una lección gratuita de AI Agents with LangChain & Autonomous Workflows en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de AI Agents with LangChain & Autonomous Workflows, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de AI Agents with LangChain & Autonomous Workflows incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en 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 tune k
  • Use score thresholds, MMR, and metadata filters
  • Contextual compression removes noisy text
  • EmbeddingsFilter is a cheap alternative to LLM extraction
  • Chain compressors for quality plus efficiency

Better retrieval is often the biggest lever for RAG quality.

Preguntas frecuentes

¿La lección «Retrievers y compresión contextual» es gratis?

Sí — el texto completo de «Retrievers y compresión contextual» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de AI Agents with LangChain & Autonomous Workflows, actualiza a CoddyKit PRO. El curso de AI Agents with LangChain & Autonomous Workflows incluye 4 lecciones en total.

¿Qué aprenderé en «Retrievers y compresión contextual»?

Convierta un almacén vectorial en un retriever configurable, controle cuántos documentos se devuelven y use la compresión contextual para eliminar el texto irrelevante antes de que llegue al LLM. Practicas AI Agents with LangChain & Autonomous Workflows con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar AI Agents with LangChain & Autonomous Workflows?

No se requiere experiencia previa. AI Agents with LangChain & Autonomous Workflows en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Retrievers y compresión contextual»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de AI Agents with LangChain & Autonomous Workflows?

Sí. Cada lección de AI Agents with LangChain & Autonomous Workflows incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Explicación de los cargadores de documentos
  2. Divisores de texto y embeddings
  3. Almacenes vectoriales para recuperación
  4. Retrievers y compresión contextual
← Volver a AI Agents with LangChain & Autonomous Workflows