Lab 1 — สร้าง RAG เองทั้งเส้น
Lab walkthrough · EP10 RAG Fundamentals
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP10 RAG Fundamentals
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
จากคลิปทฤษฎี: RAG คือการให้ บัตรห้องสมุด กับ model — เตรียมคลังครั้งเดียว ค้นชิ้นที่เกี่ยวข้อง แล้วให้ model ตอบจากชิ้นเหล่านั้นพร้อมอ้างอิง (§16.1–16.2)
คลังของเรา: ตำราเล่มนี้เอง — The Hitchhiker’s Guide to Agentic AI บทที่ 15–19 (หน้า 292–374) ซึ่งออกหลังจากที่ model ถูกฝึก
สิ่งที่จะได้ทำ
- ถาม model เรื่องในตำรา โดยไม่มี RAG
- Indexing: โหลด PDF พร้อมเลขหน้า → ตัดเป็น chunk (512 token, overlap 64) → ทำ embedding
- ค้น: cosine similarity + top-k ด้วย numpy
- ตอบ: prompt ตาม Listing 16.1 ที่อ้างอิง
[Doc N]พร้อมเลขหน้า - ดูสามกรณี: เจอในคลัง · ไม่มีในคลัง · ค้นพลาด
คำตอบของ model ทุกคำตอบมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §16.1–16.2 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ราว 0.1 เซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv, pypdf, numpy, tokenizers (ติดตั้งใน cell ถัดไป) |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env
%pip install -q "openai>=1.50" python-dotenv "pypdf>=6" numpy "tokenizers==0.23.3"1. Model สองตัว: ตัวตอบ และตัวทำ embedding
ตัวตอบ google/gemma-4-26b-a4b-it — model เดียวกับทุก EP ล็อก provider เป็น Makora เหมือน EP08–EP09 ราคา 0.09 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.28 ต่อล้าน token ขาออก · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-21: 3 ใน 3 ครั้งได้ 429 “temporarily rate-limited upstream”)
ตัวทำ embedding qwen/qwen3-embedding-8b — embedding model แบบเปิดของ Qwen เรียกผ่าน OpenRouter ด้วย key เดียวกัน ได้เวกเตอร์ยาว 4,096 ตัวเลข ราคา 0.01 ดอลลาร์ต่อล้าน token (ทำ embedding ทั้งคลังของเราราว 0.05 เซ็นต์) ล็อก provider เป็น Nebius เพื่อให้ตัวเลขเหมือนกันทุกรอบที่รัน
usage.cost ที่ OpenRouter ส่งกลับมา คือค่าใช้จ่ายจริงของแต่ละคำขอ — เรารวมไว้ใน COST แล้วดูตอนท้าย
import os, json, urllib.request
import numpy as np
from openai import OpenAI
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}}
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5)
COST = {"chat": 0.0, "embed": 0.0}
def ask(prompt):
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA,
messages=[{"role": "user", "content": prompt}])
COST["chat"] += r.usage.cost
return r.choices[0].message.content2. ถามโดยไม่มี RAG
ตำราออกปี 2026 หลังจากที่ Gemma ถูกฝึก — model รู้จักตำราเล่มนี้ไหม
question = ("In Roitman's book The Hitchhiker's Guide to Agentic AI, "
"what analogy does the RAG chapter use to explain RAG?")
print(ask(question))In Roitman's book *The Hitchhiker's Guide to Agentic AI*, the analogy used to explain **Retrieval-Augmented Generation (RAG)** is that of an **open-book exam.**
Here is how the analogy breaks down:
* **The LLM (Large Language Model) is the student:** The student has a vast amount of general knowledge and reasoning ability (the pre-training), but they might forget specific details, hallucinate facts, or lack access to information that was published after they finished studying.
* **RAG is the textbook/reference material:** Instead of forcing the student to rely solely on their memory (parametric memory), RAG provides the student with a specific textbook or a set of notes (the external knowledge base) to look at during the exam.
* **The Process:** When a question is asked, the "student" (LLM) first looks up the relevant passage in the "textbook" (Retrieval), reads it, and then uses their reasoning skills to write a perfect answer based on that specific information (Generation).
By using this analogy, Roitman illustrates that RAG doesn't change how "smart" the model is; rather, it changes what information the model has available to it at the moment it needs to answer a question.
3. Indexing ขั้นที่ 1: โหลดเอกสารพร้อม metadata
ดาวน์โหลดตำราจาก arXiv เวอร์ชัน 1 (…v1) — เวอร์ชันใหม่กว่ามีเนื้อหาเพิ่มและเลขหน้าเปลี่ยน ซึ่งก็คือเหตุผลที่ตำราบอกว่า RAG เหมาะกับความรู้ที่เปลี่ยนบ่อย: เอกสารเปลี่ยน เราแค่ทำ index ใหม่
เราเก็บทีละหน้า แต่ละหน้ามี metadata: ชื่อไฟล์ (source) และเลขหน้า (page) — ตัดบรรทัดหัวกระดาษที่ซ้ำทุกหน้าออก
URL = "https://arxiv.org/pdf/2606.24937v1"
urllib.request.urlretrieve(URL, "hitchhikers-guide-v1.pdf")
reader = PdfReader("hitchhikers-guide-v1.pdf")
print(len(reader.pages), "pages")
HEADER = "H. Roitman — The Hitchhiker’s Guide to Agentic AI: From Foundations to Systems\n"
pages = []
for n in range(292, 375): # book pages 292–374: chapters 15–19
text = reader.pages[n - 1].extract_text().replace(HEADER, "")
pages.append({"source": "hitchhikers-guide-v1.pdf", "page": n, "text": text})
print(len(pages), "pages loaded")
print(pages[3]["text"][:300])603 pages
83 pages loaded
Chapter 16
Retrieval-Augmented Generation
(RAG)
Retrieval-Augmented Generation (RAG) [128] has emerged as one of the most practically impactful
techniques for deploying large language models in production. Rather than relying solely on knowledge
encoded in model weights during training, RAG equips L
4. Indexing ขั้นที่ 2: ตัดเป็น chunk
ขนาดคงที่ + overlap (§16.4.1): ชิ้นละ W = 512 token ชิ้นที่ติดกันซ้อนกัน O = 64 token — นับด้วย tokenizer ของ Gemma ใน lab นี้เราตัดทีละหน้า เพื่อให้ทุกชิ้นมีเลขหน้าเดียว (Lab 3 จะลองตัดแบบอื่น)
tok = Tokenizer.from_pretrained(MODEL)
# ✏️ TODO 1 (▶ วิดีโอ 4:17): เดินจาก 0 ทีละ W − O token (หยุดก่อนถึงท้าย O token) แล้วตัดชิ้นละ W token
def chunk_page(page, W=512, O=64):
ids = tok.encode(page["text"], add_special_tokens=False).ids
chunks = []
for start in range(0, ___, ___):
chunks.append({"source": page["source"], "page": page["page"],
"text": tok.decode(ids[___])})
return chunks
chunks = [c for p in pages for c in chunk_page(p)]
print(len(chunks), "chunks")tok = Tokenizer.from_pretrained(MODEL)
def chunk_page(page, W=512, O=64):
ids = tok.encode(page["text"], add_special_tokens=False).ids
chunks = []
for start in range(0, max(len(ids) - O, 1), W - O):
chunks.append({"source": page["source"], "page": page["page"],
"text": tok.decode(ids[start:start + W])})
return chunks
chunks = [c for p in pages for c in chunk_page(p)]
print(len(chunks), "chunks")Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
141 chunks
5. Indexing ขั้นที่ 3: embedding
ส่งข้อความให้ embedding model ทีละ 64 ชิ้น แล้ว normalize ทุกเวกเตอร์ให้ยาว 1 เมื่อยาว 1 แล้ว cosine similarity (สมการ 16.3) เหลือแค่ dot product: a @ b
def embed(texts):
vectors = []
for i in range(0, len(texts), 64):
r = client.embeddings.create(model=EMBED_MODEL, input=texts[i:i + 64],
extra_body=EMBED_EXTRA)
COST["embed"] += r.usage.cost
vectors += [d.embedding for d in r.data]
# ✏️ TODO 2 (▶ วิดีโอ 5:17): ทำให้ทุกแถวของ V ยาว 1 (หารด้วย norm ของแถวนั้น)
V = np.array(vectors)
return ___
demo = embed(["car", "automobile", "banana"])
print(demo.shape)
print("car · automobile =", round(float(demo[0] @ demo[1]), 3))
print("car · banana =", round(float(demo[0] @ demo[2]), 3))def embed(texts):
vectors = []
for i in range(0, len(texts), 64):
r = client.embeddings.create(model=EMBED_MODEL, input=texts[i:i + 64],
extra_body=EMBED_EXTRA)
COST["embed"] += r.usage.cost
vectors += [d.embedding for d in r.data]
V = np.array(vectors)
return V / np.linalg.norm(V, axis=1, keepdims=True)
demo = embed(["car", "automobile", "banana"])
print(demo.shape)
print("car · automobile =", round(float(demo[0] @ demo[1]), 3))
print("car · banana =", round(float(demo[0] @ demo[2]), 3))(3, 4096)
car · automobile = 0.948
car · banana = 0.582
E = embed([c["text"] for c in chunks])
print(E.shape)(141, 4096)
6. ค้น: cosine similarity + top-k
คำถาม → embedding (ยาว 1) → E @ q ได้คะแนนของทุกชิ้นในครั้งเดียว → เก็บ k ชิ้นที่คะแนนสูงสุด
# ✏️ TODO 3 (▶ วิดีโอ 6:30): คำนวณคะแนน cosine ของทุกชิ้น แล้วเลือก index ของ k ชิ้นที่คะแนนสูงสุด
def search(query, k=3):
q = embed([query])[0]
scores = ___
best = ___
return [(float(scores[i]), chunks[i]) for i in best]
for score, c in search("What analogy does the textbook use to explain RAG?"):
print(f"{score:.3f} page {c['page']} {c['text'][:70]!r}")def search(query, k=3):
q = embed([query])[0]
scores = E @ q
best = np.argsort(-scores)[:k]
return [(float(scores[i]), chunks[i]) for i in best]
for score, c in search("What analogy does the textbook use to explain RAG?"):
print(f"{score:.3f} page {c['page']} {c['text'][:70]!r}")0.632 page 296 '16.1.2 When to Use RAG vs. Fine-Tuning vs. Long Context\nTable 16.1: De'
0.592 page 295 'Chapter 16\nRetrieval-Augmented Generation\n(RAG)\nRetrieval-Augmented Ge'
0.572 page 305 '1. Retrieve top-k documents\n2. Grade each document: Correct / Ambiguou'
7. ตอบ: prompt ตาม Listing 16.1
กฎสามข้อ: ตอบจาก context เท่านั้น · ถ้าไม่พอให้ บอกตรงๆ · อ้างอิงด้วย [Doc N] แต่ละชิ้นติดหัว [Doc N] (Source: …, Page: …) — metadata จากส่วนที่ 3
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."""
# ✏️ TODO 4 (▶ วิดีโอ 7:27): ใส่หัว [Doc N] (Source: …, Page: …) ให้แต่ละชิ้น โดย N เริ่มจาก 1
def build_rag_prompt(query, chunks):
context_str = "\n\n".join(
___
for i, c in enumerate(chunks))
return f"""{SYSTEM_PROMPT}
Context:
{context_str}
Question: {query}
Answer:"""
# ✏️ TODO 5 (▶ วิดีโอ 7:49): ค้น k ชิ้น แล้วถาม model ด้วย prompt ที่สร้างจากชิ้นเหล่านั้น
def rag(query, k=3):
hits = ___
for score, c in hits:
print(f" retrieved page {c['page']} ({score:.3f})")
return ___
print(rag("What analogy does the textbook use to explain RAG?"))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."""
def build_rag_prompt(query, chunks):
context_str = "\n\n".join(
f"[Doc {i+1}] (Source: {c['source']}, Page: {c.get('page', 'N/A')})\n{c['text']}"
for i, c in enumerate(chunks))
return f"""{SYSTEM_PROMPT}
Context:
{context_str}
Question: {query}
Answer:"""
def rag(query, k=3):
hits = search(query, k)
for score, c in hits:
print(f" retrieved page {c['page']} ({score:.3f})")
return ask(build_rag_prompt(query, [c for _, c in hits]))
print(rag("What analogy does the textbook use to explain RAG?")) retrieved page 296 (0.632)
retrieved page 295 (0.592)
retrieved page 305 (0.572)
The textbook uses the "Library Analogy" to explain RAG: 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].
print(rag("What chunk size and overlap does the textbook recommend for legal documents?")) retrieved page 302 (0.737)
retrieved page 303 (0.690)
retrieved page 302 (0.643)
For legal / regulatory documents, the textbook recommends a paragraph-level chunk size and an overlap of 1 sentence [Doc 2].
print(rag("What is the capital of Australia?")) retrieved page 308 (0.183)
retrieved page 350 (0.168)
retrieved page 310 (0.157)
The provided context does not contain information regarding the capital of Australia.
8. เมื่อการค้นพลาด
ถามคำถามแรกของ lab (ส่วนที่ 2) ผ่าน RAG — คำถามยาวกว่า และมีชื่อตำรากับชื่อผู้เขียนอยู่ด้วย
print(rag(question)) retrieved page 309 (0.663)
retrieved page 292 (0.655)
retrieved page 311 (0.632)
The provided text does not mention a book titled "Roitman's book The Hitchhiker's Guide to Agentic AI." Therefore, the context does not contain enough information to answer the question.
ranked = np.argsort(-(E @ embed([question])[0]))
where = [r for r, i in enumerate(ranked, 1) if "library card" in chunks[i]["text"]]
print("the 'library card' chunk is at rank", where)the 'library card' chunk is at rank [8]
print(f"embeddings ${COST['embed']:.5f} chat ${COST['chat']:.5f}")embeddings $0.00045 chat $0.00062
สรุป
| ขั้น | ที่เราเห็นใน lab |
|---|---|
| ไม่มี RAG | model ตอบอย่างมั่นใจว่า “open-book exam” — ตำราไม่มีคำนี้สักหน้า |
| Load + metadata | ตำรา v1 หน้า 292–374 → 83 หน้า แต่ละหน้ามี source + page |
| Chunk | 512 token, overlap 64 → 141 ชิ้น |
| Embed | car · automobile ≈ 0.94 แต่ car · banana ≈ 0.58 (ไม่ใช่ 0) — ลำดับสำคัญกว่าตัวเลข |
| Retrieve + generate | “library card” อ้างอิง [Doc 2] หน้า 295 · เอกสารกฎหมาย: ระดับย่อหน้า ซ้อน 1 ประโยค |
| ไม่มีในคลัง | “context ไม่มีข้อมูล” — แม้ model รู้คำตอบ |
| ค้นพลาด | คำถามยาวที่มีชื่อตำรา → ชิ้น “library card” ตกไปอันดับ 8 → ตอบว่าไม่มีข้อมูล |
แบบฝึกหัด
- รันส่วนที่ 8 ด้วย
rag(question, k=8)— model ตอบถูกไหม แล้ว prompt ยาวขึ้นกี่เท่า - เปลี่ยน
sourceในส่วนที่ 3 เป็นชื่อตำราเต็ม แล้วทำ index ใหม่ — model ยังบ่นว่าเอกสารไม่ได้เอ่ยถึงชื่อตำราไหม
ถัดไป — Lab 2: เขียน BM25 เอง เทียบกับ dense retrieval บนคลังเดียวกัน แล้วรวมสองแบบด้วย RRF