Retrieval-Augmented Generation (RAG) cho phép AI models truy cập tài liệu của bạn mà không cần fine-tuning. Tutorial này hướng dẫn xây pipeline RAG production-ready bằng LangChain.

Bạn Sẽ Xây Gì

Hệ thống trả lời câu hỏi về tài liệu bằng cách:

  1. Chia tài liệu thành chunks
  2. Embedding vào vector store
  3. Retrieve chunks liên quan cho mỗi query
  4. Tạo câu trả lời dựa trên data thực

Yêu Cầu

  • Node.js 18+ hoặc Python 3.10+
  • API key từ OpenAI hoặc Anthropic
  • Tài liệu để index (PDFs, markdown, etc.)

Bước 1: Setup Project

mkdir rag-pipeline && cd rag-pipeline
npm init -y
npm install langchain @langchain/openai @langchain/community chromadb

Bước 2: Load Documents

import { DirectoryLoader } from "langchain/document_loaders/fs/directory";
import { PDFLoader } from "langchain/document_loaders/fs/pdf";
 
const loader = new DirectoryLoader("./docs", {
  ".pdf": (path) => new PDFLoader(path),
  ".txt": (path) => new TextLoader(path),
});
 
const docs = await loader.load();

Bước 3: Chunking

import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
 
const splitter = new RecursiveCharacterTextSplitter({
  chunkSize: 1000,
  chunkOverlap: 200,
});
 
const chunks = await splitter.splitDocuments(docs);

Bước 4: Embedding & Lưu Trữ

import { OpenAIEmbeddings } from "@langchain/openai";
import { Chroma } from "@langchain/community/vectorstores/chroma";
 
const vectorStore = await Chroma.fromDocuments(
  chunks,
  new OpenAIEmbeddings(),
  { collectionName: "my-docs" }
);

Bước 5: Query

import { ChatOpenAI } from "@langchain/openai";
import { RetrievalQAChain } from "langchain/chains";
 
const model = new ChatOpenAI({ modelName: "gpt-4o" });
const chain = RetrievalQAChain.fromLLM(model, vectorStore.asRetriever());
 
const result = await chain.call({
  query: "Chính sách hoàn tiền là gì?"
});

Tips Production

  • Chunk size quan trọng: Bắt đầu 1000 chars, điều chỉnh theo content type
  • Dùng hybrid search: Kết hợp vector similarity với keyword matching
  • Cache embeddings: Không re-embed documents chưa thay đổi
  • Monitor relevance: Log retrieval scores để phát hiện quality degradation