Skip to main content

Lab 1 — นับก่อนส่ง

Lab walkthrough · EP07 Context Window Management

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

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

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

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

จากคลิปทฤษฎี: context window มีขนาดจำกัด (C) และห้าส่วนแย่งพื้นที่กัน — C ≥ S + M + T + H + R (สมการ 18.1) ถ้าส่งเกิน API อาจตัดบางส่วนทิ้ง โดยไม่มี error (silent truncation)

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

  1. นับ token ด้วย tokenizer ของ Gemma เอง เทียบกับกฎ “4 ตัวอักษร ≈ 1 token”
  2. ประกอบ prompt จาก block (สมการ 18.8) แล้วนับ token ทีละ block — นับตรงกับที่ API นับไหม
  3. pre-flight check: เทียบกับ C − R ก่อนส่งทุกครั้ง
  4. ส่ง prompt ที่ยาวเกิน context ไปจริงๆ — ครั้งแรกได้ error ครั้งที่สองไม่มี error เลย

paper ในบทสนทนายาวเป็น ข้อมูลจำลองที่สร้างขึ้นเพื่อการสอน ส่วนตัวเลข token, error และคำตอบของ model ทั้งหมดมาจากการรันจริง

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

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ราว 1–2 เซ็นต์ดอลลาร์)
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. เรียก Gemma ผ่าน OpenRouter

ทำไมใช้ google/gemma-4-26b-a4b-it — ทำตามคำสั่งภาษาไทยได้ดี, tokenizer เปิดให้โหลด (นับ token บนเครื่องเราได้ตรงกับที่ model นับ) และเรียก tool ได้ ซึ่ง Lab 4 ต้องใช้

ทำไมล็อก provider เป็น DeepInfra — เจ้าเดียวกับ EP03 และ EP06 · รับ context ได้ 262,144 token (ตัวเลข C ของ lab นี้) provider แต่ละเจ้ารับ context ไม่เท่ากัน (บางเจ้า 131,072) ถ้าไม่ล็อก C ก็เปลี่ยนไปทุกครั้งที่ OpenRouter สลับเจ้า

ไม่ฟรี แต่ถูกมาก: DeepInfra คิด 0.07 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.34 ต่อล้าน token ขาออก — ท้าย lab เราจะรวม token ที่ใช้จริงให้ดู · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-16: 3 ใน 3 ครั้งได้ 429 “rate-limited upstream”)

import json, os, random
from openai import OpenAI, BadRequestError

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"
PROVIDER = {"order": ["deepinfra/fp8"], "allow_fallbacks": False}
EXTRA = {"reasoning": {"enabled": False}, "provider": PROVIDER}

USAGE = {"in": 0, "out": 0}

def chat(messages, **kw):
    reply = client.chat.completions.create(model=MODEL, messages=messages, max_tokens=300, extra_body=EXTRA | kw)
    USAGE["in"] += reply.usage.prompt_tokens
    USAGE["out"] += reply.usage.completion_tokens
    return reply

2. นับ token ด้วย tokenizer ของ Gemma เอง

ตำรา (§18.2.6): นับด้วย tokenizer ของ model ตัวนั้น ไม่ใช่นับคำหรือหารความยาวด้วย 4 — กฎ “4 ตัวอักษรต่อ token” เพี้ยนได้ 20–40% กับโค้ด, JSON และภาษาที่ไม่ใช่อังกฤษ

ใน EP01 เราใช้ tiktoken ของ OpenAI ดูภาพรวม คราวนี้ใช้ tokenizer ของ Gemma จริงๆ (โหลดครั้งแรกราว 30 MB)

os.environ["HF_HUB_VERBOSITY"] = "error"  # hide the "no HF_TOKEN" notice: the tokenizer is public
from tokenizers import Tokenizer

tok = Tokenizer.from_pretrained(MODEL)
print("vocabulary:", f"{tok.get_vocab_size():,}", "pieces")

# ✏️ TODO 1 (▶ วิดีโอ 3:04): นับ token ของ text ด้วย tokenizer ของ Gemma (ไม่ใส่ token พิเศษ)

def count_tokens(text):
    return len(___)
os.environ["HF_HUB_VERBOSITY"] = "error"  # hide the "no HF_TOKEN" notice: the tokenizer is public
from tokenizers import Tokenizer

tok = Tokenizer.from_pretrained(MODEL)
print("vocabulary:", f"{tok.get_vocab_size():,}", "pieces")

def count_tokens(text):
    return len(tok.encode(text, add_special_tokens=False).ids)
vocabulary: 262,144 pieces
SAMPLES = {
    "English": "The context window is the agent's working memory. Every token in the window costs money and latency; every token not in the window is invisible to the model.",
    "Thai": "ช่วยสรุปงานวิจัยเรื่องการพยากรณ์ข้อมูลอนุกรมเวลาด้วยทรานส์ฟอร์มเมอร์ให้หน่อยครับ อยากได้สามย่อหน้า",
    "Python": 'for i, msg in enumerate(history):\n    if msg["role"] == "tool":\n        weights[i] = 4\n',
    "JSON": json.dumps({"id": "P07", "title": "PatchTST", "year": 2023, "scores": [0.412, 0.387, 0.355]}),
}

for kind, text in SAMPLES.items():
    real, guess = count_tokens(text), len(text) / 4
    print(f"{kind:8} {len(text):4} chars → Gemma {real:3} tokens · 4-chars rule {guess:5.0f} ({(guess - real) / real:+.0%})")
English   157 chars → Gemma  33 tokens · 4-chars rule    39 (+19%)
Thai       98 chars → Gemma  36 tokens · 4-chars rule    24 (-32%)
Python     87 chars → Gemma  30 tokens · 4-chars rule    22 (-28%)
JSON       81 chars → Gemma  48 tokens · 4-chars rule    20 (-58%)

3. ประกอบ prompt จาก block (สมการ 18.8)

Prompt = Concat(SystemBlock, MemoryBlock, ToolBlock, HistoryBlock, QueryBlock)

  • System — template สี่หัวข้อตาม §18.3.1: Identity · Capabilities · Constraints · Output Format
  • Memory — สิ่งที่ harness จำไว้ให้ (lab นี้เขียนไว้ตายตัว — เรื่องความจำมีใน EP12)
  • Tools — คำอธิบาย tool (เขียนแบบ EP06 Lab 1)
  • History และ Query — บทสนทนาที่ผ่านมา และคำถามล่าสุด

แต่ละ block เป็นตัวแปรของมันเอง เปลี่ยนก้อนหนึ่งได้โดยไม่แตะก้อนอื่น

SYSTEM_TEMPLATE = """# Identity
You are {agent_name}, a research assistant built by Cogito Learn. Today's date is {date}.
# Capabilities
You can use these tools: {tool_list}.
# Constraints
- Never invent a paper. Cite the paper id for every claim.
# Output Format
Answer in Thai, in at most three short paragraphs."""

MEMORY = "Known about the user: master's student; writing a literature review on transformers for time series."
TOOLS = ("search_papers(query, year_from): search the paper library by topic; returns [{id, title, year}]. "
         "Use for any question about papers. Do NOT use for questions about the user.")
HISTORY = [
    {"role": "user", "content": "Which papers have I already read?"},
    {"role": "assistant", "content": "So far: Informer (P01) and PatchTST (P05)."},
]
QUERY = "What should I read next, and why?"

# ✏️ TODO 2 (▶ วิดีโอ 4:56): ต่อ block ตามลำดับสมการ 18.8: system message → history → คำถาม

def assemble(system, memory, tools, history, query):
    system_text = f"{system}\n\n# Memory\n{memory}\n\n# Tools\n{tools}"
    return ___

SYSTEM = SYSTEM_TEMPLATE.format(agent_name="Cogito", date="2026-11-16", tool_list="search_papers")
messages = assemble(SYSTEM, MEMORY, TOOLS, HISTORY, QUERY)
print(messages[0]["content"])
SYSTEM_TEMPLATE = """# Identity
You are {agent_name}, a research assistant built by Cogito Learn. Today's date is {date}.
# Capabilities
You can use these tools: {tool_list}.
# Constraints
- Never invent a paper. Cite the paper id for every claim.
# Output Format
Answer in Thai, in at most three short paragraphs."""

MEMORY = "Known about the user: master's student; writing a literature review on transformers for time series."
TOOLS = ("search_papers(query, year_from): search the paper library by topic; returns [{id, title, year}]. "
         "Use for any question about papers. Do NOT use for questions about the user.")
HISTORY = [
    {"role": "user", "content": "Which papers have I already read?"},
    {"role": "assistant", "content": "So far: Informer (P01) and PatchTST (P05)."},
]
QUERY = "What should I read next, and why?"

def assemble(system, memory, tools, history, query):
    system_text = f"{system}\n\n# Memory\n{memory}\n\n# Tools\n{tools}"
    return [{"role": "system", "content": system_text}] + history + [{"role": "user", "content": query}]

SYSTEM = SYSTEM_TEMPLATE.format(agent_name="Cogito", date="2026-11-16", tool_list="search_papers")
messages = assemble(SYSTEM, MEMORY, TOOLS, HISTORY, QUERY)
print(messages[0]["content"])
# Identity
You are Cogito, a research assistant built by Cogito Learn. Today's date is 2026-11-16.
# Capabilities
You can use these tools: search_papers.
# Constraints
- Never invent a paper. Cite the paper id for every claim.
# Output Format
Answer in Thai, in at most three short paragraphs.

# Memory
Known about the user: master's student; writing a literature review on transformers for time series.

# Tools
search_papers(query, year_from): search the paper library by topic; returns [{id, title, year}]. Use for any question about papers. Do NOT use for questions about the user.

นับให้ตรงกับที่ API นับ

API ไม่ได้นับแค่ข้อความ — ทุก message ถูกห่อด้วยรูปแบบแชทของ Gemma (<|turn>user … <turn|>) และท้ายสุดมีหัวของคำตอบ <|turn>model ที่ model จะเขียนต่อ เราจึงนับทีละ message ในรูปแบบเดียวกัน

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

REPLY_HEADER = count_tokens("<bos><|turn>model\n<|channel>thought\n<channel|>")

def count_messages(messages):
    return sum(message_tokens(m) for m in messages) + REPLY_HEADER

sent = count_messages(messages)
reply = chat(messages)
print("we counted:", sent, "· the API counted:", reply.usage.prompt_tokens)
print(reply.choices[0].message.content)
we counted: 214 · the API counted: 215
เนื่องจากคุณได้อ่าน Informer ซึ่งเน้นการใช้ ProbSparse Attention และ PatchTST ที่ใช้การแบ่งข้อมูลเป็น Patch ไปแล้ว ขั้นตอนต่อไปที่ควรศึกษาคือกลุ่มโมเดลที่เน้นความสามารถในการเรียนรู้ความสัมพันธ์ระยะยาว (Long-term dependency) และการจัดการกับความซับซ้อนของข้อมูลที่หลากหลายขึ้น

ฉันขอแนะนำให้คุณอ่าน **Autoformer** เพื่อทำความเข้าใจกลไก Decomposition-based architecture ที่ช่วยแยกแยะแนวโน้ม (Trend) และฤดูกาล (Seasonality) ออกจากกัน ซึ่งเป็นพื้นฐานสำคัญในการทำ Time series forecasting นอกจากนี้ การศึกษา **FEDformer** จะช่วยให้คุณเห็นภาพการใช้ Frequency domain (Fourier Transform) ในการจัดการข้อมูล ซึ่งเป็นอีกหนึ่งแนวทางที่ทรงพลังนอกเหนือจาก Time domain แบบเดิม

การอ่านทั้งสองเล่มนี้จะช่วยให้งาน Literature Review ของคุณครอบคลุมทั้งมิติของการจัดการโครงสร้างข้อมูล (Decomposition) และมิติของการเปลี่ยนผ่านโดเมน (Frequency domain) ทำให้ภาพรวมของวิวัฒนาการ Transformer ในงาน Time series สมบูรณ์ยิ่งขึ้นครับ

4. Pre-flight check (§18.2.6)

ก่อนเรียก LLM ทุกครั้ง:

  1. นับ token ของ prompt ที่ประกอบเสร็จ ด้วย tokenizer ของ model
  2. เทียบกับ C − R (ขนาด context − ที่เว้นไว้ให้ตอบ)
  3. ถ้าเกิน: บีบ ตัด หรือ หยุดพร้อม error ที่ชัดเจน
  4. log จำนวน token แยกทีละส่วน

งบตายตัวตามตำรา (สมการ 18.2): S 10% · M 20% · T 10% · H 50% · R 10% ของ C

C = 262_144          # DeepInfra's context for this model
SHARE = {"S system": 0.10, "M memory": 0.20, "T tools": 0.10, "H history+query": 0.50, "R reserved": 0.10}
R = int(SHARE["R reserved"] * C)

class ContextOverflow(Exception):
    pass

def preflight(system, memory, tools, history, query):
    parts = {"S system": count_tokens(system), "M memory": count_tokens(memory), "T tools": count_tokens(tools),
             "H history+query": sum(message_tokens(m) for m in history) + count_tokens(query)}
    messages = assemble(system, memory, tools, history, query)
    total = count_messages(messages)
    for name, n in parts.items():
        print(f"  {name:16} {n:>8,} tokens ({n / C:6.2%} of C, budget {SHARE[name]:.0%})")
    print(f"  {'total':16} {total:>8,} / limit C - R = {C - R:,}")
    # ✏️ TODO 3 (▶ วิดีโอ 6:54): ถ้า total เกิน C − R ให้ raise ContextOverflow ที่บอกจำนวน token และ limit
    if ___:
        raise ___
    return messages

preflight(SYSTEM, MEMORY, TOOLS, HISTORY, QUERY);
C = 262_144          # DeepInfra's context for this model
SHARE = {"S system": 0.10, "M memory": 0.20, "T tools": 0.10, "H history+query": 0.50, "R reserved": 0.10}
R = int(SHARE["R reserved"] * C)

class ContextOverflow(Exception):
    pass

def preflight(system, memory, tools, history, query):
    parts = {"S system": count_tokens(system), "M memory": count_tokens(memory), "T tools": count_tokens(tools),
             "H history+query": sum(message_tokens(m) for m in history) + count_tokens(query)}
    messages = assemble(system, memory, tools, history, query)
    total = count_messages(messages)
    for name, n in parts.items():
        print(f"  {name:16} {n:>8,} tokens ({n / C:6.2%} of C, budget {SHARE[name]:.0%})")
    print(f"  {'total':16} {total:>8,} / limit C - R = {C - R:,}")
    if total > C - R:
        raise ContextOverflow(f"prompt is {total:,} tokens, limit is {C - R:,}: compress the history before sending")
    return messages

preflight(SYSTEM, MEMORY, TOOLS, HISTORY, QUERY);
  S system               82 tokens ( 0.03% of C, budget 10%)
  M memory               20 tokens ( 0.01% of C, budget 20%)
  T tools                42 tokens ( 0.02% of C, budget 10%)
  H history+query        44 tokens ( 0.02% of C, budget 50%)
  total                 214 / limit C - R = 235,930

5. บทสนทนาที่ยาวเกิน context

ผู้ใช้แปะ paper ทีละฉบับให้ research assistant (paper จำลอง ที่สุ่มสร้างขึ้น) และ ตรงกลางบทสนทนา บอกเรื่องหนึ่งไว้: กำหนดส่งรีวิวและชื่ออาจารย์ที่ปรึกษา — แล้วข้อความสุดท้ายถามเรื่องนั้น

เราจะลองสามแบบ: ① ผ่าน pre-flight ② ส่งตรงๆ ③ ส่งแบบให้ OpenRouter ตัดส่วนกลางทิ้งให้ (middle-out)

random.seed(7)
TOPICS = ["forecasting", "anomaly detection", "imputation", "classification", "traffic", "energy load", "weather", "finance"]
METHODS = ["patching", "sparse attention", "frequency decomposition", "channel independence", "state space layers", "diffusion"]

def fake_paper(k):  # simulated data for teaching: ~590 tokens per paper
    t, m = random.choice(TOPICS), random.choice(METHODS)
    lines = [f"Paper {k}: A study of {m} for time-series {t}."]
    for j in range(14):
        lines.append(f"In experiment {j + 1}, the {m} variant reached an error of {random.uniform(0.1, 0.9):.3f} "
                     f"against a baseline of {random.uniform(0.2, 1.0):.3f}, using a window of {random.choice([96, 192, 336, 512])} points.")
    return " ".join(lines)
LONG = [{"role": "user", "content": "I'll paste papers one by one; just reply 'noted'."},
        {"role": "assistant", "content": "noted"}]
for k in range(1, 461):
    LONG += [{"role": "user", "content": fake_paper(k)}, {"role": "assistant", "content": "noted"}]
    if k == 230:  # the middle of the conversation
        LONG += [{"role": "user", "content": "Side note: my review is due on 12 December and my advisor is Dr. Kanya."},
                 {"role": "assistant", "content": "noted"}]
ASK = "When is my review due, and who is my advisor?"
print(len(LONG), "messages")
924 messages
try:
    preflight(SYSTEM, MEMORY, TOOLS, LONG, ASK)
except ContextOverflow as e:
    print("🛑 pre-flight:", e)
  S system               82 tokens ( 0.03% of C, budget 10%)
  M memory               20 tokens ( 0.01% of C, budget 20%)
  T tools                42 tokens ( 0.02% of C, budget 10%)
  H history+query   270,557 tokens (103.21% of C, budget 50%)
  total             270,727 / limit C - R = 235,930
🛑 pre-flight: prompt is 270,727 tokens, limit is 235,930: compress the history before sending
big = assemble(SYSTEM, MEMORY, TOOLS, LONG, ASK)
print("we would send:", f"{count_messages(big):,}", "tokens")
try:
    chat(big)
except BadRequestError as e:
    print("❌", json.loads(e.body["metadata"]["raw"])["error"]["message"])
we would send: 270,727 tokens
❌ Input too long: 270728 input tokens, limit is 262144 for this model
reply = chat(big, transforms=["middle-out"])
print("we sent:", f"{count_messages(big):,}", "· the model saw:", f"{reply.usage.prompt_tokens:,}")
print(reply.choices[0].message.content)
we sent: 270,727 · the model saw: 174,387
ขออภัยครับ ผมไม่สามารถทราบข้อมูลส่วนตัวของคุณ เช่น วันกำหนดส่งบทวิจารณ์ (literature review) หรือชื่ออาจารย์ที่ปรึกษาของคุณได้ เนื่องจากข้อมูลเหล่านี้ไม่ได้ถูกระบุไว้ในบริบทการสนทนาของเราครับ
# ✏️ TODO 4 (▶ วิดีโอ 9:58): เตือนเมื่อ model เห็น token น้อยกว่าที่ส่ง (เผื่อ 5 token)
def check_seen(sent, reply):
    seen = ___
    if ___:
        print(f"⚠️ silent truncation: sent {sent:,} tokens, the model saw {seen:,} ({sent - seen:,} dropped)")

check_seen(count_messages(big), reply)
def check_seen(sent, reply):
    seen = reply.usage.prompt_tokens
    if seen < sent - 5:
        print(f"⚠️ silent truncation: sent {sent:,} tokens, the model saw {seen:,} ({sent - seen:,} dropped)")

check_seen(count_messages(big), reply)
⚠️ silent truncation: sent 270,727 tokens, the model saw 174,387 (96,340 dropped)
cost = USAGE["in"] / 1e6 * 0.07 + USAGE["out"] / 1e6 * 0.34
print(f"the whole lab used {USAGE['in']:,} input tokens + {USAGE['out']:,} output tokens ≈ ${cost:.4f}")
the whole lab used 174,602 input tokens + 283 output tokens ≈ $0.0123

สรุป

สิ่งที่ทำ ที่เราเห็นใน lab
นับด้วย tokenizer ของ model กฎ 4 ตัวอักษรเดาเกินกับภาษาอังกฤษ แต่เดาขาดกับภาษาไทย โค้ด และ JSON (JSON ขาดไปเกินครึ่ง)
ประกอบ prompt จาก block นับทีละ message ในรูปแบบแชทของ Gemma → ตรงกับ usage.prompt_tokens ไม่เกิน 1 token
pre-flight check บทสนทนายาวถูกหยุดก่อนส่ง พร้อม log ว่า history กินเกินงบ
ส่งตรงๆ DeepInfra ปฏิเสธ: 400 “Input too long”
middle-out ไม่มี error · model เห็นแค่ ~175K จาก ~271K token · ข้อความตรงกลางหาย → ตอบว่าไม่มีข้อมูล

แบบฝึกหัด

  1. ย้ายข้อความ “Side note” ไปไว้หลัง paper ฉบับที่ 3 (ต้นบทสนทนา) แล้วรันแบบที่สามอีกครั้ง — model ตอบได้ไหม เพราะอะไร
  2. เพิ่ม preflight ให้บอกด้วยว่าต้องตัด history ออกอย่างน้อยกี่ token ถึงจะผ่าน

ถัดไป — Lab 2: เมื่อ history ล้นหน้าต่าง — เทียบ FIFO, การปักหมุด, การสรุป และการให้น้ำหนักความสำคัญ