Lab 4 — RAG ด้วย LangChain
Lab walkthrough · EP10 RAG Fundamentals
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP10 RAG Fundamentals
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
สาม lab ที่ผ่านมาเราเขียน RAG เองทุกชิ้น แล็บนี้สร้างตัวเดิมด้วย LangChain แล้วจับคู่แต่ละชิ้นกับโค้ดของเรา
สิ่งที่จะได้ทำ
DocumentและRecursiveCharacterTextSplitter— และสิ่งที่ Listing 16.2 ในตำราพลาดOpenAIEmbeddings+InMemoryVectorStore=embed()+search()ของ Lab 1- BM25 ของเราใส่ใน LangChain +
EnsembleRetriever=rrf()ของ Lab 2 ParentDocumentRetriever= parent-child ของ Lab 3- ต่อทุกชิ้นเป็น chain แล้วถาม Gemma
หมายเหตุเรื่องเวอร์ชัน: ตำราใช้ langchain.text_splitter และ langchain.retrievers ซึ่งย้ายไปแล้วใน LangChain 1.x แล็บนี้ใช้ที่อยู่ใหม่ และไม่ใช้ langchain-community ซึ่งกำลังจะเลิกดูแล
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §16.1–16.4 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
เหมือน Lab 1: Python 3.10+ หรือ Colab และ OPENROUTER_API_KEY (Colab: 🔑 Secrets · เครื่องตัวเอง: ไฟล์ .env) key เดียวใช้ได้ทั้ง Gemma และ embedding model — ค่าใช้จ่ายทั้งแล็บไม่ถึง 1 เซ็นต์ดอลลาร์
เราตรึงเวอร์ชันของ LangChain ไว้ เพราะ LangChain เปลี่ยนเร็ว — ที่อยู่ของ class ในตำราก็เปลี่ยนไปแล้ว
%pip install -q "openai>=2.45" python-dotenv "pypdf>=6" numpy "tokenizers==0.23.3"
%pip install -q "langchain-core==1.7.6" "langchain-openai==1.7.4" "langchain-text-splitters==1.1.3" "langchain-classic==1.0.8"import os, re, math, urllib.request
from collections import Counter
import numpy as np
from pypdf import PdfReader
from tokenizers import Tokenizer
def load_key():
try: # Google Colab Secrets
from google.colab import userdata
return userdata.get("OPENROUTER_API_KEY")
except ImportError:
pass
from dotenv import load_dotenv
load_dotenv()
return os.environ["OPENROUTER_API_KEY"]
MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False}, "provider": {"order": ["makora"], "allow_fallbacks": False}}
EMBED_MODEL = "qwen/qwen3-embedding-8b"
EMBED_EXTRA = {"provider": {"order": ["nebius"], "allow_fallbacks": False}}
OPENROUTER = "https://openrouter.ai/api/v1"
tok = Tokenizer.from_pretrained(MODEL)
def n_tokens(text):
return len(tok.encode(text, add_special_tokens=False).ids)
urllib.request.urlretrieve("https://arxiv.org/pdf/2606.24937v1", "hitchhikers-guide-v1.pdf")
TESTS = [
("What is PLAID?", {301}),
("What is HyDE?", {303}),
("What does FAISS stand for?", {298}),
("How can I search millions of vectors quickly?", {298}),
("Which method compares every query token with every document token?", {300}),
("How do I make keyword search understand synonyms?", {299}),
("When should I fine-tune a model instead of looking things up?", {296}),
("Which chunks should I give the model if small ones retrieve better but lack context?", {302, 303}),
("How do I combine keyword search and embedding search?", {298}),
("What analogy does the textbook use to explain RAG?", {295}),
("How does the textbook add randomness to retry waits?", {357}),
("What does FIFO mean for conversation history?", {345}),
("Where should the unchanging part of a prompt go so caching works?", {358}),
("When should a person approve an agent's action?", {355}),
("How does Graph RAG find groups of related entities?", {305}),
("Which chunking method splits where the topic changes?", {302}),
("Which frameworks are compared in Table 18.1?", {359}),
("What is the difference between episodic and semantic memory?", {321, 322}),
("What does an evaluator-optimizer workflow do?", {370, 371}),
("How does the harness notice an agent repeating the same tool call?", {357, 363}),
]Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
1. Document และการตัดชิ้น
| ของเรา | LangChain |
|---|---|
{"text": ..., "source": ..., "page": ...} |
Document(page_content=..., metadata={...}) |
chunk_page() (Lab 1) |
RecursiveCharacterTextSplitter |
from langchain_core.documents import Document
reader = PdfReader("hitchhikers-guide-v1.pdf")
HEADER = "H. Roitman — The Hitchhiker’s Guide to Agentic AI: From Foundations to Systems\n"
book = [Document(page_content=reader.pages[n - 1].extract_text().replace(HEADER, ""),
metadata={"source": "hitchhikers-guide-v1.pdf", "page": n})
for n in range(292, 375)]
print(len(book), "pages ·", book[3].metadata)83 pages · {'source': 'hitchhikers-guide-v1.pdf', 'page': 295}
from langchain_text_splitters import RecursiveCharacterTextSplitter
def mean_tokens(docs):
return round(np.mean([n_tokens(d.page_content) for d in docs]))
as_written = RecursiveCharacterTextSplitter(
chunk_size=512, # the book: "tokens per chunk"
chunk_overlap=64,
length_function=len,
separators=["\n\n", "\n", ". ", " ", ""],
).split_documents(book)
print("as written:", len(as_written), "chunks · mean", mean_tokens(as_written), "tokens")as written: 408 chunks · mean 115 tokens
# ✏️ TODO 1 (▶ วิดีโอ 2:15): ให้ splitter นับความยาวเป็น token ของ Gemma (ฟังก์ชันที่เรามีแล้ว)
splitter = RecursiveCharacterTextSplitter(
chunk_size=512,
chunk_overlap=64,
length_function=___,
separators=["\n\n", "\n", ". ", " ", ""],
)
chunks = splitter.split_documents(book)
print("Gemma tokens:", len(chunks), "chunks · mean", mean_tokens(chunks), "tokens ·", chunks[5].metadata)splitter = RecursiveCharacterTextSplitter(
chunk_size=512,
chunk_overlap=64,
length_function=n_tokens,
separators=["\n\n", "\n", ". ", " ", ""],
)
chunks = splitter.split_documents(book)
print("Gemma tokens:", len(chunks), "chunks · mean", mean_tokens(chunks), "tokens ·", chunks[5].metadata)Gemma tokens: 141 chunks · mean 340 tokens · {'source': 'hitchhikers-guide-v1.pdf', 'page': 295}
2. Embedding และ vector store
| ของเรา (Lab 1) | LangChain |
|---|---|
embed() |
OpenAIEmbeddings (ใช้กับ API แบบ OpenAI ได้ทุกเจ้า รวม OpenRouter) |
เมทริกซ์ E + search() |
InMemoryVectorStore + .as_retriever() |
from langchain_openai import OpenAIEmbeddings
emb = OpenAIEmbeddings(
model=EMBED_MODEL, base_url=OPENROUTER, api_key=load_key(),
check_embedding_ctx_length=False,
model_kwargs={"extra_body": EMBED_EXTRA},
chunk_size=64, max_retries=5,
)
car, auto, banana = np.array(emb.embed_documents(["car", "automobile", "banana"]))
print("car·automobile", round(car @ auto, 2), "· car·banana", round(car @ banana, 2))car·automobile 0.95 · car·banana 0.58
from langchain_core.vectorstores import InMemoryVectorStore
store = InMemoryVectorStore.from_documents(chunks, emb)
dense = store.as_retriever(search_kwargs={"k": 3})
for d in dense.invoke("What analogy does the textbook use to explain RAG?"):
print(d.metadata["page"], d.page_content[:70].replace("\n", " "))296 16.1.2 When to Use RAG vs. Fine-Tuning vs. Long Context Table 16.1: De
295 Chapter 16 Retrieval-Augmented Generation (RAG) Retrieval-Augmented Ge
305 1. Retrieve top-k documents 2. Grade each document: Correct / Ambiguou
def hit3(name, retriever):
hits, context = 0, []
for q, gold in TESTS:
top3 = retriever.invoke(q)[:3]
# ✏️ TODO 2 (▶ วิดีโอ 4:20): เป็น hit ถ้าเลขหน้าใน metadata ของ Document ใดใน top3 อยู่ใน gold
hits += ___
context.append(sum(n_tokens(d.page_content) for d in top3))
print(f"{name:26s} hit@3 {hits:2d}/{len(TESTS)} · context ≈ {np.mean(context):,.0f} tokens")
hit3("dense", dense)def hit3(name, retriever):
hits, context = 0, []
for q, gold in TESTS:
top3 = retriever.invoke(q)[:3]
hits += any(d.metadata["page"] in gold for d in top3)
context.append(sum(n_tokens(d.page_content) for d in top3))
print(f"{name:26s} hit@3 {hits:2d}/{len(TESTS)} · context ≈ {np.mean(context):,.0f} tokens")
hit3("dense", dense)dense hit@3 11/20 · context ≈ 992 tokens
3. BM25 ของเราใน LangChain + EnsembleRetriever
LangChain มี BM25Retriever ใน langchain-community ซึ่งกำลังจะเลิกดูแล และค่าเริ่มต้นตัดคำด้วยช่องว่างอย่างเดียว ("PLAID?" ติดเครื่องหมายคำถามมาด้วย ไม่แปลงเป็นตัวเล็ก) — เราลองแล้วได้แค่ 4 จาก 20 เราจึงใส่ BM25 ของ Lab 2 เข้าไปเอง: retriever ของ LangChain คือ class ที่มีเมธอดเดียว
| ของเรา (Lab 2) | LangChain |
|---|---|
bm25_rank() |
class OurBM25(BaseRetriever) |
rrf() (Listing 16.8) |
EnsembleRetriever |
from langchain_core.retrievers import BaseRetriever
def words(text):
return re.findall(r"\w+", text.lower())
class OurBM25(BaseRetriever):
docs: list
k: int = 3
def _get_relevant_documents(self, query, *, run_manager=None):
bags = [Counter(words(d.page_content)) for d in self.docs]
lens = [sum(bag.values()) for bag in bags]
N, avgdl = len(bags), sum(lens) / len(bags)
df = Counter(w for bag in bags for w in bag)
k1, b = 1.5, 0.75
scores = []
for bag, dl in zip(bags, lens):
s = 0.0
for t in words(query):
idf = math.log((N - df[t] + 0.5) / (df[t] + 0.5) + 1)
s += idf * bag[t] * (k1 + 1) / (bag[t] + k1 * (1 - b + b * dl / avgdl))
scores.append(s)
# ✏️ TODO 3 (▶ วิดีโอ 5:21): เรียง index ตามคะแนนจากมากไปน้อย เอา k อันดับแรก แล้วคืน Document ของ index เหล่านั้น
best = ___
return ___
bm25 = OurBM25(docs=chunks, k=3)
hit3("BM25 (ours, in LangChain)", bm25)from langchain_core.retrievers import BaseRetriever
def words(text):
return re.findall(r"\w+", text.lower())
class OurBM25(BaseRetriever):
docs: list
k: int = 3
def _get_relevant_documents(self, query, *, run_manager=None):
bags = [Counter(words(d.page_content)) for d in self.docs]
lens = [sum(bag.values()) for bag in bags]
N, avgdl = len(bags), sum(lens) / len(bags)
df = Counter(w for bag in bags for w in bag)
k1, b = 1.5, 0.75
scores = []
for bag, dl in zip(bags, lens):
s = 0.0
for t in words(query):
idf = math.log((N - df[t] + 0.5) / (df[t] + 0.5) + 1)
s += idf * bag[t] * (k1 + 1) / (bag[t] + k1 * (1 - b + b * dl / avgdl))
scores.append(s)
best = np.argsort(-np.array(scores))[:self.k]
return [self.docs[i] for i in best]
bm25 = OurBM25(docs=chunks, k=3)
hit3("BM25 (ours, in LangChain)", bm25)BM25 (ours, in LangChain) hit@3 11/20 · context ≈ 1,120 tokens
# ✏️ TODO 4 (▶ วิดีโอ 5:38): รวม bm25 กับ dense ด้วย EnsembleRetriever น้ำหนักเท่ากัน
from langchain_classic.retrievers import EnsembleRetriever
hybrid = ___
hit3("hybrid, 3 per list", hybrid)from langchain_classic.retrievers import EnsembleRetriever
hybrid = EnsembleRetriever(retrievers=[bm25, dense], weights=[0.5, 0.5])
hit3("hybrid, 3 per list", hybrid)hybrid, 3 per list hit@3 13/20 · context ≈ 1,078 tokens
bm25.k = 60
dense.search_kwargs["k"] = 60
hit3("hybrid, 60 per list", hybrid)hybrid, 60 per list hit@3 17/20 · context ≈ 1,229 tokens
4. ParentDocumentRetriever
| ของเรา (Lab 3) | LangChain |
|---|---|
ตัดลูกจากแม่, parent_of |
child_splitter + docstore |
dict.fromkeys(...) แปลงลูกเป็นแม่ |
ทำให้เองข้างใน |
| แม่ = หัวข้อของตำรา | parent_splitter (ไม่ใส่ = ทั้ง Document คือหนึ่งหน้า) |
from langchain_classic.retrievers import ParentDocumentRetriever
from langchain_core.stores import InMemoryStore
parent_child = ParentDocumentRetriever(
vectorstore=InMemoryVectorStore(emb),
docstore=InMemoryStore(),
child_splitter=RecursiveCharacterTextSplitter(chunk_size=128, chunk_overlap=16, length_function=n_tokens),
search_kwargs={"k": 10},
)
parent_child.add_documents(book)
hit3("parent-child (page parents)", parent_child)parent-child (page parents) hit@3 15/20 · context ≈ 1,821 tokens
5. ต่อเป็น chain แล้วถาม Gemma
| ของเรา (Lab 1) | LangChain |
|---|---|
SYSTEM_PROMPT + build_rag_prompt() |
ChatPromptTemplate |
ask() |
ChatOpenAI |
rag() |
ต่อทุกชิ้นด้วย \| |
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
SYSTEM_PROMPT = """You are a helpful assistant. Answer the question using ONLY
the provided context. If the context does not contain enough information,
say so explicitly. Cite your sources using [Doc N] notation."""
prompt = ChatPromptTemplate.from_messages([
("system", SYSTEM_PROMPT),
("human", "Context:\n{context}\n\nQuestion: {question}\n\nAnswer:"),
])
llm = ChatOpenAI(model=MODEL, base_url=OPENROUTER, api_key=load_key(),
temperature=0, extra_body=EXTRA, max_retries=5)
def format_docs(docs):
return "\n\n".join(
f"[Doc {i+1}] (Source: {d.metadata['source']}, Page: {d.metadata['page']})\n{d.page_content}"
for i, d in enumerate(docs[:3]))# ✏️ TODO 5 (▶ วิดีโอ 8:00): ต่อ prompt → llm → StrOutputParser ด้วยเครื่องหมาย |
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
def make_rag(retriever):
return ({"context": retriever | format_docs, "question": RunnablePassthrough()}
| ___)from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
def make_rag(retriever):
return ({"context": retriever | format_docs, "question": RunnablePassthrough()}
| prompt | llm | StrOutputParser())dense.search_kwargs["k"] = 3
rag_dense = make_rag(dense)
for q in ["What analogy does the textbook use to explain RAG?",
"How do I combine keyword search and embedding search?"]:
print("Q:", q, "· pages", [d.metadata["page"] for d in dense.invoke(q)])
print("A:", rag_dense.invoke(q), "\n")Q: What analogy does the textbook use to explain RAG? · pages [296, 295, 305]
A: The textbook uses "The Library Analogy" to explain RAG [Doc 2]. It compares a parametric LLM to a scholar who has memorized an enormous library but graduated years ago, while RAG provides that scholar with a library card, allowing them to look things up in real time, cite sources, and acknowledge when they need to check a reference instead of guessing from memory [Doc 2].
Q: How do I combine keyword search and embedding search? · pages [314, 303, 332]
A: Based on the provided documents, there is no information explaining how to combine keyword search and embedding search. The documents mention "Hybrid retrieval: dense similarity + temporal recency" [Doc 3] and "Dense + sparse + multi-vec" in relation to the BAAI/bge-m3 model [Doc 1], but they do not provide instructions on combining keyword search with embedding search.
dense.search_kwargs["k"] = 60
rag_hybrid = make_rag(hybrid)
for q in ["What analogy does the textbook use to explain RAG?",
"How do I combine keyword search and embedding search?"]:
print("Q:", q, "· pages", [d.metadata["page"] for d in hybrid.invoke(q)[:3]])
print("A:", rag_hybrid.invoke(q), "\n")Q: What analogy does the textbook use to explain RAG? · pages [305, 296, 307]
A: The provided text does not contain an analogy used to explain RAG. It does, however, state that "Fine-tuning teaches the model how to reason and respond; RAG provides what to reason about" [Doc 2].
Q: How do I combine keyword search and embedding search? · pages [298, 311, 301]
A: You can combine keyword search (sparse scores) and embedding search (dense scores) using the following methods:
* **Linear Combination:** A simple way to combine them is through a linear combination of the scores: $s_{hybrid}(d,q) = \alpha \cdot s_{dense}(d,q) + (1-\alpha) \cdot s_{sparse}(d,q)$ [Doc 1].
* **Reciprocal Rank Fusion (RRF):** Because scores from different systems are not directly comparable, RRF can be used to combine results by operating on ranks rather than scores [Doc 1]. The formula is $RRF(d) = \sum_{r \in R} \frac{1}{k + rank_r(d)}$, where $R$ is the set of ranked lists (such as BM25 ranking and dense ranking) [Doc 1].
สรุป
| ของเรา (Labs 1–3) | LangChain 1.x | ต้องระวัง |
|---|---|---|
| dict ของหน้า | Document |
— |
chunk_page() |
RecursiveCharacterTextSplitter |
length_function=len นับตัวอักษร (Listing 16.2) |
embed() |
OpenAIEmbeddings |
ต้อง check_embedding_ctx_length=False เมื่อไม่ใช่ model ของ OpenAI |
E + search() |
InMemoryVectorStore.as_retriever() |
— |
bm25_rank() |
class OurBM25(BaseRetriever) |
BM25Retriever ของ community ตัดคำด้วยช่องว่าง |
rrf() |
EnsembleRetriever |
รวมได้แค่ที่แต่ละฝั่งส่งมา (3 → 13/20, 60 → 17/20) |
| parent-child | ParentDocumentRetriever |
แม่ = อะไร ยังเป็นการตัดสินใจของเรา |
rag() |
{...} \| prompt \| llm \| StrOutputParser() |
— |
แบบฝึกหัด
- ใส่
parent_splitter=splitter(512 token) ให้ParentDocumentRetriever— hit@3 และ context เปลี่ยนอย่างไร - ลอง
weights=[0.3, 0.7]ในEnsembleRetriever— ข้อไหนเปลี่ยน - ใส่ชิ้นตามหัวข้อจาก Lab 3 (
structure_chunks) เป็นDocumentแล้วใช้กับInMemoryVectorStore
ถัดไป: สรุป EP10