Skip to main content

Lab 3 — แบ่ง context แล้วเรียกซ้ำ

Lab walkthrough · EP07 Context Window Management

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

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

▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP07 Context Window Management

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

Lab 2 ทุกวิธียอมรับข้อจำกัดเดียวกัน: ทุกอย่างต้องลงหน้าต่างเดียว §18.2.5 เสนออีกทาง — ไม่มี call ไหนเห็น context ทั้งหมด:

RLM(q, C) = M(q, RLM(q₁, C₁), RLM(q₂, C₂), …) (สมการ 18.7)

แบ่ง (decompose) → เรียกซ้ำทีละชิ้น (recurse) → รวมผล (aggregate) ตามโค้ด recursive_summarize ในตำรา

สิ่งที่จะได้เรียน

  1. เมื่อเอกสารใหญ่กว่างบ: ตัดให้พอดีแล้วส่งครั้งเดียว — เห็นแค่ต้นเอกสาร
  2. เขียน recursive_summarize ตามตำรา แล้วดูต้นไม้ของการเรียก
  3. จุดพลาดที่เจอจริง: แบ่งชิ้นแล้ว หัวข้อหาย
  4. ต้นทุน: กี่ call, call ที่ใหญ่ที่สุดกี่ token

บันทึกการประชุมในเอกสารเป็น ข้อมูลจำลองที่สร้างขึ้นเพื่อการสอน ส่วนคำตอบของ model มาจากการรันจริง

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

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์)
Packages openai, python-dotenv, 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 "tokenizers==0.23.3"

1. Model และการนับ token (จาก Lab 1)

Gemma 4 26B ผ่าน OpenRouter ล็อก provider DeepInfra — เหตุผลที่เลือก model และวิธีตั้งค่า key อยู่ใน Lab 1 call เรียก model ด้วย temperature 0 และจดไว้ใน CALLS ว่าแต่ละ call อยู่ชั้นไหนของต้นไม้ และส่งไปกี่ token

import os, re, random
from openai import OpenAI
os.environ["HF_HUB_VERBOSITY"] = "error"
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"]

client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key())
MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False}, "provider": {"order": ["deepinfra/fp8"], "allow_fallbacks": False}}
CALLS = []   # (depth, input tokens, output tokens) of every call

def call(prompt, depth=0):
    reply = client.chat.completions.create(model=MODEL, messages=[{"role": "user", "content": prompt}],
                                           max_tokens=500, temperature=0, extra_body=EXTRA)
    CALLS.append((depth, reply.usage.prompt_tokens, reply.usage.completion_tokens))
    return reply.choices[0].message.content

tok = Tokenizer.from_pretrained(MODEL)

def count_tokens(text):
    return len(tok.encode(text, add_special_tokens=False).ids)

2. เอกสารที่ใหญ่กว่างบ

บันทึกการประชุมของกลุ่มวิจัยทั้งปี (52 สัปดาห์ · ข้อมูลจำลอง) — มีการตัดสินใจเรื่อง paper กระจายอยู่สามที่ และสัปดาห์ที่ 27 เป็น บันทึกการประชุมฉบับเต็ม ที่ยาวกว่าสัปดาห์อื่นมาก

คำถาม: paper ไหนที่กลุ่มตัดสินใจเอาออกจากตารางหลักของรีวิว เพราะอะไร สัปดาห์ไหน

งบต่อ call ของ lab นี้: 1,500 token (ตั้งเล็กเพื่อให้เห็นต้นไม้ชัด — หลักการเดียวกับเอกสารหลายแสน token)

random.seed(3)  # simulated meeting notes, generated for teaching
PEOPLE = ["Nok", "Ton", "Ploy", "Bank", "Mint"]
TASKS = ["data loaders for the weather set", "the GPU booking sheet", "a reading list for new members", "plots for the seminar",
         "the baseline scripts", "the shared bibliography file", "unit tests for the metrics", "the poster draft"]
DECISIONS = {
    9:  "- Decision: drop P09 (Temporal Fusion Transformer) from the main table, because it was published in 2019, before our 2023 cutoff.",
    30: "- Ploy suggested dropping P05 (PatchTST), but we decided to keep it: it is the strongest baseline we have.",
    44: "- Decision: drop P08 (Chronos) from the main table, because its benchmark used a different forecast horizon, so the numbers are not comparable.",
}

def week(k):
    a, b = random.sample(PEOPLE, 2)
    lines = [f"## Week {k}", f"Present: {', '.join(random.sample(PEOPLE, 4))}."]
    for _ in range(5):
        lines.append(f"- {random.choice(PEOPLE)} worked on {random.choice(TASKS)}; about {random.randint(2, 9)} hours, "
                     f"{random.choice(['done', 'half done', 'blocked on data', 'needs review'])}.")
    lines.append(f"- Next week: {a} presents, {b} takes notes.")
    return "\n".join(lines)

def transcript(k):
    lines = [f"## Week {k} (full transcript of the review meeting)"]
    for i in range(60):
        lines.append(f"{random.choice(PEOPLE)}: On {random.choice(TASKS)}, I think we should spend {random.randint(1, 6)} more hours "
                     f"before the seminar, and check it with {random.choice(PEOPLE)} first.")
        if i % 6 == 5:
            lines.append("")
        if i == 33:
            lines.append("Nok: So we agree: drop P04 (Are Transformers Effective for Time Series Forecasting?) from the main table, "
                         "because it is a critique of transformers, not a new model. It moves to the discussion section.")
    return "\n".join(lines)

weeks = []
for k in range(1, 53):
    w = transcript(k) if k == 27 else week(k)
    weeks.append(w + ("\n" + DECISIONS[k] if k in DECISIONS else ""))
DOC = "\n\n".join(["# Cogito Learn research group: meeting notes, 2026"] + weeks)
MAX = 1500
QUERY = ("Which papers did we decide to drop from the review's main table, and why? "
         "Answer one line per paper: paper id, week, reason.")
print(f"document: {count_tokens(DOC):,} tokens · budget per call: {MAX:,}")

def report(answer):
    print(answer)
    found = {}
    for p in ["P09", "P04", "P08"]:
        lines = [l for l in answer.splitlines() if p in l]
        if lines:
            weeks = re.findall(r"[Ww]eek (\d+)", lines[0])
            found[p] = "week " + weeks[0] if weeks else "week ?"
    print("→", found)
document: 8,243 tokens · budget per call: 1,500

3. ตัดให้พอดีแล้วส่งครั้งเดียว

วิธีที่ง่ายที่สุด: เก็บแค่ 1,500 token แรก แล้วถามครั้งเดียว

first_part = tok.decode(tok.encode(DOC, add_special_tokens=False).ids[:MAX])
report(call(f"{QUERY}\n\nContext:\n{first_part}"))
P09, Week 9, published in 2019 before the 2023 cutoff.
→ {'P09': 'week 9'}

4. recursive_summarize ตามตำรา

  1. Base case: ถ้า context ลงงบ → เรียก model ครั้งเดียว
  2. Recursive case: แบ่งตามโครงสร้างเป็นชิ้นละไม่เกินครึ่งงบ → เรียกตัวเองกับแต่ละชิ้น ด้วยคำถามย่อย
  3. Aggregate: รวมผลย่อยทั้งหมด แล้วถามคำถามเดิมอีกครั้ง

“แบ่งตามโครงสร้าง” ของเอกสารนี้: แบ่งตามหัวข้อ ## Week · ถ้าเหลือหัวข้อเดียวที่ยังใหญ่ ค่อยแบ่งตามย่อหน้า

KEEP_HEADING = False

def split_by_structure(text, max_tokens):
    units, head = re.split(r"\n(?=## )", text), ""
    if len(units) == 1:              # a single section that is still too big → split it by paragraphs
        head, body = text.split("\n", 1)
        units = body.split("\n\n")

    # ✏️ TODO 1 (▶ วิดีโอ 3:29): ถ้าเพิ่มหน่วยนี้แล้วเกินงบ ให้ปิดชิ้นปัจจุบัน แล้วเริ่มชิ้นใหม่ด้วยหน่วยนี้

    chunks, cur = [], ""
    for u in units:
        if cur and ___:
            chunks.append(cur)
            cur = ___
        else:
            cur = cur + "\n\n" + u if cur else u
    chunks.append(cur)
    if head and KEEP_HEADING:
        chunks = [head + "\n" + c for c in chunks]
    return chunks
KEEP_HEADING = False

def split_by_structure(text, max_tokens):
    units, head = re.split(r"\n(?=## )", text), ""
    if len(units) == 1:              # a single section that is still too big → split it by paragraphs
        head, body = text.split("\n", 1)
        units = body.split("\n\n")

    chunks, cur = [], ""
    for u in units:
        if cur and count_tokens(cur + "\n\n" + u) > max_tokens:
            chunks.append(cur)
            cur = u
        else:
            cur = cur + "\n\n" + u if cur else u
    chunks.append(cur)
    if head and KEEP_HEADING:
        chunks = [head + "\n" + c for c in chunks]
    return chunks
# ✏️ TODO 2 (▶ วิดีโอ 3:46): base case: ถ้า context ลงงบ เรียก model ครั้งเดียว
def recursive_summarize(context, query, max_tokens, depth=0):
    n = count_tokens(context)
    print("    " * depth + f"depth {depth}: {n:,} tokens")
    if ___:
        return call(f"{query}\n\nContext:\n{context}", depth)

    chunks = split_by_structure(context, max_tokens // 2)
    sub_results = [recursive_summarize(c, f"Summarize this section relevant to: {query}", max_tokens, depth + 1)
                   for c in chunks]

    # ✏️ TODO 3 (▶ วิดีโอ 4:10): aggregate: ต่อผลย่อยทั้งหมด แล้วถามคำถามเดิมอีกครั้ง

    combined = ___
    return call(f"Given these partial summaries, answer: {query}\n\nSummaries:\n{combined}", depth)
def recursive_summarize(context, query, max_tokens, depth=0):
    n = count_tokens(context)
    print("    " * depth + f"depth {depth}: {n:,} tokens")
    if n <= max_tokens:
        return call(f"{query}\n\nContext:\n{context}", depth)

    chunks = split_by_structure(context, max_tokens // 2)
    sub_results = [recursive_summarize(c, f"Summarize this section relevant to: {query}", max_tokens, depth + 1)
                   for c in chunks]

    combined = "\n---\n".join(sub_results)
    return call(f"Given these partial summaries, answer: {query}\n\nSummaries:\n{combined}", depth)
CALLS.clear()
report(recursive_summarize(DOC, QUERY, MAX))
depth 0: 8,243 tokens
    depth 1: 628 tokens
    depth 1: 654 tokens
    depth 1: 739 tokens
    depth 1: 727 tokens
    depth 1: 494 tokens
    depth 1: 1,854 tokens
        depth 2: 720 tokens
        depth 2: 581 tokens
        depth 2: 537 tokens
    depth 1: 650 tokens
    depth 1: 744 tokens
    depth 1: 610 tokens
    depth 1: 652 tokens
    depth 1: 491 tokens
P09, Week 9, published in 2019 before the 2023 cutoff.
P04, N/A, it is a critique of transformers, not a new model.
P08, Week 44, its benchmark used a different forecast horizon so the numbers are not comparable.
→ {'P09': 'week 9', 'P04': 'week ?', 'P08': 'week 44'}

5. หัวข้อหายตอนแบ่งชิ้น

สัปดาห์ที่ 27 ถูกแบ่งตามย่อหน้าที่ความลึก 2 — ชิ้นที่มีการตัดสินใจเรื่อง P04 ไม่มีบรรทัด ## Week 27 อยู่เลย model ที่อ่านชิ้นนั้นจึงไม่มีทางรู้ว่าเป็นสัปดาห์ไหน → แก้ที่ harness: พาหัวข้อไปกับทุกชิ้น

print(split_by_structure(weeks[26], MAX // 2)[1][:200])
Mint: On the baseline scripts, I think we should spend 1 more hours before the seminar, and check it with Bank first.
Nok: On plots for the seminar, I think we should spend 2 more hours before the sem
KEEP_HEADING = True
print(split_by_structure(weeks[26], MAX // 2)[1][:200])
## Week 27 (full transcript of the review meeting)
Mint: On the baseline scripts, I think we should spend 1 more hours before the seminar, and check it with Bank first.
Nok: On plots for the seminar,
CALLS.clear()
report(recursive_summarize(DOC, QUERY, MAX))
depth 0: 8,243 tokens
    depth 1: 628 tokens
    depth 1: 654 tokens
    depth 1: 739 tokens
    depth 1: 727 tokens
    depth 1: 494 tokens
    depth 1: 1,854 tokens
        depth 2: 734 tokens
        depth 2: 595 tokens
        depth 2: 551 tokens
    depth 1: 650 tokens
    depth 1: 744 tokens
    depth 1: 610 tokens
    depth 1: 652 tokens
    depth 1: 491 tokens
P09, Week 9, published in 2019 before the 2023 cutoff.
P04, Week 27, it is a critique of transformers rather than a new model.
P08, Week 44, its benchmark used a different forecast horizon so the numbers are not comparable.
→ {'P09': 'week 9', 'P04': 'week 27', 'P08': 'week 44'}

6. ต้นทุนของการเรียกซ้ำ

ไม่มี call ไหนเห็นเอกสารทั้งหมด — แต่ต้องเรียก model หลายครั้ง เทียบกับการส่งเอกสารทั้งฉบับครั้งเดียว (8 พันกว่า token ลงหน้าต่างจริงของ Gemma ได้สบาย — งบ 1,500 เป็นงบสมมติของ lab)

tree = list(CALLS)
print(f"recursive: {len(tree)} calls · largest call {max(c[1] for c in tree):,} tokens · "
      f"total input {sum(c[1] for c in tree):,} tokens · deepest level {max(c[0] for c in tree)}")
CALLS.clear()
report(call(f"{QUERY}\n\nContext:\n{DOC}"))
print(f"one call: {CALLS[0][1]:,} tokens")
recursive: 15 calls · largest call 798 tokens · total input 9,509 tokens · deepest level 2
P09, Week 9, published in 2019 before the 2023 cutoff
P04, Week 27, it is a critique of transformers rather than a new model
P08, Week 44, its benchmark used a different forecast horizon making numbers incomparable
→ {'P09': 'week 9', 'P04': 'week 27', 'P08': 'week 44'}
one call: 8,291 tokens
cost = sum(c[1] for c in tree + CALLS) / 1e6 * 0.07 + sum(c[2] for c in tree + CALLS) / 1e6 * 0.34
print(f"the recursive run + the one-call run ≈ ${cost:.4f}")
the recursive run + the one-call run ≈ $0.0014

สรุป

สิ่งที่ทำ ที่เราเห็นใน lab
ตัดให้พอดี ส่งครั้งเดียว เห็นแค่ต้นเอกสาร → เจอแค่ P09
recursive_summarize ต้นไม้ลึก 2 ชั้น (สัปดาห์ 27 แตกต่อ) · เจอครบ 3 ฉบับ แต่ P04 ไม่มีสัปดาห์
พาหัวข้อไปทุกชิ้น ครบทั้ง 3 ฉบับพร้อมสัปดาห์ 9 · 27 · 44 · ไม่หลงตัวหลอก P05
ต้นทุน 15 call · call ใหญ่สุดไม่เกินงบ · token รวมมากกว่าส่งครั้งเดียวเล็กน้อย

แบบฝึกหัด

  1. ลด MAX เป็น 800 — ต้นไม้ลึกขึ้นไหม ใช้กี่ call และคำตอบยังครบไหม
  2. ตำราบอกว่ารูปแบบนี้ใช้ค้นเข็มในกองฟาง (recursive search) ได้ด้วย: เปลี่ยน QUERY เป็น “Who suggested dropping P05?” แล้วรันอีกครั้ง

ถัดไป — Lab 4: ทำเรื่องเดียวกับ Lab 2 ด้วย framework — SummarizationMiddleware ของ LangChain