Skip to main content

Lab 2 — เมื่อ history ล้นหน้าต่าง

Lab walkthrough · EP07 Context Window Management

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

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

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

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

Lab 1: ถ้าปล่อยให้ API ตัดเอง ข้อความสำคัญหายไปเงียบๆ → คราวนี้ harness เลือกเองว่าจะเก็บอะไร

บทสนทนาเดียวกัน งบ history เท่ากัน สี่วิธีจาก §18.2.3–18.2.4:

  1. FIFO — ทิ้งข้อความเก่าที่สุดก่อน
  2. Pinned — ปักหมุดข้อความแรกของผู้ใช้ไว้ ที่เหลือใช้ FIFO
  3. Importance-weighted — ให้น้ำหนักแต่ละข้อความ แล้วเก็บแบบ knapsack (สมการ 18.6)
  4. Summarization — สรุปของเก่าเป็นย่อหน้าเดียว เก็บของใหม่ไว้ครบ (สมการ 18.4)

แล้วให้คะแนนแต่ละวิธีด้วยโค้ด: ตอบเป็นไทยไหม · มี paper เก่ากว่า 2023 ที่ผู้ใช้สั่งตัดออกไหม · ได้ paper ที่ถูกครบไหม

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

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §18.2.3–18.2.4 — 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 message_tokens นับ token ของหนึ่ง message ในรูปแบบแชทของ Gemma (ตรงกับ API ไม่เกิน 1 token)

import json, os, re
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}}
USAGE = {"in": 0, "out": 0}

def chat(messages, max_tokens=400, **kw):
    reply = client.chat.completions.create(model=MODEL, messages=messages, max_tokens=max_tokens, extra_body=EXTRA | kw)
    USAGE["in"] += reply.usage.prompt_tokens
    USAGE["out"] += 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)

def message_tokens(m):
    role = "model" if m["role"] == "assistant" else m["role"]
    return count_tokens(f"<|turn>{role}\n{m['content'].strip()}<turn|>\n")

2. บทสนทนาที่ยาวเกินงบ

ผู้ใช้คุยกับ research assistant (ข้อมูลจำลอง):

  • ข้อความแรก: โจทย์ — เขียนรีวิวเรื่อง transformer สำหรับ time series · ตอบเป็นภาษาไทยเสมอ
  • ข้อความที่สาม: แก้โจทย์ — ใช้เฉพาะ paper ตั้งแต่ปี 2023
  • จากนั้น: โน้ตของ paper 10 ฉบับ (2019–2024) สลับกับคุยเล่น

งบ history ของ lab นี้: 400 token — ตั้งเล็กๆ ให้เห็นผลเร็วและถูก (งานจริงตามสมการ 18.2: H ≤ 50% ของ C ≈ 131,000 token แต่หลักการเดียวกัน)

PAPERS = {  # simulated notes written for teaching; the titles and years are real papers
    "P01": ("Informer", 2021, "ProbSparse self-attention cuts the cost of long inputs; tested on electricity and weather data."),
    "P02": ("Autoformer", 2021, "Replaces attention with auto-correlation and splits each series into trend and seasonal parts."),
    "P03": ("FEDformer", 2022, "Works in the frequency domain with Fourier and wavelet blocks; linear cost in sequence length."),
    "P04": ("Are Transformers Effective for Time Series Forecasting?", 2023, "A one-layer linear model beats several transformers."),
    "P05": ("PatchTST", 2023, "Cuts each series into patches of 16 points and treats channels independently."),
    "P06": ("iTransformer", 2024, "Inverts the axes: each variable becomes a token, attention runs across variables."),
    "P07": ("TimesFM", 2024, "A decoder-only foundation model pretrained on 100 billion time points; good zero-shot forecasts."),
    "P08": ("Chronos", 2024, "Scales and quantizes values into tokens and trains a T5 language model on them."),
    "P09": ("Temporal Fusion Transformer", 2019, "LSTM encoders with attention and variable selection for interpretable forecasts."),
    "P10": ("Moirai", 2024, "A universal forecasting transformer trained on 27 billion observations across nine domains."),
}
SMALL_TALK = ["Thanks!", "Nice, coffee break, back in five minutes.", "Haha, my cat just walked on the keyboard.", "Ok, next one."]

HISTORY = [
    {"role": "user", "content": "Task for this whole chat: I'm writing a literature review on transformers for time series. I'll paste paper notes. Always answer in Thai."},
    {"role": "assistant", "content": "เข้าใจแล้วครับ ส่งโน้ตของ paper มาได้เลย"},
    {"role": "user", "content": "Correction to the task: my review only covers papers published in 2023 or later. Leave older ones out."},
    {"role": "assistant", "content": "รับทราบครับ จะใช้เฉพาะ paper ตั้งแต่ปี 2023"},
]
for i, pid in enumerate(["P04", "P05", "P06", "P01", "P07", "P09", "P08", "P02", "P10", "P03"]):
    title, year, note = PAPERS[pid]
    HISTORY += [{"role": "user", "content": f"Paper note {pid}: {title} ({year}). {note}"},
                {"role": "assistant", "content": f"บันทึก {pid} แล้วครับ"}]
    if i % 3 == 2:
        HISTORY += [{"role": "user", "content": SMALL_TALK[i // 3]}, {"role": "assistant", "content": "ได้เลยครับ"}]
def label(m):
    t = m["content"]
    if t.startswith("Task"): return "T"
    if t.startswith("Correction"): return "C"
    if t.startswith("Paper note"): return t[11:14]
    return "a" if m["role"] == "assistant" else "s"

def show(kept, history=HISTORY):
    ids = {id(m) for m in kept}
    print(" ".join(label(m) if id(m) in ids else "·" for m in history))
    print(f"kept {len(kept)}/{len(history)} messages, {sum(message_tokens(m) for m in kept)} tokens")
BUDGET = 400
show(HISTORY)
T a C a P04 a P05 a P06 a s a P01 a P07 a P09 a s a P08 a P02 a P10 a s a P03 a
kept 30/30 messages, 652 tokens
SYSTEM = {"role": "system", "content": "You are the Cogito Learn research assistant."}
ASK = "List every paper that belongs in my review, one line each: id, title, year."
RESULTS = {}

def ask(name, kept):
    answer = chat([SYSTEM] + kept + [{"role": "user", "content": ASK}])
    ids = sorted(set(re.findall(r"^\W*(P\d\d)", answer, re.M)))  # ids that start a line = the listed papers
    RESULTS[name] = {"thai": sum(0x0E00 <= ord(ch) <= 0x0E7F for ch in answer) > 20,
                     "older than 2023": [p for p in ids if PAPERS[p][1] < 2023],
                     "right papers": f"{sum(PAPERS[p][1] >= 2023 for p in ids)}/6"}
    print(answer, "\n→", RESULTS[name])
ask("full history", HISTORY)
นี่คือรายชื่อ paper ที่ตรงตามเงื่อนไข (ตีพิมพ์ตั้งแต่ปี 2023 เป็นต้นไป) สำหรับการทำ literature review ของคุณครับ:

P04, Are Transformers Effective for Time Series Forecasting?, 2023
P05, PatchTST, 2023
P06, iTransformer, 2024
P07, TimesFM, 2024
P08, Chronos, 2024
P10, Moirai, 2024 
→ {'thai': True, 'older than 2023': [], 'right papers': '6/6'}

3. FIFO — ทิ้งข้อความเก่าที่สุดก่อน

เก็บจากข้อความล่าสุดย้อนขึ้นไป จนกว่าจะเต็มงบ

# ✏️ TODO 1 (▶ วิดีโอ 3:31): หยุดเมื่อข้อความนี้จะทำให้เกินงบ
def fifo(history, budget):
    kept, used = [], 0
    for m in reversed(history):
        if ___:
            break
        kept.insert(0, m)
        used += message_tokens(m)
    return kept

kept = fifo(HISTORY, BUDGET)
show(kept)
ask("FIFO", kept)
def fifo(history, budget):
    kept, used = [], 0
    for m in reversed(history):
        if used + message_tokens(m) > budget:
            break
        kept.insert(0, m)
        used += message_tokens(m)
    return kept

kept = fifo(HISTORY, BUDGET)
show(kept)
ask("FIFO", kept)
· · · · · · · · · · · a P01 a P07 a P09 a s a P08 a P02 a P10 a s a P03 a
kept 19/30 messages, 399 tokens
นี่คือรายการ Paper ทั้งหมดที่คุณบันทึกไว้ครับ:

P01: Informer (2021)
P07: TimesFM (2024)
P09: Temporal Fusion Transformer (2019)
P08: Chronos (2024)
P02: Autoformer (2021)
P10: Moirai (2024)
P03: FEDformer (2022) 
→ {'thai': True, 'older than 2023': ['P01', 'P02', 'P03', 'P09'], 'right papers': '3/6'}

4. Pinned — ปักหมุดข้อความแรกไว้

ตำรา: “Keep the system prompt and first user message pinned” — system prompt ของเราอยู่นอก history อยู่แล้ว จึงปักหมุดข้อความแรกของผู้ใช้ (โจทย์) แล้วใช้ FIFO กับที่เหลือ ด้วยงบที่ลดลง

# ✏️ TODO 2 (▶ วิดีโอ 4:23): เก็บข้อความแรกไว้เสมอ แล้วใช้ fifo กับที่เหลือด้วยงบที่หักข้อความแรกออกแล้ว
def pinned(history, budget):
    first = history[0]
    return [first] + fifo(___, ___)

kept = pinned(HISTORY, BUDGET)
show(kept)
ask("pinned", kept)
def pinned(history, budget):
    first = history[0]
    return [first] + fifo(history[1:], budget - message_tokens(first))

kept = pinned(HISTORY, BUDGET)
show(kept)
ask("pinned", kept)
T · · · · · · · · · · · · a P07 a P09 a s a P08 a P02 a P10 a s a P03 a
kept 18/30 messages, 389 tokens
นี่คือรายการบทความทั้งหมดที่คุณบันทึกไว้ครับ:

P07, TimesFM, 2024
P09, Temporal Fusion Transformer, 2019
P08, Chronos, 2024
P02, Autoformer, 2021
P10, Moirai, 2024
P03, FEDformer, 2022 
→ {'thai': True, 'older than 2023': ['P02', 'P03', 'P09'], 'right papers': '3/6'}

5. Importance-weighted — เก็บแบบ knapsack (สมการ 18.6)

ให้น้ำหนัก wᵢ แต่ละข้อความ (ตำรา: ผล tool และคำแก้ของผู้ใช้ได้น้ำหนักสูง) แล้วเก็บข้อความที่ wᵢ / |mᵢ| สูงก่อน — เหมือนจัดกระเป๋าที่จำกัดน้ำหนัก ใส่ของที่คุ้มต่อน้ำหนักก่อน

ข้อความ w (ที่เราตั้ง)
โจทย์ / แก้โจทย์ (T, C) 10
โน้ตของ paper 4
คำตอบรับของ agent 0.5
คุยเล่น 0.1
def weight(m):
    t = m["content"]
    if m["role"] == "user" and t.startswith(("Task", "Correction")): return 10
    if t.startswith("Paper note"): return 4
    if m["role"] == "assistant": return 0.5
    return 0.1

# ✏️ TODO 3 (▶ วิดีโอ 5:26): เรียงข้อความตาม weight หารด้วยจำนวน token จากมากไปน้อย

def importance(history, budget):
    order = sorted(range(len(history)), key=lambda i: ___, reverse=True)
    keep, used = set(), 0
    for i in order:
        if used + message_tokens(history[i]) <= budget:
            keep.add(i)
            used += message_tokens(history[i])
    return [history[i] for i in sorted(keep)]

kept = importance(HISTORY, BUDGET)
show(kept)
ask("importance", kept)
def weight(m):
    t = m["content"]
    if m["role"] == "user" and t.startswith(("Task", "Correction")): return 10
    if t.startswith("Paper note"): return 4
    if m["role"] == "assistant": return 0.5
    return 0.1

def importance(history, budget):
    order = sorted(range(len(history)), key=lambda i: weight(history[i]) / message_tokens(history[i]), reverse=True)
    keep, used = set(), 0
    for i in order:
        if used + message_tokens(history[i]) <= budget:
            keep.add(i)
            used += message_tokens(history[i])
    return [history[i] for i in sorted(keep)]

kept = importance(HISTORY, BUDGET)
show(kept)
ask("importance", kept)
T · C · P04 · P05 · P06 · · a P01 · · · P09 · · a P08 · P02 · P10 · · · P03 ·
kept 13/30 messages, 399 tokens
นี่คือรายชื่อบทความวิจัยที่ตรงตามเงื่อนไข (ตีพิมพ์ตั้งแต่ปี 2023 เป็นต้นไป) สำหรับการทบทวนวรรณกรรมของคุณครับ:

P04, Are Transformers Effective for Time Series Forecasting?, 2023
P05, PatchTST, 2023
P06, iTransformer, 2024
P08, Chronos, 2024
P10, Moirai, 2024 
→ {'thai': True, 'older than 2023': [], 'right papers': '5/6'}

6. Summarization — สรุปของเก่า (สมการ 18.4)

H′ = Summarize(H₁:ₖ) ‖ Hₖ₊₁:ₙ — สรุปข้อความเก่าเป็นย่อหน้าเดียว แล้วต่อด้วยข้อความล่าสุดที่เก็บไว้ครบ

prompt ของตัวสรุปสั่งให้ เก็บทุกคำสั่งและทุกการแก้ไขของผู้ใช้ และทุก paper พร้อมปี ห้ามเพิ่มอะไรเอง (temperature 0) ตำราบอกว่าใช้ model ที่เล็กกว่า ถูกกว่า มาสรุปก็ได้ — lab นี้ใช้ Gemma ตัวเดิม

SUMMARY_PROMPT = ("Summarize this conversation for the assistant's own memory, in English, in at most 120 words. "
                  "Keep every instruction and correction the user gave, and every paper id with its title and year. "
                  "Copy numbers exactly; add nothing.")

# ✏️ TODO 4 (▶ วิดีโอ 6:36): history ใหม่ = บทสรุป (+ คำตอบรับ) ต่อด้วยข้อความล่าสุดที่เก็บไว้ครบ

def summarize_old(history, keep_last=6):
    old, recent = history[:-keep_last], history[-keep_last:]
    text = "\n".join(f"{m['role']}: {m['content']}" for m in old)
    summary = chat([{"role": "user", "content": SUMMARY_PROMPT + "\n\n" + text}], max_tokens=300, temperature=0)
    print(f"summary: {sum(message_tokens(m) for m in old)} tokens → {count_tokens(summary)} tokens\n{summary}\n")
    return [{"role": "user", "content": "Summary of our earlier conversation: " + summary},
            {"role": "assistant", "content": "รับทราบครับ"}] + ___

kept = summarize_old(HISTORY)
print(sum(message_tokens(m) for m in kept), "tokens, budget", BUDGET)
ask("summary", kept)
SUMMARY_PROMPT = ("Summarize this conversation for the assistant's own memory, in English, in at most 120 words. "
                  "Keep every instruction and correction the user gave, and every paper id with its title and year. "
                  "Copy numbers exactly; add nothing.")

def summarize_old(history, keep_last=6):
    old, recent = history[:-keep_last], history[-keep_last:]
    text = "\n".join(f"{m['role']}: {m['content']}" for m in old)
    summary = chat([{"role": "user", "content": SUMMARY_PROMPT + "\n\n" + text}], max_tokens=300, temperature=0)
    print(f"summary: {sum(message_tokens(m) for m in old)} tokens → {count_tokens(summary)} tokens\n{summary}\n")
    return [{"role": "user", "content": "Summary of our earlier conversation: " + summary},
            {"role": "assistant", "content": "รับทราบครับ"}] + recent

kept = summarize_old(HISTORY)
print(sum(message_tokens(m) for m in kept), "tokens, budget", BUDGET)
ask("summary", kept)
summary: 532 tokens → 156 tokens
The user is writing a literature review on transformers for time series. The assistant must always answer in Thai. The review only covers papers published in 2023 or later; leave older ones out.

Papers noted:
P04: Are Transformers Effective for Time Series Forecasting? (2023)
P05: PatchTST (2023)
P06: iTransformer (2024)
P01: Informer (2021)
P07: TimesFM (2024)
P09: Temporal Fusion Transformer (2019)
P08: Chronos (2024)
P02: Autoformer (2021)

295 tokens, budget 400
นี่คือรายการบทความวิจัยที่ตรงตามเงื่อนไขสำหรับงานรีวิวของคุณ (ตีพิมพ์ตั้งแต่ปี 2023 เป็นต้นไป) ครับ:

P04, Are Transformers Effective for Time Series Forecasting?, 2023
P05, PatchTST, 2023
P06, iTransformer, 2024
P07, TimesFM, 2024
P08, Chronos, 2024
P10, Moirai, 2024 
→ {'thai': True, 'older than 2023': [], 'right papers': '6/6'}
for name, r in RESULTS.items():
    print(f"{name:13} thai={str(r['thai']):5}  older than 2023={str(r['older than 2023']):28} right papers={r['right papers']}")
cost = USAGE["in"] / 1e6 * 0.07 + USAGE["out"] / 1e6 * 0.34
print(f"\nthe whole lab used {USAGE['in']:,} input + {USAGE['out']:,} output tokens ≈ ${cost:.4f}")
full history  thai=True   older than 2023=[]                           right papers=6/6
FIFO          thai=True   older than 2023=['P01', 'P02', 'P03', 'P09'] right papers=3/6
pinned        thai=True   older than 2023=['P02', 'P03', 'P09']        right papers=3/6
importance    thai=True   older than 2023=[]                           right papers=5/6
summary       thai=True   older than 2023=[]                           right papers=6/6

the whole lab used 2,917 input + 707 output tokens ≈ $0.0004

สรุป

วิธี ที่เราเห็นใน lab
FIFO โจทย์และการแก้โจทย์หาย → มี paper เก่าที่ผู้ใช้สั่งตัดออก (บางรอบตอบเป็นอังกฤษ)
Pinned ตอบไทยได้ (โจทย์ถูกปักหมุด) แต่การแก้โจทย์หาย → ยังมี paper เก่า
Importance-weighted คำสั่งอยู่ครบ ไม่มี paper เก่า แต่โน้ตยาวหนึ่งฉบับลงงบไม่ได้ → ได้ 5/6
Summarization ข้อความเก่าสั้นลงกว่า 3 เท่า · ได้ 6/6 เหมือน history ครบ · แลกกับ LLM call เพิ่มหนึ่งครั้ง

แบบฝึกหัด

  1. Hierarchical summarization (§18.2.4): แบ่งข้อความเก่าเป็นสองช่วง ช่วงเก่าสุดสรุปให้เหลือประโยคเดียว ช่วงกลางสรุปเป็นย่อหน้า ส่วนข้อความล่าสุดเก็บครบ — ลงงบ 300 token ได้ไหม และยังได้ 6/6 ไหม
  2. ใน weight ให้คุยเล่นได้ 4 เท่ากับโน้ตของ paper แล้วรัน importance อีกครั้ง — อะไรหายไปแทน

ถัดไป — Lab 3: เมื่อเอกสารใหญ่กว่างบตั้งแต่แรก — แบ่งเป็นชิ้น เรียก model ซ้ำทีละชิ้น แล้วรวมผล (recursive context decomposition)