0Pricing
AI Agents with LangChain & Autonomous Workflows · Lezione

Retriever e compressione contestuale

Trasformate un vector store in un retriever configurabile, controllate quanti documenti vengono restituiti e usate la compressione contestuale per rimuovere il testo irrilevante prima che raggiunga l’LLM.

Retriever e compressione contestuale è una lezione AI Agents with LangChain & Autonomous Workflows gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Agents with LangChain & Autonomous Workflows, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Agents with LangChain & Autonomous Workflows include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Retriever e compressione contestuale» è gratuita?

Sì — il testo completo di «Retriever e compressione contestuale» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Agents with LangChain & Autonomous Workflows, passa a CoddyKit PRO. Il corso AI Agents with LangChain & Autonomous Workflows include 4 lezioni in totale.

Cosa imparerò in «Retriever e compressione contestuale»?

Trasformate un vector store in un retriever configurabile, controllate quanti documenti vengono restituiti e usate la compressione contestuale per rimuovere il testo irrilevante prima che raggiunga l… Eserciti AI Agents with LangChain & Autonomous Workflows con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare AI Agents with LangChain & Autonomous Workflows?

Non è richiesta alcuna esperienza precedente. AI Agents with LangChain & Autonomous Workflows su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Retriever e compressione contestuale»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione AI Agents with LangChain & Autonomous Workflows?

Sì. Ogni lezione AI Agents with LangChain & Autonomous Workflows include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Spiegazione dei document loader
  2. Splitter di testo ed embeddings
  3. Vector store per il retrieval
  4. Retriever e compressione contestuale
← Torna a AI Agents with LangChain & Autonomous Workflows