Bird
Raised Fist0
LangChainframework~5 mins

Contextual compression in LangChain

Choose your learning style10 modes available
Introduction

Contextual compression helps reduce the size of text data while keeping its important meaning. This makes it easier and faster to process in language models.

When you want to send large text data to a language model but need to save space or speed up processing.
When you want to keep only the most important parts of a conversation or document for analysis.
When you want to improve performance by reducing unnecessary details in text inputs.
When working with limited memory or bandwidth and need smaller text chunks.
When preparing text data for embedding or search to focus on key information.
Syntax
LangChain
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.retrievers.document_compressors import LLMChainCompressor
from langchain.schema import Document

# Create a language model instance
llm = OpenAI(temperature=0)

# Create a prompt for compression
prompt = PromptTemplate(
    template="Compress the following text while keeping key information:\n\n{context}",
    input_variables=["context"]
)

# Create the LLM chain for compression
llm_chain = LLMChain(llm=llm, prompt=prompt)

# Create the compressor
compressor = LLMChainCompressor(llm_chain=llm_chain)

# Compress text (as document)
compressed_docs = compressor.compress_documents([Document(page_content=long_text)])
compressed_text = compressed_docs[0].page_content

The LLMChainCompressor uses a language model chain to contextually compress documents.

You need to provide an LLMChain instance (with prompt) to create the compressor.

Examples
This example shows how to create a compressor and compress a simple text string.
LangChain
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.retrievers.document_compressors import LLMChainCompressor
from langchain.schema import Document

llm = OpenAI(temperature=0)
prompt = PromptTemplate(input_variables=["context"], template="Compress: {context}")
llm_chain = LLMChain(llm=llm, prompt=prompt)
compressor = LLMChainCompressor(llm_chain=llm_chain)

text = "This is a long text that needs to be compressed."
compressed = compressor.compress_documents([Document(page_content=text)])[0].page_content
This example compresses a longer text, useful for documents or conversations.
LangChain
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.retrievers.document_compressors import LLMChainCompressor
from langchain.schema import Document

llm = OpenAI(temperature=0)
prompt = PromptTemplate(input_variables=["context"], template="Compress: {context}")
llm_chain = LLMChain(llm=llm, prompt=prompt)
compressor = LLMChainCompressor(llm_chain=llm_chain)

long_text = """Here is a very long document or conversation that you want to shorten while keeping the main ideas."""
compressed_text = compressor.compress_documents([Document(page_content=long_text)])[0].page_content
Sample Program

This program shows how to compress a paragraph using LLMChainCompressor. It prints the original and compressed text lengths and the compressed text itself.

LangChain
from langchain.llms import OpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain.retrievers.document_compressors import LLMChainCompressor
from langchain.schema import Document

# Initialize the language model
llm = OpenAI(temperature=0)

# Create compression prompt
prompt = PromptTemplate(
    input_variables=["context"],
    template="Compress the following text while preserving key meaning: {context}"
)

# Create LLM chain
llm_chain = LLMChain(llm=llm, prompt=prompt)

# Create compressor
compressor = LLMChainCompressor(llm_chain=llm_chain)

# Original long text
long_text = """LangChain helps developers build applications with language models. It provides tools to manage prompts, chains, and memory. Contextual compression reduces text size while keeping meaning."""

# Compress the text
doc = Document(page_content=long_text)
compressed_docs = compressor.compress_documents([doc])
compressed_text = compressed_docs[0].page_content

print("Original text length:", len(long_text))
print("Compressed text:", compressed_text)
print("Compressed text length:", len(compressed_text))
OutputSuccess
Important Notes

Contextual compression depends on the quality of the language model used.

It works best on longer texts where summarizing can reduce size significantly.

Always check the compressed output to ensure important details are kept.

Summary

Contextual compression shrinks text while keeping its main meaning.

It uses language models to summarize or compress text smartly.

Useful for saving space and speeding up text processing in language apps.

Practice

(1/5)
1. What is the main purpose of Contextual compression in langchain?
easy
A. To check grammar and spelling errors
B. To translate text into multiple languages
C. To generate random text from a prompt
D. To reduce text size while keeping its important meaning

Solution

  1. Step 1: Understand the goal of contextual compression

    Contextual compression aims to shrink text but keep its main meaning intact.
  2. Step 2: Compare options with this goal

    Only To reduce text size while keeping its important meaning matches this goal; others describe different tasks.
  3. Final Answer:

    To reduce text size while keeping its important meaning -> Option D
  4. Quick Check:

    Contextual compression = reduce text size + keep meaning [OK]
Hint: Focus on meaning retention while reducing text size [OK]
Common Mistakes:
  • Confusing compression with translation
  • Thinking it generates new text
  • Assuming it checks grammar
2. Which of the following is the correct way to create a ContextualCompressionRetriever in langchain?
easy
A. ContextualCompressionRetriever(base_retriever, llm)
B. ContextualCompressionRetriever(llm, base_retriever)
C. ContextualCompressionRetriever()
D. ContextualCompressionRetriever(llm)

Solution

  1. Step 1: Recall the constructor parameters order

    The correct order is base_retriever first, then llm.
  2. Step 2: Match options with correct order

    Only ContextualCompressionRetriever(base_retriever, llm) matches this order; others have wrong order or missing arguments.
  3. Final Answer:

    ContextualCompressionRetriever(base_retriever, llm) -> Option A
  4. Quick Check:

    Constructor order = base_retriever, llm [OK]
Hint: Remember: retriever first, then language model [OK]
Common Mistakes:
  • Swapping the order of parameters
  • Omitting required arguments
  • Using empty constructor
3. Given this code snippet, what will be the output type of compressed_docs?
from langchain.retrievers import ContextualCompressionRetriever
compressed_retriever = ContextualCompressionRetriever(base_retriever, llm)
compressed_docs = compressed_retriever.get_relevant_documents(query)
medium
A. A list of compressed Document objects
B. A single compressed string
C. A dictionary with original and compressed texts
D. An error because get_relevant_documents is undefined

Solution

  1. Step 1: Understand what get_relevant_documents returns

    It returns a list of Document objects relevant to the query.
  2. Step 2: Consider compression effect

    ContextualCompressionRetriever compresses content inside Document objects but still returns a list of Documents.
  3. Final Answer:

    A list of compressed Document objects -> Option A
  4. Quick Check:

    get_relevant_documents returns list of Documents [OK]
Hint: Retriever methods return lists of Documents, not strings [OK]
Common Mistakes:
  • Expecting a single string instead of list
  • Thinking it returns a dictionary
  • Assuming method does not exist
4. You wrote this code but get an error: TypeError: ContextualCompressionRetriever() missing 1 required positional argument. What is the likely cause?
compressed_retriever = ContextualCompressionRetriever(llm)
medium
A. You passed arguments in the wrong order
B. You forgot to pass the base retriever argument
C. You need to import ContextualCompressionRetriever differently
D. The llm argument is invalid

Solution

  1. Step 1: Check constructor requirements

    ContextualCompressionRetriever requires both base_retriever and llm arguments.
  2. Step 2: Analyze the error message and code

    The code passes only llm, missing base_retriever, causing the error.
  3. Final Answer:

    You forgot to pass the base retriever argument -> Option B
  4. Quick Check:

    Missing base retriever causes TypeError [OK]
Hint: Always pass base retriever first, then llm [OK]
Common Mistakes:
  • Passing only one argument
  • Swapping argument order
  • Ignoring error message details
5. You want to speed up document retrieval by compressing context but keep key info. Which approach best applies ContextualCompressionRetriever correctly in a langchain app?
hard
A. Replace your retriever with only an LLM that compresses text manually
B. Use ContextualCompressionRetriever without a base retriever to compress all documents at once
C. Wrap your existing retriever with ContextualCompressionRetriever passing your LLM, then query it
D. Compress documents before adding them to the retriever, then use a normal retriever

Solution

  1. Step 1: Understand how ContextualCompressionRetriever works

    It wraps an existing retriever and uses an LLM to compress retrieved documents on the fly.
  2. Step 2: Evaluate options for correct usage

    Wrap your existing retriever with ContextualCompressionRetriever passing your LLM, then query it correctly wraps the retriever with compression; others either omit retriever or do manual steps outside the pattern.
  3. Final Answer:

    Wrap your existing retriever with ContextualCompressionRetriever passing your LLM, then query it -> Option C
  4. Quick Check:

    Wrap retriever + LLM = ContextualCompressionRetriever usage [OK]
Hint: Wrap retriever with compression, don't replace or skip it [OK]
Common Mistakes:
  • Skipping base retriever wrapping
  • Trying to compress all docs at once without retriever
  • Replacing retriever with only LLM
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard