Skip to main content

Lab 2 — Agentic RAG: ให้คะแนน เลือกแหล่ง วนค้น

Lab walkthrough · EP11 Advanced & Agentic RAG

หมายเหตุวิธีใช้หน้านี้

หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด

▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP11 Advanced & Agentic RAG

model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้

Lab 1 แปลงคำถามและจัดลำดับใหม่ — แต่ทุกคำถามยังเดินเส้นเดียว: ค้นครั้งเดียวจากคลังเดียว แล้วตอบ Lab นี้ให้ agent ตัดสินใจเอง (§16.7)

สิ่งที่จะได้ทำ

  1. แหล่งความรู้ สามแหล่ง บนตำราเล่มเดียว: BM25 · embedding · สารบัญของตำรา
  2. ค้นด้วยสารบัญ — model เดินลงสารบัญทีละชั้น เปิด ย้อน หรือใช้หัวข้อนั้น (นอกตำรา: MemWalker, Chen et al., 2023)
  3. CRAG grader — ให้คะแนนเอกสารแต่ละชิ้น: correct / ambiguous / incorrect (§16.5.5)
  4. Router — LLM เลือกแหล่งที่เหมาะกับคำถาม (Listing 16.9)
  5. วงวน plan → retrieve → evaluate → generate พร้อม max_iterations (Listing 16.10 เขียนด้วย Python ล้วน — LangGraph อยู่ใน Lab 4)

คำตอบของ model ทุกคำตอบมาจากการรันจริง

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §16.5.5, §16.7 — CC BY-SA 4.0 การค้นด้วยสารบัญ: H. Chen et al., Walking Down the Memory Maze: Beyond Context Limit through Interactive Reading (MemWalker), arXiv:2310.05029, 2023 · ที่เกี่ยวข้อง: RAPTOR (Sarthi et al., ICLR 2024) · PageIndex (VectifyAI, MIT license)

0. เตรียมเครื่องก่อนเริ่ม

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key key เดิมจาก Lab 1 (lab นี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์) — วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 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 และคลังเดิม

Gemma 4 26B (Makora) ตอบ · Qwen3 Embedding 8B (Nebius) ทำ embedding — เหมือน Lab 1 คลังเดิม 141 ชิ้น + BM25 ที่เราเขียนเองใน EP10 Lab 2

import os, re, math, json, urllib.request
from collections import Counter
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, "calls": 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
    COST["calls"] += 1
    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)
def ask_json(prompt, schema):
    r = client.chat.completions.create(
        model=MODEL, temperature=0, extra_body=EXTRA,
        messages=[{"role": "user", "content": prompt}],
        response_format={"type": "json_schema",
                         "json_schema": {"name": "reply", "strict": True, "schema": schema}})
    COST["chat"] += r.usage.cost
    COST["calls"] += 1
    return json.loads(r.choices[0].message.content)

def obj(**fields):
    return {"type": "object", "properties": fields,
            "required": list(fields), "additionalProperties": False}
TEXT = {"type": "string"}
def one_of(*values):
    return {"type": "string", "enum": list(values)}
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 [{"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])

def words(text):                                        # BM25 from EP10 Lab 2
    return re.findall(r"\w+", text.lower())
docs = [words(c["text"]) for c in chunks]
N, avgdl = len(docs), sum(len(d) for d in docs) / len(docs)
df = Counter(w for d in docs for w in set(d))
tfs = [Counter(d) for d in docs]
def idf(t):
    n = df.get(t, 0)
    return math.log((N - n + 0.5) / (n + 0.5) + 1)
def bm25_rank(query, k1=1.5, b=0.75):
    scores = [sum(idf(t) * tf[t] * (k1 + 1) / (tf[t] + k1 * (1 - b + b * len(d) / avgdl))
                  for t in words(query)) for d, tf in zip(docs, tfs)]
    return list(np.argsort(-np.array(scores)))
print(len(chunks), "chunks")
141 chunks

2. แหล่งความรู้แบบที่หนึ่งและสอง: BM25 และ embedding

ทุกแหล่งคืนรายการ เอกสาร แบบเดียวกัน: {"source", "pages", "text"} — agent จะได้ใช้ทุกแหล่งเหมือนกัน

def as_docs(order, source, k=3):
    return [{"source": source, "pages": [chunks[i]["page"]], "text": chunks[i]["text"]}
            for i in order[:k]]

def search_keyword(query):
    return as_docs(bm25_rank(query), "keyword_search")

def search_vector(query):
    return as_docs(list(np.argsort(-(E @ embed([query])[0]))), "vector_db")

3. แหล่งความรู้แบบที่สาม: สารบัญของตำรา (นอกตำรา)

แนวคิดจาก MemWalker (Chen et al., 2023): จัดเอกสารเป็น tree แล้วให้ model เดินลง tree เอง — ที่แต่ละชั้น เปิดหัวข้อย่อย · ย้อนขึ้น · หรือใช้หัวข้อนั้น และจำเส้นทางที่เดินมา (working memory) MemWalker สร้าง tree ด้วยบทสรุปที่ LLM เขียน และใช้ model ราว 70B — เราใช้ สารบัญที่อยู่ใน PDF แล้ว: มีแค่ชื่อหัวข้อกับเลขหน้า ไม่มี embedding · RAPTOR (Sarthi et al., 2024) และ PageIndex (VectifyAI) ใช้ tree ของเอกสารในแบบคล้ายกัน

def walk(outline, depth=0):
    for item in outline:
        if isinstance(item, list):
            yield from walk(item, depth + 1)
        else:
            yield depth, item.title, reader.get_destination_page_number(item) + 1

items = [x for x in walk(reader.outline) if x[0] >= 1 and 292 <= x[2] <= 374]
print(len(items), "entries:", items[:3])
157 entries: [(1, 'Introduction to Agentic AI', 292), (1, 'Retrieval-Augmented Generation (RAG)', 295), (2, 'Motivation and Problem Statement', 295)]
root = {"title": "The book, pages 292-374", "depth": 0, "start": 292, "end": 374, "children": []}
stack = [root]
for n, (depth, title, start) in enumerate(items):
    end = next((s for d, _, s in items[n + 1:] if d <= depth), 374)   # where the next section starts
    node = {"title": title, "depth": depth, "start": start, "end": max(start, end), "children": []}
    while stack[-1]["depth"] >= depth:
        stack.pop()
    stack[-1]["children"].append(node)
    stack.append(node)
print([c["title"] for c in root["children"]])
['Introduction to Agentic AI', 'Retrieval-Augmented Generation (RAG)', 'Agentic Memory Systems', 'Agent Harness – Context Management and Orchestration', 'Agent Design Patterns']
PAGE = {p["page"]: p["text"] for p in pages}
MENU = obj(reasoning=TEXT, action=TEXT)
LEAF = obj(reasoning=TEXT, action=one_of("use", "back"))
def label(n):
    return f'{n["title"]} (pp. {n["start"]}-{n["end"]})'

def search_toc(query, max_steps=10, show=False):
    node, path, read = root, [root], []
    for step in range(1, max_steps + 1):
        if node["children"]:
            menu = "\n".join(f"[{i}] {label(c)}" for i, c in enumerate(node["children"]))
            out = ask_json(f"You are finding the part of a book that answers a question, using its table of contents.\n"
                           f"Question: {query}\nYou are at: {' > '.join(n['title'] for n in path)}\n"
                           f"Already read, did not help: {', '.join(read) or 'nothing'}\n\nSections:\n{menu}\n\n"
                           'Set "action" to the number of the section to open, or to "back" if none fits.', MENU)
        else:
            text = "\n".join(PAGE[p] for p in range(node["start"], node["end"] + 1))
            out = ask_json(f"Question: {query}\nYou opened: {label(node)}\n\n{text}\n\n"
                           'Set "action" to "use" if this text helps answer the question, or "back" if it does not.', LEAF)
        action = out["action"].strip("[] ")
        if show:
            print(f"  step {step}: {node['title'][:40]!r} -> {action}")
        # ✏️ TODO 1 (▶ วิดีโอ 5:30): เปิดหัวข้อลูกที่ model เลือก แล้วต่อมันเข้ากับเส้นทาง
        if action == "use":
            return [{"source": "table_of_contents", "text": text,
                     "pages": list(range(node["start"], node["end"] + 1))}]
        if action.isdigit() and int(action) < len(node["children"]):
            node = ___
            path.append(node)
        else:                                           # "back"
            if not node["children"]:
                read.append(node["title"])
            if len(path) > 1:
                path.pop()
                node = path[-1]
    return []
PAGE = {p["page"]: p["text"] for p in pages}
MENU = obj(reasoning=TEXT, action=TEXT)
LEAF = obj(reasoning=TEXT, action=one_of("use", "back"))
def label(n):
    return f'{n["title"]} (pp. {n["start"]}-{n["end"]})'

def search_toc(query, max_steps=10, show=False):
    node, path, read = root, [root], []
    for step in range(1, max_steps + 1):
        if node["children"]:
            menu = "\n".join(f"[{i}] {label(c)}" for i, c in enumerate(node["children"]))
            out = ask_json(f"You are finding the part of a book that answers a question, using its table of contents.\n"
                           f"Question: {query}\nYou are at: {' > '.join(n['title'] for n in path)}\n"
                           f"Already read, did not help: {', '.join(read) or 'nothing'}\n\nSections:\n{menu}\n\n"
                           'Set "action" to the number of the section to open, or to "back" if none fits.', MENU)
        else:
            text = "\n".join(PAGE[p] for p in range(node["start"], node["end"] + 1))
            out = ask_json(f"Question: {query}\nYou opened: {label(node)}\n\n{text}\n\n"
                           'Set "action" to "use" if this text helps answer the question, or "back" if it does not.', LEAF)
        action = out["action"].strip("[] ")
        if show:
            print(f"  step {step}: {node['title'][:40]!r} -> {action}")
        if action == "use":
            return [{"source": "table_of_contents", "text": text,
                     "pages": list(range(node["start"], node["end"] + 1))}]
        if action.isdigit() and int(action) < len(node["children"]):
            node = node["children"][int(action)]
            path.append(node)
        else:                                           # "back"
            if not node["children"]:
                read.append(node["title"])
            if len(path) > 1:
                path.pop()
                node = path[-1]
    return []
found = search_toc("Where does the book compare agent orchestration frameworks in a table?", show=True)
print(found[0]["pages"], found[0]["text"][:200])
  step 1: 'The book, pages 292-374' -> 3
  step 2: 'Agent Harness – Context Management and O' -> 8
  step 3: 'Framework Comparison' -> use
[359, 360] 18.8.4 Evaluation in Production
• A/B testing: Route a fraction of traffic to a new agent version and compare success rates,
cost, and latency.
• Canary deployments: Gradually increase traffic to a ne

4. CRAG grader: เอกสารที่ได้ช่วยตอบจริงไหม

CRAG (§16.5.5) ให้คะแนนเอกสารแต่ละชิ้น: correct มีคำตอบ · ambiguous เกี่ยวแต่ไม่ตอบ · incorrect ไม่เกี่ยว ถ้าไม่มีชิ้นไหน correct → ตำราไปค้นเว็บ · ของเรา: ให้ agent ลองแหล่งอื่น

GRADE = obj(reasoning=TEXT, grade=one_of("correct", "ambiguous", "incorrect"))
def grade(query, doc):
    return ask_json(f"Question: {query}\n\nDocument (pages {doc['pages']}):\n{doc['text']}\n\n"
                    "Grade the document. correct: it contains the answer. "
                    "ambiguous: it is related but does not answer. "
                    "incorrect: it is not about the question.", GRADE)["grade"]

question = ("In Roitman's book The Hitchhiker's Guide to Agentic AI, "
            "what analogy does the RAG chapter use to explain RAG?")
for d in search_vector(question):
    print(d["pages"], grade(question, d))
[309] incorrect
[292] incorrect
[311] incorrect

5. Router: เลือกแหล่งให้ตรงกับคำถาม (Listing 16.9)

LLM-based routing: model เลือก source และเขียน refined_query ให้เหมาะกับแหล่งนั้น พร้อม reasoning ตำราบอกว่ายืดหยุ่นที่สุด แต่ เพิ่มการเรียก model หนึ่งครั้ง

SOURCES = {"keyword_search": search_keyword, "vector_db": search_vector, "table_of_contents": search_toc}
ROUTE = obj(reasoning=TEXT, source=one_of(*SOURCES), refined_query=TEXT)

def route(query, tried=()):
    note = (f"\nAlready tried, found nothing useful: {', '.join(tried)}. Pick another source."
            if tried else "")
    return ask_json(f'Given the query: "{query}"\nDecide which knowledge source to use:\n'
                    "- keyword_search: BM25 over the book's text; best for rare exact terms, acronyms and names\n"
                    "- vector_db: embedding search over the book's text; best for questions phrased in different words from the book\n"
                    "- table_of_contents: walk the book's table of contents; best when the question asks where in the book a topic is covered\n"
                    f"Return the source, a refined query for that source, and your reasoning.{note}", ROUTE)

for q in ["What is PLAID?", "How does the textbook add randomness to retry waits?",
          "Where does the book compare agent orchestration frameworks in a table?"]:
    r = route(q)
    print(f"{r['source']:17} {r['refined_query']!r}")
keyword_search    'PLAID'
vector_db         'How is randomness or jitter incorporated into retry wait times and exponential backoff strategies?'
table_of_contents 'agent orchestration frameworks comparison table'

6. วงวน agentic RAG (Listing 16.10 ด้วย Python ล้วน)

  1. Plan — แยกคำถามเป็น sub-query ทีละเรื่องที่ต้องหา
  2. Retrieve — แต่ละ sub-query: route → ค้น → grade เก็บเฉพาะชิ้นที่ correct
  3. Evaluate — context ที่สะสมมาพอตอบทุกส่วนหรือยัง
  4. ยังไม่พอ → วนกลับไป retrieve ด้วย sub-query ที่ยังขาด · พอแล้ว หรือครบ max_iterations → Generate
BOOK = "Roitman, The Hitchhiker's Guide to Agentic AI"
LIBRARY = f"Our library is one book: {BOOK}, pages 292-374."
PLAN = obj(sub_queries={"type": "array", "items": TEXT})
def plan(query):
    return ask_json(f"{LIBRARY}\nSplit this question into the separate things we must look up in the book: "
                    "one sub-query per information need, and only one if it asks for one thing."
                    f"\n\nQuestion: {query}", PLAN)["sub_queries"]

EVAL = obj(reasoning=TEXT, sufficient={"type": "boolean"}, missing={"type": "array", "items": TEXT})
def evaluate(query, docs):
    context = "\n\n".join(f"[pages {d['pages']}]\n{d['text']}" for d in docs) or "(nothing yet)"
    return ask_json(f"Question: {query}\n\nRetrieved context:\n{context}\n\n"
                    "Does this context answer every part of the question? If a part is not answered yet, "
                    "list one sub-query per missing part; do not ask for extra detail.", EVAL)

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 generate(query, docs):
    context = "\n\n".join(f"[Doc {i+1}] (Source: {BOOK}, Pages: {d['pages']})\n{d['text']}"
                          for i, d in enumerate(docs))
    return ask(f"{SYSTEM_PROMPT}\n\nContext:\n{context}\n\nQuestion: {query}\n\nAnswer:")
def agent(query, max_iterations=3):
    start = COST["calls"]
    sub_queries, docs, tried = plan(query), [], []
    print("plan:", sub_queries)
    # ✏️ TODO 2 (▶ วิดีโอ 9:54): เก็บเฉพาะเอกสารที่ grader ให้ว่า correct
    for iteration in range(1, max_iterations + 1):
        for sq in sub_queries:
            r = route(sq, tried)
            found = SOURCES[r["source"]](r["refined_query"])
            good = ___
            print(f"  round {iteration}: {r['source']:17} {len(good)}/{len(found)} correct  {sq[:45]!r}")
            if not good:
                tried.append(r["source"])
            docs += good
        # ✏️ TODO 3 (▶ วิดีโอ 10:16): ออกจากวงเมื่อ evaluate บอกว่าพอแล้ว ถ้ายังไม่พอ ใช้ sub-query ที่ยังขาดในรอบถัดไป
        check = evaluate(query, docs)
        print(f"  evaluate: sufficient = {check['sufficient']}")
        if ___:
            break
        sub_queries = ___ or sub_queries
    answer = generate(query, docs)
    print(f"  {COST['calls'] - start} model calls")
    return answer
def agent(query, max_iterations=3):
    start = COST["calls"]
    sub_queries, docs, tried = plan(query), [], []
    print("plan:", sub_queries)
    for iteration in range(1, max_iterations + 1):
        for sq in sub_queries:
            r = route(sq, tried)
            found = SOURCES[r["source"]](r["refined_query"])
            good = [d for d in found if grade(sq, d) == "correct"]
            print(f"  round {iteration}: {r['source']:17} {len(good)}/{len(found)} correct  {sq[:45]!r}")
            if not good:
                tried.append(r["source"])
            docs += good
        check = evaluate(query, docs)
        print(f"  evaluate: sufficient = {check['sufficient']}")
        if check["sufficient"]:
            break
        sub_queries = check["missing"] or sub_queries
    answer = generate(query, docs)
    print(f"  {COST['calls'] - start} model calls")
    return answer
print(agent("What is PLAID, and how does the textbook add randomness to retry waits?"))
plan: ['What is PLAID?', 'How does the textbook add randomness to retry waits?']
  round 1: keyword_search    1/3 correct  'What is PLAID?'
  round 1: vector_db         1/3 correct  'How does the textbook add randomness to retry'
  evaluate: sufficient = True
  11 model calls
PLAID is an indexing method that clusters document embeddings and uses centroids for initial candidate retrieval, followed by the computation of exact MaxSim only on candidates; this reduces latency by 5–10× [Doc 1].

To add randomness to retry waits, the textbook uses a random jitter, denoted as $\epsilon$, in the exponential backoff formula for transient failures [Doc 2]. The backoff delay for the $k$-th retry is formally expressed as $t_k = \min(2^k \cdot t_0 + U(0, t_0), t_{max})$ [Doc 2].
print(agent("Where does the book compare agent orchestration frameworks in a table?"))
plan: ['Where does the book compare agent orchestration frameworks in a table?']
  round 1: table_of_contents 1/1 correct  'Where does the book compare agent orchestrati'
  evaluate: sufficient = True
  8 model calls
The book compares major agent orchestration frameworks in Table 18.1 [Doc 1].
print(agent("What does the acronym PLAID stand for?"))
plan: ['What does the acronym PLAID stand for?']
  round 1: keyword_search    0/3 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  round 2: vector_db         0/3 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  round 3: table_of_contents 0/0 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  24 model calls
The provided context does not contain information regarding what the acronym PLAID stands for.
print(agent(question))
plan: ["What analogy does the RAG chapter in Roitman's 'The Hitchhiker's Guide to Agentic AI' use to explain RAG?"]
  round 1: table_of_contents 0/1 correct  "What analogy does the RAG chapter in Roitman'"
  evaluate: sufficient = False
  round 2: vector_db         1/3 correct  "What analogy does the RAG chapter in Roitman'"
  evaluate: sufficient = True
  14 model calls
The RAG chapter uses the "Library Analogy," where a parametric LLM is compared to a scholar who has memorized an enormous library but graduated years ago [Doc 1]. RAG is described as giving that scholar 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 1].
print(COST["calls"], "model calls ·", f"chat ${COST['chat']:.4f} · embed ${COST['embed']:.5f}")
66 model calls · chat $0.0038 · embed $0.00045

สรุป

ชิ้นส่วน ที่เราเห็นใน lab
สามแหล่ง BM25 · embedding · สารบัญ — คืนเอกสารแบบเดียวกัน
สารบัญ (นอกตำรา, MemWalker) Gemma 26B เดินจาก root ถึง Framework Comparison (หน้า 359–360) ใน 3 ก้าว ไม่ใช้ embedding
CRAG grader คำถามยาว: embedding top 3 ได้ incorrect ทั้งสามชิ้น
Router PLAID → keyword · การสุ่มเวลารอ → vector · ตารางเปรียบเทียบ framework → สารบัญ
Plan คำถามสองเรื่อง → สอง sub-query → สองแหล่ง → ตอบครบ
max_iterations “PLAID ย่อมาจากอะไร” — ตำราไม่ได้บอก → ครบ 3 รอบ → ตอบว่าไม่มีข้อมูล (24 ครั้ง)
Fallback คำถามยาว: เส้นทางต่างกันแต่ละรอบ แต่จบที่ “library card” ทุกรอบ

แบบฝึกหัด

  1. Knowledge refinement (CRAG): ก่อน generate ให้ Gemma ตัดประโยคที่ไม่เกี่ยวออกจากเอกสารที่ correct
  2. รัน agent("What is PLAID?") หลายรอบ — บางรอบ evaluate ขอให้หาว่าชื่อย่อมาจากอะไร และค้นเพิ่มอีกสองรอบ แก้ prompt ให้มันจบในรอบแรก แล้วลองคำถามสองเรื่องอีกครั้ง ยังค้นครบทั้งสองส่วนไหม
  3. Parallel fan-out: ค้นทุกแหล่งพร้อมกัน แล้วรวมด้วย RRF แทนการ route (ตำรา §16.7.3) — เรียก model มากขึ้นหรือน้อยลง

ถัดไป — Lab 3: วัดผล RAG — เขียน Recall@K, MRR, NDCG และ faithfulness เอง แล้ววัดทุกระบบที่เราสร้างมา