0Pricing
AI Agents with LangChain & Autonomous Workflows · บทเรียน

คลังเวกเตอร์สำหรับการดึงข้อมูล

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

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

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

Intro to Vector Stores

Welcome to the final lesson on Data Loading & Retrieval! Today, we'll dive into Vector Stores, a crucial component for building intelligent AI agents.

Think of vector stores as specialized databases designed to store and efficiently search through numerical representations of information, called embeddings.

Why Vector Stores for RAG?

Vector stores are the backbone of Retrieval Augmented Generation (RAG). RAG allows Large Language Models (LLMs) to access external, up-to-date information, overcoming their inherent limitations like:

  • Knowledge cutoffs: LLMs only know what they were trained on.
  • Hallucinations: Making up facts when uncertain.

Vector stores provide the relevant context for the LLM to generate accurate responses.

How Vector Stores Work

When you have text documents (which you learned to load and split in previous lessons), they are first converted into numerical embeddings.

These embeddings are then stored in a vector store. When a query comes in, it's also converted into an embedding. The vector store then finds document embeddings that are 'closest' (most similar) to the query embedding.

LangChain's VectorStore Abstraction

LangChain provides a powerful abstraction for interacting with various vector stores. This means you can swap out different vector database providers (like Chroma, Pinecone, FAISS) with minimal code changes.

Key methods include from_documents() to create a store from documents, add_documents() to add more, and similarity_search() to find relevant content.

Local Store: ChromaDB

For our examples, we'll use ChromaDB. It's an open-source, lightweight vector database that can run locally, making it perfect for development and testing without needing cloud services.

First, make sure you have the necessary packages installed:

  • pip install chromadb
  • pip install langchain-community
  • pip install sentence-transformers

Initializing Chroma & Embeddings

Let's set up ChromaDB with a local embedding model. The embedding model converts text into vectors.

This example uses SentenceTransformerEmbeddings, which runs directly on your machine.

from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import SentenceTransformerEmbeddings
import os

def main():
    # Define a path for ChromaDB to store data locally
    # This creates a 'chroma_db' folder if it doesn't exist
    persist_directory = "./chroma_db"
    
    # Initialize a local embedding function
    # 'all-MiniLM-L6-v2' is a small, efficient model
    embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
    
    # Initialize ChromaDB. It will load if exists, or create new.
    vectordb = Chroma(
        persist_directory=persist_directory,
        embedding_function=embeddings
    )
    
    print("ChromaDB initialized successfully!")
    print(f"Database will persist at: {os.path.abspath(persist_directory)}")

if __name__ == "__main__":
    main()

Adding Documents to Chroma

Once initialized, we can add Document objects (which contain page_content and optional metadata) to our vector store. LangChain handles the embedding process automatically.

We'll add a few sample documents to our ChromaDB instance.

from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import SentenceTransformerEmbeddings
from langchain_core.documents import Document
import os

def main():
    persist_directory = "./chroma_db"
    embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
    
    # Load the existing ChromaDB or create a new one
    vectordb = Chroma(
        persist_directory=persist_directory,
        embedding_function=embeddings
    )
    
    # Example documents to add
    documents = [
        Document(page_content="The quick brown fox jumps over the lazy dog."),
        Document(page_content="Artificial intelligence is transforming industries."),
        Document(page_content="Machine learning is a subset of AI."),
        Document(page_content="Dogs are known for their loyalty and companionship.")
    ]
    
    print(f"Adding {len(documents)} documents to ChromaDB...")
    # add_documents handles embedding and storing
    vectordb.add_documents(documents)
    print("Documents added.")

if __name__ == "__main__":
    main()

Performing Similarity Search

Now that documents are stored, we can query the vector store to find content semantically similar to our query. The similarity_search() method returns a list of relevant Document objects.

The k parameter specifies how many top similar documents to retrieve.

from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import SentenceTransformerEmbeddings
import os

def main():
    persist_directory = "./chroma_db"
    embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
    
    # Load the existing ChromaDB
    vectordb = Chroma(
        persist_directory=persist_directory,
        embedding_function=embeddings
    )
    
    query = "What is AI?"
    print(f"Searching for documents similar to: '{query}'")
    
    # Perform similarity search, retrieve top 2 results
    docs = vectordb.similarity_search(query, k=2)
    
    print("\nFound relevant documents:")
    for i, doc in enumerate(docs):
        print(f"--- Document {i+1} ---")
        print(doc.page_content)

if __name__ == "__main__":
    main()

VectorStore as a Retriever

In LangChain, a Retriever is an interface that returns Documents given an unstructured query. A vector store is one of the most common ways to create a retriever.

By converting your vector store into a retriever, you can easily plug it into more complex LangChain chains and agents, especially for RAG applications.

Activating the Retriever

Here's how to convert your ChromaDB instance into a retriever and use it to fetch documents based on a query. This is the final step before integrating it into a full RAG chain.

from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import SentenceTransformerEmbeddings
import os

def main():
    persist_directory = "./chroma_db"
    embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
    
    # Load the existing ChromaDB
    vectordb = Chroma(
        persist_directory=persist_directory,
        embedding_function=embeddings
    )
    
    # Convert the vector store into a retriever
    # search_kwargs allows passing arguments like 'k' to the underlying search
    retriever = vectordb.as_retriever(search_kwargs={"k": 2})
    
    query = "Tell me about AI."
    print(f"Using retriever to find documents for: '{query}'")
    
    # Use the retriever to get relevant documents
    relevant_docs = retriever.get_relevant_documents(query)
    
    print("\nRelevant documents retrieved by the retriever:")
    for i, doc in enumerate(relevant_docs):
        print(f"--- Retrieved Document {i+1} ---")
        print(doc.page_content)

if __name__ == "__main__":
    main()

Quick Check: Vector Stores

Which of the following best describes the primary purpose of a vector store in the context of Retrieval Augmented Generation (RAG)?

Recap: Vector Stores for RAG

Great job! In this lesson, you learned about:

  • The role of vector stores in enhancing LLMs through RAG.
  • How vector stores store embeddings for semantic search.
  • Setting up and interacting with a local ChromaDB.
  • Adding documents and performing similarity searches.
  • Converting a vector store into a LangChain Retriever.

You now have a solid foundation for implementing data retrieval in your AI agents!

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

บทเรียน “คลังเวกเตอร์สำหรับการดึงข้อมูล” ฟรีหรือไม่

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

คุณจะเรียนรู้อะไรในบทเรียน “คลังเวกเตอร์สำหรับการดึงข้อมูล”

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

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents with LangChain & Autonomous Workflows หรือไม่

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

บทเรียน “คลังเวกเตอร์สำหรับการดึงข้อมูล” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน AI Agents with LangChain & Autonomous Workflows นี้ได้ไหม

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

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

  1. อธิบายตัวโหลดเอกสาร
  2. ตัวแบ่งข้อความและเวกเตอร์ฝังตัว
  3. คลังเวกเตอร์สำหรับการดึงข้อมูล
  4. ตัวดึงข้อมูลและการบีบอัดตามบริบท
← กลับไปที่ AI Agents with LangChain & Autonomous Workflows