Lab 1 — แปลงคำถาม + จัดลำดับใหม่
Lab walkthrough · EP11 Advanced & Agentic RAG
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP11 Advanced & Agentic RAG
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
จาก EP10 Lab 1: คำถามยาวที่มีชื่อตำราและชื่อผู้เขียน ทำให้ชิ้น “library card” ตกไป อันดับ 8 — RAG จึงตอบไม่ได้ BM25, hybrid และการตัดชิ้นแบบอื่นใน EP10 ก็ยังไม่ช่วย
คลิปทฤษฎี EP11 ให้เครื่องมือมาสองกลุ่ม (§16.5.1–16.5.2)
- แปลงคำถามก่อนค้น: HyDE · multi-query + RAG-Fusion · step-back
- จัดลำดับใหม่หลังค้น: cross-encoder re-ranking
สิ่งที่จะได้ทำ
- สร้างคลังเดิมของ EP10 ใหม่ (ตำราหน้า 292–374, 141 ชิ้น)
- HyDE: ให้ model ร่างคำตอบ แล้วค้นด้วยร่างนั้น
- Multi-query + RAG-Fusion: หลายคำถาม รวมด้วย RRF — และ prompt ที่ทำให้มันพลาด
- Re-ranking: ให้ cross-encoder อ่าน 20 ชิ้นแรกแล้วเรียงใหม่
- วัดทุกวิธีบนคำถามทดสอบ 20 ข้อของ EP10
คำตอบของ model ทุกคำตอบมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §16.5 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ราว 7 เซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv, pypdf, numpy, tokenizers, requests (ติดตั้งใน 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" requests1. Model สามตัว: ตัวตอบ ตัวทำ embedding และตัวจัดลำดับใหม่
ตัวตอบ google/gemma-4-26b-a4b-it — model เดียวกับทุก EP ล็อก provider เป็น Makora ราคา 0.09 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.28 ต่อล้าน token ขาออก · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-22: 3 ใน 3 ครั้งได้ 429 “rate-limited”)
ตัวทำ embedding qwen/qwen3-embedding-8b — ตัวเดียวกับ EP10 ล็อก provider เป็น Nebius
ตัวจัดลำดับใหม่ qwen/qwen3-reranker-8b — cross-encoder แบบเปิดตระกูลเดียวกัน เรียกผ่าน endpoint /api/v1/rerank ของ OpenRouter ด้วย key เดียวกัน ล็อก provider เป็น Fireworks · ราคาราว 0.20 ดอลลาร์ต่อล้าน token (จัด 20 ชิ้นใหม่ ≈ 0.2 เซ็นต์) · ตำราใช้ BGE re-ranker ผ่าน sentence-transformers ซึ่งต้องโหลด model ลงเครื่อง — ที่นี่เราเรียกผ่าน API แทน ไม่ต้องใช้ GPU
ค่าใช้จ่ายจริงของทุกคำขอรวมไว้ใน COST
import os, urllib.request, requests
import numpy as np
from openai import OpenAI
from pypdf import PdfReader
from tokenizers import Tokenizer
from concurrent.futures import ThreadPoolExecutor
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}}
RERANK_MODEL = "qwen/qwen3-reranker-8b"
RERANK_PROVIDER = {"order": ["fireworks"], "allow_fallbacks": False}KEY = load_key()
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=KEY, max_retries=5)
COST = {"chat": 0.0, "embed": 0.0, "rerank": 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.content
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)2. คลังเดิม และคำถามที่ค้นพลาด
คลังเดียวกับ EP10 Lab 1: ตำรา v1 หน้า 292–374 → ชิ้นละ 512 token ซ้อน 64 → 141 ชิ้น → embedding
urllib.request.urlretrieve("https://arxiv.org/pdf/2606.24937v1", "hitchhikers-guide-v1.pdf")
reader = PdfReader("hitchhikers-guide-v1.pdf")
HEADER = "H. Roitman — The Hitchhiker’s Guide to Agentic AI: From Foundations to Systems\n"
pages = [{"page": n, "text": reader.pages[n - 1].extract_text().replace(HEADER, "")}
for n in range(292, 375)] # chapters 15–19
tok = Tokenizer.from_pretrained(MODEL)
def chunk_page(page, W=512, O=64):
ids = tok.encode(page["text"], add_special_tokens=False).ids
return [{"source": "hitchhikers-guide-v1.pdf", "page": page["page"],
"text": tok.decode(ids[s:s + W])}
for s in range(0, max(len(ids) - O, 1), W - O)]
chunks = [c for p in pages for c in chunk_page(p)]
E = embed([c["text"] for c in chunks])
print(len(chunks), "chunks", E.shape)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 (141, 4096)
def search(query_vector):
return list(np.argsort(-(E @ query_vector))) # every chunk, best first
def card_rank(order):
return [r for r, i in enumerate(order, 1) if "library card" in chunks[i]["text"]][0]
question = ("In Roitman's book The Hitchhiker's Guide to Agentic AI, "
"what analogy does the RAG chapter use to explain RAG?")
dense = search(embed([question])[0])
print("dense: rank", card_rank(dense))dense: rank 8
3. HyDE: ค้นด้วยคำตอบสมมุติ
ให้ model ร่างคำตอบ ก่อน แล้วทำ embedding ของร่าง แทนคำถาม (สมการ 16.20) ร่างเขียนด้วยภาษาแบบตำรา จึงอาจอยู่ใกล้ชิ้นที่ถูกมากกว่าคำถาม — แม้ร่างจะผิด
def hyde(query):
draft = ask("Write a short passage (about 100 words) from a textbook that answers this question. "
"Write it as the textbook would, even if you are not sure.\n\nQuestion: " + query)
# ✏️ TODO 1 (▶ วิดีโอ 3:59): ทำ embedding ของร่าง (ไม่ใช่ของคำถาม) แล้วค้นด้วยเวกเตอร์นั้น
return draft, ___
draft, by_hyde = hyde(question)
print(draft, "\n")
print("HyDE: rank", card_rank(by_hyde))def hyde(query):
draft = ask("Write a short passage (about 100 words) from a textbook that answers this question. "
"Write it as the textbook would, even if you are not sure.\n\nQuestion: " + query)
return draft, search(embed([draft])[0])
draft, by_hyde = hyde(question)
print(draft, "\n")
print("HyDE: rank", card_rank(by_hyde))**Section 4.2: Retrieval-Augmented Generation (RAG)**
To understand the mechanics of Retrieval-Augmented Generation, Roitman employs a foundational analogy: the distinction between a student taking an exam from memory versus a student taking an "open-book" exam. In this comparison, the Large Language Model (LLM) represents the student’s innate intelligence and linguistic capability. While a standard LLM relies solely on its internal weights (memory), RAG provides the model with an external textbook (the retrieval source). By allowing the agent to "look up" specific, real-time data before formulating a response, RAG transforms the model from a closed system into an informed researcher.
HyDE: rank 1
4. Multi-query + RAG-Fusion
ให้ model เขียนคำถามใหม่ 3 แบบ → ค้นทุกแบบ (รวมคำถามเดิม) → รวมลำดับด้วย RRF (สมการเดียวกับ EP10 Lab 2, k = 60) ชิ้นที่ติดอันดับดีในหลายรายการจะขึ้นบนสุด
def variants(query, extra=""):
out = ask("Write 3 different search queries that could find the answer to this question "
f"in a textbook.{extra} One per line, no numbering, nothing else.\n\nQuestion: " + query)
return [line.strip(" -•\t") for line in out.splitlines() if line.strip()][:3]
# ✏️ TODO 2 (▶ วิดีโอ 5:04): บวกคะแนน 1 / (k + rank) ให้ชิ้น i ทุกครั้งที่มันอยู่ในรายการ
def rrf(lists, k=60):
score = {}
for order in lists:
for rank, i in enumerate(order, 1):
score[i] = ___
return sorted(score, key=score.get, reverse=True)
def rag_fusion(query, extra=""):
queries = variants(query, extra)
lists = [search(embed([query])[0])] + [search(v) for v in embed(queries)]
return queries, lists, rrf(lists)
queries, lists, fused = rag_fusion(question)
for q, order in zip(queries, lists[1:]):
print(f"rank {card_rank(order):>3} {q}")
print("RAG-Fusion: rank", card_rank(fused))def variants(query, extra=""):
out = ask("Write 3 different search queries that could find the answer to this question "
f"in a textbook.{extra} One per line, no numbering, nothing else.\n\nQuestion: " + query)
return [line.strip(" -•\t") for line in out.splitlines() if line.strip()][:3]
def rrf(lists, k=60):
score = {}
for order in lists:
for rank, i in enumerate(order, 1):
score[i] = score.get(i, 0) + 1 / (k + rank)
return sorted(score, key=score.get, reverse=True)
def rag_fusion(query, extra=""):
queries = variants(query, extra)
lists = [search(embed([query])[0])] + [search(v) for v in embed(queries)]
return queries, lists, rrf(lists)
queries, lists, fused = rag_fusion(question)
for q, order in zip(queries, lists[1:]):
print(f"rank {card_rank(order):>3} {q}")
print("RAG-Fusion: rank", card_rank(fused))rank 12 Roitman The Hitchhiker's Guide to Agentic AI RAG analogy
rank 13 "The Hitchhiker's Guide to Agentic AI" RAG chapter analogy
rank 9 What analogy does Roitman use to explain RAG in The Hitchhiker's Guide to Agentic AI?
RAG-Fusion: rank 9
NO_NAMES = " Leave out book titles and author names; keep only the topic."
queries, lists, fused = rag_fusion(question, NO_NAMES)
for q, order in zip(queries, lists[1:]):
print(f"rank {card_rank(order):>3} {q}")
print("RAG-Fusion: rank", card_rank(fused))rank 1 analogy used to explain Retrieval-Augmented Generation
rank 2 RAG explanation analogy
rank 3 Retrieval-Augmented Generation conceptual analogy
RAG-Fusion: rank 1
5. Re-ranking ด้วย cross-encoder
ค้นรอบแรกด้วย embedding (เร็ว) → เอา 20 ชิ้นแรก ให้ cross-encoder อ่าน คู่คำถามกับชิ้น ทีละคู่ แล้วให้คะแนนใหม่ (§16.5.2) cross-encoder ไม่มีเวกเตอร์ที่ทำไว้ล่วงหน้า จึงใช้ค้นทั้งคลังไม่ได้ แต่แม่นกว่า
def rerank(query, order, n=20):
top = order[:n]
r = requests.post("https://openrouter.ai/api/v1/rerank",
headers={"Authorization": f"Bearer {KEY}"},
json={"model": RERANK_MODEL, "provider": RERANK_PROVIDER, "query": query,
"documents": [chunks[i]["text"] for i in top]}, timeout=60)
r.raise_for_status()
# ✏️ TODO 3 (▶ วิดีโอ 6:51): แปลง index ของแต่ละผลลัพธ์ (ตำแหน่งใน top) กลับเป็นเลขชิ้นในคลัง
data = r.json()
COST["rerank"] += data["usage"]["cost"]
return [___ for x in data["results"]], [x["relevance_score"] for x in data["results"]]
reranked, scores = rerank(question, dense)
print("re-ranked: rank", card_rank(reranked))
for i, s in zip(reranked[:3], scores[:3]):
print(f"{s:.3f} page {chunks[i]['page']} {chunks[i]['text'][:60]!r}")def rerank(query, order, n=20):
top = order[:n]
r = requests.post("https://openrouter.ai/api/v1/rerank",
headers={"Authorization": f"Bearer {KEY}"},
json={"model": RERANK_MODEL, "provider": RERANK_PROVIDER, "query": query,
"documents": [chunks[i]["text"] for i in top]}, timeout=60)
r.raise_for_status()
data = r.json()
COST["rerank"] += data["usage"]["cost"]
return [top[x["index"]] for x in data["results"]], [x["relevance_score"] for x in data["results"]]
reranked, scores = rerank(question, dense)
print("re-ranked: rank", card_rank(reranked))
for i, s in zip(reranked[:3], scores[:3]):
print(f"{s:.3f} page {chunks[i]['page']} {chunks[i]['text'][:60]!r}")re-ranked: rank 1
0.996 page 295 'Chapter 16\nRetrieval-Augmented Generation\n(RAG)\nRetrieval-Au'
0.500 page 292 'Chapter 15\nIntroduction to Agentic AI\nThe previous parts equ'
0.081 page 312 'Results. On open-domain QA benchmarks (NQ [294], TriviaQA [2'
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:"""print(ask(build_rag_prompt(question, [chunks[i] for i in reranked[:3]])))The provided text does not mention a book titled "Roitman's book The Hitchhiker's Guide to Agentic AI." However, the RAG chapter uses the "Library Analogy" to explain RAG [Doc 1]. This analogy 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 up information in real time, cite sources, and acknowledge when they need to check a reference instead of guessing from memory [Doc 1].
6. วัดผลบนคำถาม 20 ข้อ
คำถามเดียวยังพิสูจน์อะไรไม่ได้ — ใช้คำถามทดสอบ 20 ข้อชุดเดียวกับ EP10 Lab 3 (แต่ละข้อมีหน้าที่ถูก) hit@3 = หน้าที่ถูกอยู่ในสามชิ้นแรกไหม
TESTS = [ # (question, the pages that answer it) — from EP10 Lab 3
("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}),
]# ✏️ TODO 4 (▶ วิดีโอ 8:36): คืน True ถ้าชิ้นใดใน 3 อันดับแรกมาจากหน้าที่อยู่ใน gold
def hit3(order, gold):
return ___
def methods(case):
q, gold = case
d = search(embed([q])[0])
_, h = hyde(q)
_, _, f = rag_fusion(q, NO_NAMES)
return {"dense": hit3(d, gold), "HyDE": hit3(h, gold), "RAG-Fusion": hit3(f, gold),
"re-rank": hit3(rerank(q, d)[0], gold), "HyDE + re-rank": hit3(rerank(q, h)[0], gold)}
with ThreadPoolExecutor(5) as pool:
rows = list(pool.map(methods, TESTS))
for name in rows[0]:
print(f"{name:15} {sum(r[name] for r in rows):2} / 20")def hit3(order, gold):
return any(chunks[i]["page"] in gold for i in order[:3])
def methods(case):
q, gold = case
d = search(embed([q])[0])
_, h = hyde(q)
_, _, f = rag_fusion(q, NO_NAMES)
return {"dense": hit3(d, gold), "HyDE": hit3(h, gold), "RAG-Fusion": hit3(f, gold),
"re-rank": hit3(rerank(q, d)[0], gold), "HyDE + re-rank": hit3(rerank(q, h)[0], gold)}
with ThreadPoolExecutor(5) as pool:
rows = list(pool.map(methods, TESTS))
for name in rows[0]:
print(f"{name:15} {sum(r[name] for r in rows):2} / 20")dense 12 / 20
HyDE 16 / 20
RAG-Fusion 14 / 20
re-rank 18 / 20
HyDE + re-rank 19 / 20
print({k: f"${v:.4f}" for k, v in COST.items()}){'chat': '$0.0014', 'embed': '$0.0005', 'rerank': '$0.0671'}
สรุป
| วิธี | คำถามยาว (ชิ้น “library card”) | hit@3 บน 20 ข้อ |
|---|---|---|
| dense (EP10) | อันดับ 8 | 12 |
| HyDE | อันดับ 1 — แม้ร่างจะผิด (“open-book”) | 15–16 |
| RAG-Fusion, prompt ธรรมดา | อันดับ 9 — คำค้นยังมีชื่อตำรา | — |
| RAG-Fusion, ตัดชื่อออก | 3 อันดับแรก | 13–15 |
| re-rank 20 ชิ้นแรก | อันดับ 1 (คะแนน ≈ 1) | 18 |
| HyDE + re-rank | — | 19 |
แบบฝึกหัด
- Step-back: เขียน prompt ให้ model ถามคำถามที่กว้างขึ้นเกี่ยวกับหลักการเบื้องหลัง แล้วค้นด้วยคำถามนั้น — รันหลายรอบ อันดับนิ่งไหม
- เปลี่ยน
n=20ในrerankเป็น 5 และ 50 — hit@3 เปลี่ยนไหม แล้วค่าใช้จ่ายเปลี่ยนเท่าไร - Contextual compression: ให้ Gemma ตัดประโยคที่ไม่เกี่ยวกับคำถามออกจากสามชิ้นแรก ก่อนส่งไปตอบ — prompt สั้นลงกี่ token
ถัดไป — Lab 2: agentic RAG — ให้ agent ตัดสินใจเองว่าจะค้นที่ไหน ตรวจว่าเอกสารพอไหม และค้นซ้ำถ้าไม่พอ