การค้นคืนข้อมูลตามบริบท
สร้างกลยุทธ์สำหรับค้นคืนบริบทที่เกี่ยวข้องที่สุดจากคลังเวกเตอร์ เพื่อนำไปเสริมพรอมต์ของ LLM
การค้นคืนข้อมูลตามบริบท เป็นบทเรียน Vector Databases: Pinecone, Weaviate & pgvector ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Vector Databases: Pinecone, Weaviate & pgvector และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Vector Databases: Pinecone, Weaviate & pgvector มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What is Context Retrieval?
In a Retrieval-Augmented Generation (RAG) system, the Large Language Model (LLM) needs relevant information to generate accurate responses.
- Contextual Information Retrieval is the process of finding and fetching this relevant data from your vector database.
- It's the bridge that connects the user's query to the knowledge stored in your specialized data.
The Retrieval Workflow
When a user asks a question, several steps happen to get the right context:
- The user's question (query) is converted into a vector embedding.
- This query embedding is sent to the vector database.
- The vector database searches for stored document embeddings that are most similar to the query embedding.
- The text chunks associated with these similar embeddings are retrieved and sent to the LLM.
Vector Similarity Basics
The core of retrieval is vector similarity. Your vector database calculates how 'close' your query vector is to all the stored document vectors.
- Closer vectors mean higher semantic similarity.
- Common similarity metrics include cosine similarity or Euclidean distance.
- The database efficiently finds the closest vectors, usually using specialized indexing techniques.
Simple Top-K Retrieval
The most straightforward retrieval strategy is Top-K Retrieval.
- You simply ask the vector database to return the
Kmost similar document chunks to your query. Kis a number you choose (e.g., 3, 5, or 10), representing how many pieces of context you want to provide to the LLM.- While simple, choosing the right
Kis crucial for balancing relevance and LLM token limits.
Python Top-K Retrieval Demo
This simple Python code simulates a vector store and demonstrates how top_k retrieval works. Try changing the top_k value!
import math
class SimpleVectorStore:
def __init__(self):
self.vectors = {}
def add_document(self, doc_id, vector, text):
self.vectors[doc_id] = {"vector": vector, "text": text}
def _cosine_similarity(self, vec1, vec2):
dot_product = sum(v1 * v2 for v1, v2 in zip(vec1, vec2))
magnitude1 = math.sqrt(sum(v**2 for v in vec1))
magnitude2 = math.sqrt(sum(v**2 for v in vec2))
if magnitude1 == 0 or magnitude2 == 0:
return 0.0
return dot_product / (magnitude1 * magnitude2)
def query(self, query_vector, top_k=3):
similarities = []
for doc_id, data in self.vectors.items():
sim = self._cosine_similarity(query_vector, data["vector"])
similarities.append((sim, doc_id, data["text"]))
similarities.sort(key=lambda x: x[0], reverse=True)
return [{"id": s[1], "text": s[2], "similarity": s[0]} for s in similarities[:top_k]]
if __name__ == "__main__":
store = SimpleVectorStore()
store.add_document("doc1", [0.1, 0.2, 0.3], "The quick brown fox jumps over the lazy dog.")
store.add_document("doc2", [0.15, 0.25, 0.35], "A fast fox leaps over a sleepy canine.")
store.add_document("doc3", [0.8, 0.7, 0.9], "Artificial intelligence is transforming industries.")
store.add_document("doc4", [0.75, 0.85, 0.95], "Machine learning algorithms are key to AI.")
query_vec = [0.12, 0.22, 0.32] # Simulating an embedding for "fast animal"
print("--- Top 2 Relevant Chunks ---")
results = store.query(query_vec, top_k=2)
for res in results:
print(f"ID: {res['id']}, Sim: {res['similarity']:.2f}, Text: {res['text']}")
print("\n--- Top 1 Relevant Chunk ---")
results_single = store.query(query_vec, top_k=1)
for res in results_single:
print(f"ID: {res['id']}, Sim: {res['similarity']:.2f}, Text: {res['text']}")Chunking for Effective Retrieval
The quality of your retrieval heavily depends on how your original documents were broken down into chunks before being embedded.
- Chunk Size: Too small, and context might be lost. Too large, and irrelevant information might be included.
- Overlap: Adding overlap between chunks helps ensure that important information isn't split across boundaries.
- Good chunking ensures each retrieved piece of context is meaningful and self-contained.
Enhancing Retrieval with Re-ranking
Sometimes, simple Top-K retrieval isn't enough. The most 'similar' vectors aren't always the most 'relevant' in context.
- Re-ranking is an optional but powerful step performed after initial retrieval.
- It takes the top K chunks from the vector database and uses a smaller, more specialized model to score their relevance more deeply.
- This secondary scoring helps filter out less useful chunks and prioritize truly pertinent information.
The Need for Re-ranking
Why do we need re-ranking?
- Vector similarity can sometimes be fooled by superficial semantic closeness.
- A re-ranker, often a smaller transformer model, can better understand the nuanced relationship between the query and the retrieved document chunks.
- It helps ensure the context provided to the LLM is not only similar but also highly relevant and useful for answering the user's specific question.
Advanced Retrieval Concepts
Beyond basic Top-K and re-ranking, advanced strategies can further improve retrieval:
- Query Expansion: Rewriting or adding terms to the user's original query to improve search results.
- Hybrid Search: Combining traditional keyword search (like full-text search) with vector similarity for a more comprehensive retrieval.
- These methods aim to make the initial retrieval even more robust before context is sent to the LLM.
Check Your Knowledge
Consider a RAG system that initially retrieves 10 document chunks using vector similarity. What are key benefits of adding a re-ranking step?
Contextual Retrieval Summary
You've learned how to retrieve relevant context for RAG systems!
- Contextual retrieval bridges user queries and stored knowledge.
- It involves converting queries to embeddings, querying the vector DB for similar vectors, and fetching associated text.
- Top-K retrieval is the basic method, but good chunking is vital.
- Re-ranking can further refine results by applying a secondary relevance filter.
- Advanced techniques like query expansion and hybrid search offer even more sophisticated retrieval.
เรียนรู้ Vector Databases: Pinecone, Weaviate & pgvector ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 12
- บทเรียน
- 48
คำถามที่พบบ่อย
บทเรียน “การค้นคืนข้อมูลตามบริบท” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การค้นคืนข้อมูลตามบริบท” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Vector Databases: Pinecone, Weaviate & pgvector ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Vector Databases: Pinecone, Weaviate & pgvector มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การค้นคืนข้อมูลตามบริบท”
สร้างกลยุทธ์สำหรับค้นคืนบริบทที่เกี่ยวข้องที่สุดจากคลังเวกเตอร์ เพื่อนำไปเสริมพรอมต์ของ LLM คุณปฏิบัติ Vector Databases: Pinecone, Weaviate & pgvector ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Vector Databases: Pinecone, Weaviate & pgvector หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Vector Databases: Pinecone, Weaviate & pgvector บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การค้นคืนข้อมูลตามบริบท” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Vector Databases: Pinecone, Weaviate & pgvector นี้ได้ไหม
ได้ บทเรียน Vector Databases: Pinecone, Weaviate & pgvector ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ภาพรวมสถาปัตยกรรมระบบ RAG
- การผสานเข้ากับกรอบการทำงาน LLM
- การค้นคืนข้อมูลตามบริบท
- กลยุทธ์การแบ่งส่วนสำหรับ RAG