Skip to main content

Lab 4 — agentic RAG ตัวเดิมด้วย LangGraph

Lab walkthrough · EP11 Advanced & Agentic RAG

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

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

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

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

Lab 2 เราเขียนวงวน plan → retrieve → evaluate → generate ด้วย for กับ if เอง — ตำราเขียนวงเดียวกันด้วย LangGraph (Listing 16.10) lab นี้ใช้เครื่องมือทุกตัวจาก Lab 2 เหมือนเดิม เปลี่ยนแค่ วงวน

Lab 2 (เขียนเอง) LangGraph
ตัวแปร docs, tried, sub_queries AgentState (TypedDict) + reducer operator.add
ขั้น plan / retrieve / evaluate / generate node สี่ตัว — ฟังก์ชันที่รับ state แล้วคืน เฉพาะช่องที่เปลี่ยน
for iteration in range(max_iterations) + break conditional edge should_retrieve
print ในลูป stream(stream_mode="updates")
— recursion_limit ตาข่ายกันวนของ framework เอง

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

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §16.7.4 Listing 16.10 — CC BY-SA 4.0

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key key เดิมจาก Lab 1 (lab นี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์) — วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1
Packages langgraph==1.2.16 (ตัวเดียวกับ EP04, EP05, EP08), openai, python-dotenv, pypdf, numpy, tokenizers

ใส่ API key

  • Colab: ไอคอน 🔑 Secrets → ชื่อ OPENROUTER_API_KEY → เปิด Notebook access
  • เครื่องตัวเอง: สร้างไฟล์ .env ในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัด OPENROUTER_API_KEY=sk-or-...

⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env

%pip install -q "langgraph==1.2.16" "openai>=1.50" python-dotenv "pypdf>=6" numpy "tokenizers==0.23.3"

1. เครื่องมือทุกตัวจาก Lab 2

สาม cell ถัดไปคือโค้ดจาก Lab 2 ไม่มีอะไรใหม่: model + ask_json · คลัง 141 ชิ้น + BM25 · สามแหล่ง (keyword, vector, สารบัญ) + grade, route, plan, evaluate, generate

import os, re, math, json, operator, urllib.request
from collections import Counter
from typing import TypedDict, Annotated
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):
    for attempt in range(2):                            # one retry if the JSON comes back cut off (Lab 3)
        r = client.chat.completions.create(
            model=MODEL, temperature=0, extra_body=EXTRA, max_tokens=1500,
            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
        try:
            return json.loads(r.choices[0].message.content)
        except json.JSONDecodeError:
            pass
    raise ValueError("the model did not return valid JSON")

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")
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
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")

def walk(outline, depth=0):                             # the table of contents as a tree
    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]
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)
    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)
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):
    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 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:
            if not node["children"]:
                read.append(node["title"])
            if len(path) > 1:
                path.pop()
                node = path[-1]
    return []

SOURCES = {"keyword_search": search_keyword, "vector_db": search_vector, "table_of_contents": search_toc}

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"]

ROUTE = obj(reasoning=TEXT, source=one_of(*SOURCES), refined_query=TEXT)
def route(query, tried=()):
    if set(tried) >= set(SOURCES):                      # every source already tried: start over
        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)

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:")

2. State: ทุกอย่างที่ agent จำระหว่างทาง

ใน Lab 2 เป็นตัวแปรใน agent() — ใน LangGraph รวมเป็น AgentState เดียว ทุก node อ่านและเขียนช่องของมัน ช่องที่มี reducer operator.add จะ ต่อท้าย ค่าที่ node คืนมา แทนการเขียนทับ

# ✏️ TODO 1 (▶ วิดีโอ 2:17): ทำให้ retrieved_docs ต่อท้ายเอกสารใหม่ แทนการเขียนทับ (reducer operator.add)
class AgentState(TypedDict):
    query: str
    sub_queries: list[str]
    retrieved_docs: ___
    tried: Annotated[list[str], operator.add]
    context_sufficient: bool
    answer: str
    iterations: int
    max_iterations: int
class AgentState(TypedDict):
    query: str
    sub_queries: list[str]
    retrieved_docs: Annotated[list[dict], operator.add]
    tried: Annotated[list[str], operator.add]
    context_sufficient: bool
    answer: str
    iterations: int
    max_iterations: int

3. Node สี่ตัว

แต่ละ node รับ state แล้วคืน dict ของช่องที่เปลี่ยน — LangGraph รวมเข้ากับ state ให้เอง

def plan_node(state):
    return {"sub_queries": plan(state["query"]), "iterations": 0}

def retrieve_node(state):
    new_docs, failed = [], []
    for sq in state["sub_queries"]:
        r = route(sq, state["tried"])
        found = SOURCES[r["source"]](r["refined_query"])
        good = [d for d in found if grade(sq, d) == "correct"]
        print(f"  retrieve: {r['source']:17} {len(good)}/{len(found)} correct  {sq[:45]!r}")
        if not good:
            failed.append(r["source"])
        new_docs += good
    # ✏️ TODO 2 (▶ วิดีโอ 3:21): คืนเฉพาะเอกสารใหม่ แหล่งที่พลาด และตัวนับรอบที่เพิ่มขึ้นหนึ่ง
    return {"retrieved_docs": ___, "tried": failed,
            "iterations": ___}

def evaluate_node(state):
    check = evaluate(state["query"], state["retrieved_docs"])
    print(f"  evaluate: sufficient = {check['sufficient']}")
    return {"context_sufficient": check["sufficient"],
            "sub_queries": check["missing"] or state["sub_queries"]}

def generate_node(state):
    return {"answer": generate(state["query"], state["retrieved_docs"])}
def plan_node(state):
    return {"sub_queries": plan(state["query"]), "iterations": 0}

def retrieve_node(state):
    new_docs, failed = [], []
    for sq in state["sub_queries"]:
        r = route(sq, state["tried"])
        found = SOURCES[r["source"]](r["refined_query"])
        good = [d for d in found if grade(sq, d) == "correct"]
        print(f"  retrieve: {r['source']:17} {len(good)}/{len(found)} correct  {sq[:45]!r}")
        if not good:
            failed.append(r["source"])
        new_docs += good
    return {"retrieved_docs": new_docs, "tried": failed,
            "iterations": state["iterations"] + 1}

def evaluate_node(state):
    check = evaluate(state["query"], state["retrieved_docs"])
    print(f"  evaluate: sufficient = {check['sufficient']}")
    return {"context_sufficient": check["sufficient"],
            "sub_queries": check["missing"] or state["sub_queries"]}

def generate_node(state):
    return {"answer": generate(state["query"], state["retrieved_docs"])}
# ✏️ TODO 3 (▶ วิดีโอ 3:53): เมื่อ context พอแล้ว หรือครบ max_iterations ให้ไป generate ไม่อย่างนั้นกลับไป retrieve
def should_retrieve(state):
    if ___:
        return "generate"
    if ___:
        return "generate"        # give up and generate with what we have
    return "retrieve"
def should_retrieve(state):
    if state["context_sufficient"]:
        return "generate"
    if state["iterations"] >= state["max_iterations"]:
        return "generate"        # give up and generate with what we have
    return "retrieve"

4. ต่อ node เป็น graph

plan → retrieve → evaluate → (generate หรือกลับ retrieve) → END — ตรงกับ Listing 16.10

from langgraph.graph import StateGraph, END

workflow = StateGraph(AgentState)
for name, fn in [("plan", plan_node), ("retrieve", retrieve_node),
                 ("evaluate", evaluate_node), ("generate", generate_node)]:
    workflow.add_node(name, fn)
workflow.set_entry_point("plan")
workflow.add_edge("plan", "retrieve")
workflow.add_edge("retrieve", "evaluate")
workflow.add_conditional_edges("evaluate", should_retrieve,
                               {"retrieve": "retrieve", "generate": "generate"})
workflow.add_edge("generate", END)
agent = workflow.compile()
for e in agent.get_graph().edges:
    print(f"{e.source:9} -> {e.target:9} {'(conditional)' if e.conditional else ''}")
__start__ -> plan      
evaluate  -> generate  (conditional)
evaluate  -> retrieve  (conditional)
plan      -> retrieve  
retrieve  -> evaluate  
generate  -> __end__

5. รัน agent

stream(..., stream_mode="updates") ส่งผลของแต่ละ node ออกมาทีละขั้น — เห็นว่า graph เดินผ่าน node ไหนบ้าง

def start(query, max_iterations=3):
    return {"query": query, "max_iterations": max_iterations,
            "retrieved_docs": [], "tried": [], "iterations": 0}

for update in agent.stream(start("What is PLAID, and how does the textbook add randomness to retry waits?"),
                           stream_mode="updates"):
    print("node:", list(update))
node: ['plan']
  retrieve: keyword_search    1/3 correct  'What is PLAID?'
  retrieve: vector_db         1/3 correct  'How does the textbook add randomness to retry'
node: ['retrieve']
  evaluate: sufficient = True
node: ['evaluate']
node: ['generate']
result = agent.invoke(start("What does the acronym PLAID stand for?"))
print(result["iterations"], "rounds ·", len(result["retrieved_docs"]), "documents")
print(result["answer"])
  retrieve: keyword_search    0/3 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  retrieve: vector_db         0/3 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  retrieve: table_of_contents 0/0 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
3 rounds · 0 documents
The provided context does not contain information regarding what the acronym PLAID stands for.

6. จุดที่ต้องระวังในโค้ดของตำรา

node ใน Listing 16.10 คืน {**state, ...} — state ทั้งก้อน รวมถึง retrieved_docs เดิม แต่ retrieved_docs มี reducer operator.add → LangGraph ต่อท้ายเอกสารเดิมซ้ำอีกรอบ

def book_evaluate_node(state):                         # written the way Listing 16.10 writes its nodes
    check = evaluate(state["query"], state["retrieved_docs"])
    return {**state, "context_sufficient": check["sufficient"]}

book = StateGraph(AgentState)
for name, fn in [("plan", plan_node), ("retrieve", retrieve_node),
                 ("evaluate", book_evaluate_node), ("generate", generate_node)]:
    book.add_node(name, fn)
book.set_entry_point("plan")
book.add_edge("plan", "retrieve")
book.add_edge("retrieve", "evaluate")
book.add_conditional_edges("evaluate", should_retrieve, {"retrieve": "retrieve", "generate": "generate"})
book.add_edge("generate", END)

for name, g in [("ours", agent), ("book style", book.compile())]:
    s = g.invoke(start("What is PLAID, and how does the textbook add randomness to retry waits?"))
    print(f"{name:10}", len(s["retrieved_docs"]), "documents, pages", [d["pages"][0] for d in s["retrieved_docs"]])
  retrieve: keyword_search    1/3 correct  'What is PLAID?'
  retrieve: vector_db         1/3 correct  'How does the textbook add randomness to retry'
  evaluate: sufficient = True
ours       2 documents, pages [301, 357]
  retrieve: keyword_search    1/3 correct  'What is PLAID?'
  retrieve: vector_db         1/3 correct  'How does the textbook add randomness to retry'
book style 4 documents, pages [301, 357, 301, 357]

7. สิ่งที่ framework เพิ่มให้: recursion_limit

ถ้าลืมตั้งเพดาน หรือตั้งสูงเกินไป LangGraph มีตาข่ายของตัวเอง: เดินได้ไม่เกิน recursion_limit ก้าว (ค่าเริ่มต้น 25) แล้วหยุดด้วย GraphRecursionError

from langgraph.errors import GraphRecursionError

try:
    agent.invoke(start("What does the acronym PLAID stand for?", max_iterations=100),
                 {"recursion_limit": 10})
except GraphRecursionError as e:
    print("stopped:", str(e)[:80])
  retrieve: keyword_search    0/3 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  retrieve: vector_db         0/3 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  retrieve: table_of_contents 0/0 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  retrieve: keyword_search    0/3 correct  'What does the acronym PLAID stand for?'
  evaluate: sufficient = False
  retrieve: keyword_search    0/3 correct  'What does the acronym PLAID stand for?'
stopped: Recursion limit of 10 reached without hitting a stop condition. You can increase
print(COST["calls"], "model calls ·", f"chat ${COST['chat']:.4f} · embed ${COST['embed']:.5f}")
89 model calls · chat $0.0049 · embed $0.00045

สรุป

Lab 2 (เขียนเอง) LangGraph ที่เราเห็นใน lab
docs += good reducer operator.add node คืนแค่เอกสารใหม่ LangGraph ต่อท้ายให้
ลูป for + break should_retrieve + conditional edge คำถามสองเรื่องจบรอบเดียว · คำถามที่ไม่มีคำตอบ ครบ 3 รอบแล้วตอบว่าไม่มีข้อมูล
print stream(stream_mode="updates") เห็น plan → retrieve → evaluate → generate
— recursion_limit หยุดที่ 10 ก้าวด้วย GraphRecursionError — ไม่มีคำตอบให้ผู้ใช้

⚠️ โค้ดของตำรา: node ที่คืน {**state, ...} ทำให้ retrieved_docs ซ้ำ (2 → 4 เอกสาร) — คืนเฉพาะช่องที่เปลี่ยน

แบบฝึกหัด

  1. แก้ plan_node และ retrieve_node ให้คืน {**state, ...} แบบตำราด้วย — เอกสารซ้ำกี่เท่า
  2. เพิ่ม checkpoint ด้วย InMemorySaver (EP05 Lab 5) แล้วดู get_state_history ของคำถามที่วนสามรอบ
  3. แยก retrieve_node เป็นสอง node: route และ search — graph ยาวขึ้น แต่ stream บอกอะไรเราเพิ่มขึ้น

ถัดไป — สรุป EP11