Skip to main content

Lab 2 — บันทึก checkpoint แล้วทำต่อจากจุดเดิม

Lab walkthrough · EP08 Tools, State and Error Handling

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

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

▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP08 Tools, State and Error Handling

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

จากคลิปทฤษฎี: state ของงาน (task state) มี progress, checkpoint และ rollback (§18.6.2) และตำราเตือนให้ออกแบบ state เหมือนตารางฐานข้อมูล: มีโครงสร้างชัด มีเวอร์ชัน

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

  1. เขียน state ของงานเป็น dataclass ที่มีโครงสร้างและเลขเวอร์ชัน
  2. งานหกขั้น (เรียก model ขั้นละครั้ง) ที่เน็ตหลุดตอนขั้นที่ 4
  3. ไม่มี checkpoint: เริ่มใหม่ทั้งหมด · มี checkpoint: ทำต่อจากขั้นที่ 4 — นับจำนวนครั้งที่เรียก model
  4. บันทึกไฟล์อย่างปลอดภัย (os.replace) และ rollback ย้อน k ขั้นล่าสุด

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

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

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key ใช้ key เดียวกับ Lab 1 (lab นี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์)
Packages openai, python-dotenv

วิธีใส่ key และเหตุผลที่เลือก model กับ provider อยู่ใน Lab 1

%pip install -q "openai>=1.50" python-dotenv
import json, os
from dataclasses import dataclass, field, asdict
from openai import OpenAI

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": ["makora"], "allow_fallbacks": False}}

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

def chat(messages, **kw):
    reply = client.chat.completions.create(model=MODEL, messages=messages, extra_body=EXTRA, **kw)
    USAGE["calls"] += 1
    USAGE["in"] += reply.usage.prompt_tokens
    USAGE["out"] += reply.usage.completion_tokens
    return reply.choices[0].message
PAPERS = {
    "P1": "Informer (2021): ProbSparse self-attention makes long-sequence time-series forecasting faster.",
    "P2": "PatchTST (2023): splits each series into patches of 16 steps; each channel is handled on its own.",
    "P3": "TimesFM (2024): a decoder-only foundation model that forecasts new series zero-shot.",
}

1. state ของงาน: มีโครงสร้าง มีเวอร์ชัน

ช่อง ชั้นของ state ในตำรา
task, steps แผนงาน (agent state: current plan)
results ความคืบหน้า — ขั้นไหนเสร็จแล้ว ได้ผลอะไร (task state: progress)
version เวอร์ชันของโครงสร้าง (“state as a first-class citizen”)
STATE_VERSION = 1

@dataclass
class TaskState:
    task: str
    steps: list                                   # the plan: [name, prompt template]
    results: dict = field(default_factory=dict)   # progress: step name → output
    version: int = STATE_VERSION
STEPS = [
    ["note_P1", "In one sentence, what is the key idea of this paper? {P1}"],
    ["note_P2", "In one sentence, what is the key idea of this paper? {P2}"],
    ["note_P3", "In one sentence, what is the key idea of this paper? {P3}"],
    ["compare", "Compare three papers in 3 short bullet points, using these notes:\n{note_P1}\n{note_P2}\n{note_P3}"],
    ["title",   "Write one title for a 2-page report built on this comparison. Reply with the title only.\n{compare}"],
    ["report",  "Write the report's opening paragraph, under 80 words.\nTitle: {title}\nComparison:\n{compare}"],
]
NETWORK = {"drop_at": None}

def run_step(state, name, template):
    if name == NETWORK["drop_at"]:
        NETWORK["drop_at"] = None          # drops once, then works again
        raise ConnectionError(f"network dropped at step '{name}'")
    prompt = template.format(**PAPERS, **state.results)
    return chat([{"role": "user", "content": prompt}], max_tokens=250).content

2. ไม่มี checkpoint: พังแล้วเริ่มใหม่

# ✏️ TODO 1 (▶ วิดีโอ 2:20): ข้ามขั้นที่มีผลอยู่ใน state.results แล้ว
def run_task(state, path=None):
    for name, template in state.steps:
        if ___:
            continue                       # done before: skip it
        state.results[name] = run_step(state, name, template)
        print(f"  ✓ {name}")
        if path:
            save_state(state, path)      # checkpoint after every step
    return state
def run_task(state, path=None):
    for name, template in state.steps:
        if name in state.results:
            continue                       # done before: skip it
        state.results[name] = run_step(state, name, template)
        print(f"  ✓ {name}")
        if path:
            save_state(state, path)      # checkpoint after every step
    return state
USAGE["calls"] = 0
NETWORK["drop_at"] = "compare"
state = TaskState(task="2-page report on transformers for time series", steps=STEPS)
try:
    run_task(state)
except ConnectionError as e:
    print("💥", e)

state = TaskState(task="2-page report on transformers for time series", steps=STEPS)
run_task(state)
print(f"model calls: {USAGE['calls']}")
  ✓ note_P1
  ✓ note_P2
  ✓ note_P3
💥 network dropped at step 'compare'
  ✓ note_P1
  ✓ note_P2
  ✓ note_P3
  ✓ compare
  ✓ title
  ✓ report
model calls: 9

3. บันทึก checkpoint ทุกขั้น

checkpoint = ภาพ state ที่บันทึกลงไฟล์ (§18.6.2) · เขียนลงไฟล์ชั่วคราวก่อน แล้ว os.replace ทับไฟล์จริงในครั้งเดียว ถ้าโปรแกรมล่ม ระหว่างเขียน ไฟล์ checkpoint เดิมก็ยังอยู่ครบ ไม่ใช่ไฟล์ที่เขียนค้างครึ่งๆ

# ✏️ TODO 2 (▶ วิดีโอ 3:08): เขียนลงไฟล์ชั่วคราวแล้ว ย้ายทับไฟล์จริงในครั้งเดียว
def save_state(state, path):
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        json.dump(asdict(state), f, indent=1)
    ___                  # one atomic move: never a half-written file

# ✏️ TODO 3 (▶ วิดีโอ 3:28): สร้าง TaskState จาก dict ที่อ่านมา

def load_state(path):
    with open(path) as f:
        data = json.load(f)
    if data.get("version") != STATE_VERSION:
        raise ValueError(f"checkpoint version {data.get('version')} ≠ {STATE_VERSION}: migrate it first")
    return ___
def save_state(state, path):
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        json.dump(asdict(state), f, indent=1)
    os.replace(tmp, path)                  # one atomic move: never a half-written file

def load_state(path):
    with open(path) as f:
        data = json.load(f)
    if data.get("version") != STATE_VERSION:
        raise ValueError(f"checkpoint version {data.get('version')} ≠ {STATE_VERSION}: migrate it first")
    return TaskState(**data)
USAGE["calls"] = 0
NETWORK["drop_at"] = "compare"
CKPT = "report_task.json"
state = TaskState(task="2-page report on transformers for time series", steps=STEPS)
try:
    run_task(state, CKPT)
except ConnectionError as e:
    print("💥", e)
  ✓ note_P1
  ✓ note_P2
  ✓ note_P3
💥 network dropped at step 'compare'
# ✏️ TODO 4 (▶ วิดีโอ 3:56): โหลด state จาก checkpoint แทนการสร้างใหม่
state = ___
print("done before the crash:", list(state.results))
run_task(state, CKPT)
print(f"model calls: {USAGE['calls']}")
state = load_state(CKPT)
print("done before the crash:", list(state.results))
run_task(state, CKPT)
print(f"model calls: {USAGE['calls']}")
done before the crash: ['note_P1', 'note_P2', 'note_P3']
  ✓ compare
  ✓ title
  ✓ report
model calls: 6
saved = json.load(open(CKPT))
print("keys:", list(saved), "· version", saved["version"])
for name, out in saved["results"].items():
    print(f"  {name:8} {out[:70]!r}…")
keys: ['task', 'steps', 'results', 'version'] · version 1
  note_P1  'The Informer introduces a ProbSparse self-attention mechanism to reduc'…
  note_P2  'PatchTST improves long-term time series forecasting by decomposing ind'…
  note_P3  'TimesFM is a decoder-only foundation model trained on massive datasets'…
  compare  'Here is a comparison of the three papers:\n\n* **Informer** focuses on a'…
  title    'Comparative Analysis of Informer, PatchTST, and TimesFM Architectures '…
  report   'This report provides a comparative analysis of three pivotal architect'…
print(state.results["title"], "\n")
print(state.results["report"])
Comparative Analysis of Informer, PatchTST, and TimesFM Architectures in Time-Series Forecasting 

This report provides a comparative analysis of three pivotal architectures in time-series forecasting: Informer, PatchTST, and TimesFM. While Informer optimizes long-sequence efficiency through ProbSparse self-attention, PatchTST enhances feature extraction via local patching and channel independence. In contrast, TimesFM leverages a decoder-only foundation model approach for superior zero-shot performance. By evaluating these distinct methodologies, this study highlights how advancements in complexity reduction, local pattern recognition, and large-scale pre-training shape the current forecasting landscape.

4. Rollback: ย้อน k ขั้นล่าสุด

ตำรา §18.6.2: ย้อนการกระทำล่าสุดได้ เมื่อพบว่าผิด — ตัวอย่างนี้: ย่อหน้าเปิดยากไปสำหรับนักศึกษาปีหนึ่ง ย้อนสองขั้นสุดท้าย (title, report) แก้แผน แล้วทำเฉพาะสองขั้นนั้นใหม่

# ✏️ TODO 5 (▶ วิดีโอ 4:51): ลบผลของ k ขั้นล่าสุดออกจาก state.results
def rollback(state, k):
    for name in ___:
        del state.results[name]
    return state
def rollback(state, k):
    for name in list(state.results)[-k:]:
        del state.results[name]
    return state
USAGE["calls"] = 0
state = rollback(load_state(CKPT), 2)
state.steps[5][1] = "Write the report's opening paragraph for first-year students, under 60 words, no jargon.\nTitle: {title}\nComparison:\n{compare}"
run_task(state, CKPT)
print(f"model calls: {USAGE['calls']}\n\n{state.results['report']}")
  ✓ title
  ✓ report
model calls: 2

This report compares three different ways to predict future trends using time-series data. We examine the **Informer** model, which focuses on speed; **PatchTST**, which improves how data patterns are identified; and **TimesFM**, a large-scale model designed to make accurate predictions even on new, unseen data.
cost = USAGE["in"] / 1e6 * 0.09 + USAGE["out"] / 1e6 * 0.28
print(f"the whole lab used {USAGE['in']:,} input tokens + {USAGE['out']:,} output tokens ≈ ${cost:.4f}")
the whole lab used 1,613 input tokens + 888 output tokens ≈ $0.0004

สรุป

สิ่งที่ทำ ที่เราเห็นใน lab
state เป็น dataclass + เวอร์ชัน ทุกช่องมีชื่อชัด · load_state ไม่ยอมอ่านไฟล์ที่เวอร์ชันไม่ตรง
ไม่มี checkpoint เน็ตหลุดที่ขั้น 4 → เริ่มใหม่ทั้งหมด · เรียก model 9 ครั้งสำหรับงาน 6 ขั้น
checkpoint ทุกขั้น ทำต่อจากขั้น 4 · เรียก model 6 ครั้งพอดี
os.replace ไฟล์ checkpoint ไม่มีวันถูกเขียนค้างครึ่งๆ
rollback 2 ขั้น แก้ย่อหน้าเปิดโดยเรียก model แค่ 2 ครั้ง

แบบฝึกหัด

  1. เพิ่มช่อง beliefs: dict (สิ่งที่ agent รู้แล้ว เช่น {"audience": "first-year"}) ให้ TaskState แล้วเพิ่ม STATE_VERSION เป็น 2 — โหลด report_task.json เดิมได้ไหม เขียนฟังก์ชัน migrate ที่แปลงไฟล์เวอร์ชัน 1 เป็น 2
  2. ให้เน็ตหลุดที่ขั้น report (ขั้นสุดท้าย) แทน — ประหยัดการเรียก model ได้กี่ครั้ง

ถัดไป — Lab 3: เมื่อทุกอย่างพัง — backoff + jitter, fallback model และจับ agent ที่วนซ้ำ