การบีบอัดบริบทด้วย LLM
เพิ่มประสิทธิภาพบริบทที่ส่งให้ LLM ด้วยการกรองและบีบอัดเอกสารที่เรียกคืนมาแบบไดนามิก เพื่อเน้นข้อมูลที่เกี่ยวข้อง
การบีบอัดบริบทด้วย LLM เป็นบทเรียน LangChain / RAG / Vector DBs ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน LangChain / RAG / Vector DBs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส LangChain / RAG / Vector DBs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Compress Context?
When building RAG (Retrieval Augmented Generation) systems, Large Language Models (LLMs) have a limited context window. Feeding them too much irrelevant information can lead to several problems:
- Performance issues: LLMs might get confused by noise.
- Higher costs: More tokens mean higher API bills.
- Slower responses: More text takes longer to process.
This is where contextual compression comes in!
What is Contextual Compression?
Contextual compression is a technique used to refine the documents retrieved by your RAG system before they are passed to the LLM. It acts as a smart filter and extractor.
- Filter: Remove entire documents that are less relevant.
- Extract: From the remaining documents, identify and keep only the most pertinent sentences or paragraphs related to the user's query.
Think of it like highlighting the most important parts of a long article.
The Base Retriever's Role
Contextual compression doesn't replace your initial retrieval mechanism. Instead, it works on top of it.
- You still need a base retriever (e.g., a vector store retriever) to fetch an initial set of potentially relevant documents.
- The compressor then takes these documents and applies its logic to narrow down or condense their content.
It's a refinement step, not a substitute for finding the initial information.
Introducing LangChain's Tools
LangChain provides excellent tools for implementing contextual compression:
- The
ContextualCompressionRetrieveris the main component. It wraps your base retriever and a document compressor. - A document compressor (e.g., an LLM-based one) is the actual logic that filters or extracts information from the documents.
Let's see how to set up a dummy base retriever first.
Setting Up a Base Retriever
Here's a simple dummy retriever. In a real application, this would typically connect to a vector database like Pinecone or Chroma.
from langchain_core.documents import Document
class SimpleBaseRetriever:
def get_relevant_documents(self, query: str):
if "programming" in query.lower() or "python" in query.lower():
return [
Document(page_content="Python is a versatile programming language. Used in AI & web dev."),
Document(page_content="Java is popular for enterprise apps."),
Document(page_content="Data science uses Python for analysis & ML."),
Document(page_content="History of programming languages dates back centuries.")
]
return [
Document(page_content="The quick brown fox jumps over the lazy dog."),
Document(page_content="Cats enjoy napping in sunny spots, especially in the sun."),
Document(page_content="A computer processes data very quickly and efficiently.")
]
base_retriever = SimpleBaseRetriever()
print("Base retriever initialized.")
# Example usage:
# docs = base_retriever.get_relevant_documents("python")
# for doc in docs: print(doc.page_content)LLMs as Document Compressors
One of the most powerful ways to compress context is by using another LLM! An LLM can intelligently understand the query and the retrieved documents, then extract only the most relevant sentences.
- This goes beyond simple keyword matching.
- It leverages the LLM's understanding of semantics.
LangChain provides specific compressors that use LLMs for this task.
Using LLMChainExtractor (Code)
The LLMChainExtractor uses an LLM to extract relevant sections from documents. Here's how to set it up along with the ContextualCompressionRetriever.
from langchain_core.documents import Document
from langchain.retrievers.document_compressors import LLMChainExtractor
from langchain.retrievers import ContextualCompressionRetriever
from langchain_openai import OpenAI # pip install langchain-openai
# --- Dummy Base Retriever (for standalone runnable) ---
class SimpleBaseRetriever:
def get_relevant_documents(self, query: str):
if "programming" in query.lower() or "python" in query.lower():
return [
Document(page_content="Python is a versatile programming language. Used in AI & web dev."),
Document(page_content="Java is popular for enterprise apps."),
Document(page_content="Data science uses Python for analysis & ML."),
Document(page_content="History of programming languages dates back centuries.")
]
return [
Document(page_content="The quick brown fox jumps over the lazy dog."),
Document(page_content="Cats enjoy napping in sunny spots, especially in the sun."),
Document(page_content="A computer processes data very quickly and efficiently.")
]
base_retriever = SimpleBaseRetriever()
# --- LLM for Compression ---
# NOTE: You need to set your OpenAI API key as an environment variable
# e.g., import os; os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"
# Ensure 'langchain-openai' is installed (pip install langchain-openai).
llm = OpenAI(temperature=0.1) # Low temp for focused extraction
# --- Create the Extractor and Compression Retriever ---
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(
base_compressor=compressor,
base_retriever=base_retriever
)
print("LLMChainExtractor and ContextualCompressionRetriever initialized!")Running Compressed Retrieval (Code)
Now, let's run a query and observe how the ContextualCompressionRetriever (using LLMChainExtractor) processes the documents. Pay attention to the length of the document content!
from langchain_core.documents import Document
from langchain.retrievers.document_compressors import LLMChainExtractor
from langchain.retrievers import ContextualCompressionRetriever
from langchain_openai import OpenAI # pip install langchain-openai
# --- Dummy Base Retriever (re-defined for standalone runnable) ---
class SimpleBaseRetriever:
def get_relevant_documents(self, query: str):
if "programming" in query.lower() or "python" in query.lower():
return [
Document(page_content="Python is a versatile programming language. Used in AI & web dev."),
Document(page_content="Java is popular for enterprise apps."),
Document(page_content="Data science uses Python for analysis & ML."),
Document(page_content="History of programming languages dates back centuries.")
]
return [
Document(page_content="The quick brown fox jumps over the lazy dog."),
Document(page_content="Cats enjoy napping in sunny spots, especially in the sun."),
Document(page_content="A computer processes data very quickly and efficiently.")
]
base_retriever = SimpleBaseRetriever()
# --- LLM for Compression (re-defined for standalone runnable) ---
# NOTE: You need to set your OpenAI API key as an environment variable
# Ensure 'langchain-openai' is installed.
llm = OpenAI(temperature=0.1)
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(
base_compressor=compressor,
base_retriever=base_retriever
)
# --- Run a Query ---
query = "What is Python used for?"
print(f"Query: '{query}'\n")
print("--- Original (simulated) documents ---")
original_docs = base_retriever.get_relevant_documents(query)
for i, doc in enumerate(original_docs):
print(f"Doc {i+1} (Chars: {len(doc.page_content)}): {doc.page_content}")
print(f"Total original documents: {len(original_docs)}\n")
print("--- Content after compression ---")
compressed_docs = compression_retriever.get_relevant_documents(query)
for i, doc in enumerate(compressed_docs):
# The LLMChainExtractor modifies the page_content of existing docs
print(f"Compressed Doc {i+1} (Chars: {len(doc.page_content)}): {doc.page_content}")
print(f"Total compressed documents: {len(compressed_docs)}")Other Compression Options
LangChain offers more than just LLMChainExtractor:
LLMChainFilter: Uses an LLM to decide if an entire document is relevant enough to keep, rather than extracting parts.EmbeddingsFilter: Filters documents based on the semantic similarity of their embeddings to the query. This is often faster but less nuanced than LLM-based filtering.DocumentCompressorPipeline: Allows you to chain multiple compressors together for complex logic!
Why Compression Matters
Contextual compression is a powerful technique for optimizing RAG systems:
- Improved Relevance: LLMs receive more focused, pertinent information.
- Reduced Cost: Fewer tokens are sent to the LLM API.
- Faster Responses: LLMs process less text, leading to quicker answers.
- Better Accuracy: Less irrelevant noise reduces the chance of LLM hallucinations.
It helps you get more out of your LLMs while saving resources!
Compression Check
Test your understanding of contextual compression!
Contextual Compression Recap
We've explored how contextual compression refines retrieved documents for LLMs:
- It's a post-retrieval step that filters and extracts key information.
- LangChain's
ContextualCompressionRetrieverwraps a base retriever and a document compressor. LLMChainExtractoruses an LLM to intelligently extract relevant snippets.- Benefits include improved relevance, reduced costs, faster responses, and better accuracy.
This technique is vital for optimizing RAG systems, especially with large knowledge bases.
คำถามที่พบบ่อย
บทเรียน “การบีบอัดบริบทด้วย LLM” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การบีบอัดบริบทด้วย LLM” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส LangChain / RAG / Vector DBs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส LangChain / RAG / Vector DBs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การบีบอัดบริบทด้วย LLM”
เพิ่มประสิทธิภาพบริบทที่ส่งให้ LLM ด้วยการกรองและบีบอัดเอกสารที่เรียกคืนมาแบบไดนามิก เพื่อเน้นข้อมูลที่เกี่ยวข้อง คุณปฏิบัติ LangChain / RAG / Vector DBs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน LangChain / RAG / Vector DBs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน LangChain / RAG / Vector DBs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การบีบอัดบริบทด้วย LLM” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน LangChain / RAG / Vector DBs นี้ได้ไหม
ได้ บทเรียน LangChain / RAG / Vector DBs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- กลยุทธ์การเรียกคืนจากหลายคำค้น
- การบีบอัดบริบทด้วย LLM
- การค้นหาแบบผสมและการจัดอันดับใหม่
- การค้นคืนเอกสารแม่และหน้าต่างประโยค