LangChain / RAG / Vector DBs · บทเรียน

การจัดเก็บและเรียกคืนเวกเตอร์แทนความหมาย

นำกระบวนการสร้างเวกเตอร์แทนความหมายจากส่วนย่อยของเอกสาร และจัดเก็บไว้ในฐานข้อมูลเวกเตอร์เพื่อเรียกคืนภายหลังมาใช้

บทเรียน 3 จาก 411 ขั้นตอน

การจัดเก็บและเรียกคืนเวกเตอร์แทนความหมาย เป็นบทเรียน LangChain / RAG / Vector DBs ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน LangChain / RAG / Vector DBs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส LangChain / RAG / Vector DBs มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Storing & Retrieving Embeddings

Welcome to Lesson 3! In this lesson, we'll connect the dots between text chunks and vector databases.

You'll learn how to generate numerical representations (embeddings) from your document chunks and then store them efficiently in a vector database for quick and accurate retrieval.

Recap: Chunks & Embeddings

Before we dive in, let's quickly recap. From previous lessons, you know:

  • Document Chunks: Large documents are split into smaller, manageable pieces to fit LLM context windows and improve retrieval granularity.
  • Text Embeddings: These are numerical vectors that capture the semantic meaning of text. Similar texts have similar embeddings.

Our goal now is to turn those chunks into embeddings and make them searchable!

The Storage & Retrieval Flow

Here's the typical workflow for getting your data ready for RAG:

  1. Load & Split: Ingest raw documents and break them into chunks.
  2. Embed: Convert each text chunk into an embedding vector using an embedding model.
  3. Store: Save these embedding vectors (along with their original text chunks and metadata) in a vector database.
  4. Retrieve: When a user asks a question, embed the query, search the vector database for similar embeddings, and retrieve the most relevant chunks.

Initializing an Embedding Model

First, we need an embedding model. LangChain provides interfaces for many models, including those from OpenAI, Cohere, and local models like those from Hugging Face.

For this example, we'll use a local Hugging Face model to avoid needing an API key. This model turns text into a vector of numbers.

from langchain_community.embeddings import HuggingFaceEmbeddings

# Initialize a local embedding model
# This might download the model the first time
embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

print("Embedding model initialized successfully!")

Generating Embeddings from Text

Once our embedding model is ready, we can feed it text chunks. The model will then output a list of numbers (our embedding vector) for each chunk.

These vectors are what the vector database will use to find similar pieces of information.

from langchain_community.embeddings import HuggingFaceEmbeddings

embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

texts_to_embed = [
    "The quick brown fox jumps over the lazy dog.",
    "A canine named Fido is taking a nap."
]

# Generate embeddings for the texts
vectors = embeddings_model.embed_documents(texts_to_embed)

print(f"Number of vectors generated: {len(vectors)}")
print(f"Dimension of each vector: {len(vectors[0])}")
# print(f"First vector (partial): {vectors[0][:5]}...") # Too long for mobile

Introducing Vector Stores

A vector store is a specialized database designed to efficiently store and query high-dimensional vectors. It's built to quickly find vectors that are 'close' to a given query vector.

Think of it as a super-fast index for semantic meaning. When you search, it doesn't look for keywords; it looks for meaning.

LangChain supports many vector stores, from simple in-memory ones like FAISS to robust cloud services like Pinecone or Chroma.

Storing Embeddings with FAISS

Let's use FAISS, an in-memory vector store, to demonstrate storage. We'll take our text chunks and their embeddings and add them to FAISS. FAISS handles the indexing for fast search.

In a real application, you'd load chunks from documents first, then embed them, and finally store them. Here, we'll create simple documents directly.

from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.documents import Document

embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

# Create some example documents (text chunks with optional metadata)
documents = [
    Document(page_content="The capital of France is Paris.", metadata={"source": "geo"}),
    Document(page_content="Eiffel Tower is a landmark in Paris.", metadata={"source": "tourism"}),
    Document(page_content="Python is a popular programming language.", metadata={"source": "tech"}),
    Document(page_content="Coding with Python is fun and versatile.", metadata={"source": "tech"})
]

# Create a FAISS vector store from the documents and embeddings model
vectorstore = FAISS.from_documents(documents, embeddings_model)

print("Documents successfully stored in FAISS vector store!")

Performing a Similarity Search

Now that our documents are embedded and stored, we can query the vector store to find the most semantically similar documents to our question.

The vector store will embed your query, compare its vector to all stored vectors, and return the top 'k' (e.g., top 4) most similar documents.

from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.documents import Document

embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")

documents = [
    Document(page_content="The capital of France is Paris.", metadata={"source": "geo"}),
    Document(page_content="Eiffel Tower is a landmark in Paris.", metadata={"source": "tourism"}),
    Document(page_content="Python is a popular programming language.", metadata={"source": "tech"}),
    Document(page_content="Coding with Python is fun and versatile.", metadata={"source": "tech"})
]
vectorstore = FAISS.from_documents(documents, embeddings_model)

query = "What is the main city of France?"

# Perform a similarity search
retrieved_docs = vectorstore.similarity_search(query, k=2)

print(f"Query: '{query}'\n")
print("Top 2 retrieved documents:")
for i, doc in enumerate(retrieved_docs):
    print(f"{i+1}. Content: '{doc.page_content}' (Source: {doc.metadata['source']})")

Metadata is Your Friend

Notice in the previous example how we included metadata with our documents? This is incredibly powerful!

  • Filtering: You can filter searches based on metadata (e.g., only search documents from a specific author or date).
  • Context: Metadata helps the LLM understand the source and relevance of the retrieved chunk, improving answer quality.
  • Debugging: It's easier to trace where information came from.

Always consider what metadata is useful to store alongside your text chunks.

Quick Check

You've learned about the steps to prepare your data for a RAG system. What is the correct sequence for storing and retrieving information?

Recap: Storing & Retrieving

Great job! In this lesson, you've mastered the critical steps of preparing your data for a RAG system:

  • Initializing an embedding model to convert text into numerical vectors.
  • Understanding the role of a vector store for efficient storage and similarity search.
  • Implementing the process of generating embeddings and storing them (e.g., using FAISS).
  • Performing similarity searches to retrieve relevant document chunks based on a query.
  • Recognizing the importance of metadata for richer context and filtering.

These skills are fundamental to building effective RAG applications!

เริ่มต้นได้ฟรี

เรียนรู้ LangChain / RAG / Vector DBs ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
12
บทเรียน
48

คำถามที่พบบ่อย

บทเรียน “การจัดเก็บและเรียกคืนเวกเตอร์แทนความหมาย” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การจัดเก็บและเรียกคืนเวกเตอร์แทนความหมาย” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส LangChain / RAG / Vector DBs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส LangChain / RAG / Vector DBs มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การจัดเก็บและเรียกคืนเวกเตอร์แทนความหมาย”

นำกระบวนการสร้างเวกเตอร์แทนความหมายจากส่วนย่อยของเอกสาร และจัดเก็บไว้ในฐานข้อมูลเวกเตอร์เพื่อเรียกคืนภายหลังมาใช้ คุณปฏิบัติ LangChain / RAG / Vector DBs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน LangChain / RAG / Vector DBs หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน LangChain / RAG / Vector DBs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การจัดเก็บและเรียกคืนเวกเตอร์แทนความหมาย” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน LangChain / RAG / Vector DBs นี้ได้ไหม

ได้ บทเรียน LangChain / RAG / Vector DBs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ทำความเข้าใจเวกเตอร์แทนความหมายของข้อความ
  2. บทนำสู่ฐานข้อมูลเวกเตอร์
  3. การจัดเก็บและเรียกคืนเวกเตอร์แทนความหมาย
  4. การวัดความคล้ายคลึงของเวกเตอร์ฝังความหมาย
← กลับไปที่ LangChain / RAG / Vector DBs