Lab 5 — checkpoint ด้วย LangGraph
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 ที่คุณรันเองจึงอาจต่างจากหน้านี้
Lab 2 เราเขียน state, checkpoint, การทำต่อ และ rollback เอง — lab นี้ทำ งานหกขั้นเดิม ด้วย LangGraph ใน EP05 Lab 5 เราใช้ InMemorySaver หยุดรอคนอนุมัติ — คราวนี้ใช้ SqliteSaver ที่เก็บลง ไฟล์ จึงอยู่รอดแม้โปรแกรมปิดไป
| Lab 2 (เขียนเอง) | LangGraph |
|---|---|
TaskState (dataclass) |
State (TypedDict) + reducer |
run_task วนตามแผน ข้ามขั้นที่เสร็จ |
graph ของ node ต่อกัน · graph รู้เองว่า node ถัดไปคืออะไร |
save_state หลังทุกขั้น (os.replace) |
checkpointer บันทึกหลังทุก node (ลง SQLite) |
load_state(CKPT) แล้ว run_task |
invoke(None, config) ด้วย thread_id เดิม |
rollback(state, 2) |
get_state_history + update_state → แตกกิ่งใหม่ |
version |
ไม่มีให้ — schema ของ state เรายังต้องดูแลเอง |
paper และเน็ตที่หลุด เป็น ข้อมูลจำลองเพื่อการสอน ส่วนคำตอบของ model และจำนวน checkpoint มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §18.6, §18.9 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | ใช้ key เดียวกับ Lab 1 (lab นี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์) |
| Packages | langgraph, langgraph-checkpoint, langgraph-checkpoint-sqlite (ล็อกเวอร์ชัน), openai, python-dotenv |
วิธีใส่ key และเหตุผลที่เลือก model กับ provider อยู่ใน Lab 1
%pip install -q "langgraph==1.2.16" "langgraph-checkpoint==4.3.1" "langgraph-checkpoint-sqlite==3.1.3" "openai>=1.50" python-dotenvimport operator, os, sqlite3
from typing import Annotated, TypedDict
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}
def chat(prompt):
USAGE["calls"] += 1
reply = client.chat.completions.create(model=MODEL, max_tokens=250, extra_body=EXTRA,
messages=[{"role": "user", "content": prompt}])
return reply.choices[0].message.content
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 และ node หกตัว
results ใช้ reducer operator.or_ — node แต่ละตัวคืนแค่ผลของตัวเอง แล้ว LangGraph รวมเข้า dict เดิม (a | b) audience = ผู้อ่านรายงาน ซึ่งเราจะเปลี่ยนตอน rollback
# ✏️ TODO 1 (▶ วิดีโอ 1:19): บอก LangGraph ให้รวม dict ของ results ด้วย operator.or_
class State(TypedDict):
audience: str
results: ___ # each node's output is merged inclass State(TypedDict):
audience: str
results: Annotated[dict, operator.or_] # each node's output is merged inSTEPS = [
["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 for {audience}, built on this comparison. Reply with the title only.\n{compare}"],
["report", "Write the report's opening paragraph for {audience}, under 80 words.\nTitle: {title}\nComparison:\n{compare}"],
]
NETWORK = {"drop_at": None}def make_node(name, template):
def node(state):
if NETWORK["drop_at"] == name:
NETWORK["drop_at"] = None
raise ConnectionError(f"network dropped at step '{name}'")
print(f" ✓ {name}")
prompt = template.format(**PAPERS, audience=state["audience"], **state["results"])
return {"results": {name: chat(prompt)}}
return node2. Graph ต่อกันเป็นเส้นตรง + SqliteSaver
checkpointer บันทึก state หลังทุก node ลงไฟล์ report.db — แต่ละงานแยกกันด้วย thread_id
# ✏️ TODO 2 (▶ วิดีโอ 2:15): ต่อเส้นจาก node ก่อนหน้ามาหา node นี้
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
builder = StateGraph(State)
previous = START
for name, template in STEPS:
builder.add_node(name, make_node(name, template))
___
previous = name
builder.add_edge(previous, END)
# ✏️ TODO 3 (▶ วิดีโอ 2:32): compile โดยใส่ checkpointer ที่เป็น SqliteSaver ต่อกับไฟล์ DB
DB = "report.db"
if os.path.exists(DB):
os.remove(DB)
graph = builder.compile(checkpointer=___)
print(" → ".join(graph.get_graph().nodes))from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
builder = StateGraph(State)
previous = START
for name, template in STEPS:
builder.add_node(name, make_node(name, template))
builder.add_edge(previous, name)
previous = name
builder.add_edge(previous, END)
DB = "report.db"
if os.path.exists(DB):
os.remove(DB)
graph = builder.compile(checkpointer=SqliteSaver(sqlite3.connect(DB, check_same_thread=False)))
print(" → ".join(graph.get_graph().nodes))__start__ → note_P1 → note_P2 → note_P3 → compare → title → report → __end__
3. พังกลางทาง แล้วทำต่อจากไฟล์
config = {"configurable": {"thread_id": "report-1"}}
NETWORK["drop_at"] = "compare"
try:
graph.invoke({"audience": "researchers", "results": {}}, config)
except ConnectionError as e:
print("💥", e) ✓ note_P1
✓ note_P2
✓ note_P3
💥 network dropped at step 'compare'
del graph # as if the program had closed
graph = builder.compile(checkpointer=SqliteSaver(sqlite3.connect(DB, check_same_thread=False)))
snapshot = graph.get_state(config)
print("next:", snapshot.next, "· done:", list(snapshot.values["results"]))next: ('compare',) · done: ['note_P1', 'note_P2', 'note_P3']
# ✏️ TODO 4 (▶ วิดีโอ 3:32): ทำต่อจาก checkpoint ล่าสุด (input = None)
result = ___
print(f"model calls in total: {USAGE['calls']}\n")
print(result["results"]["title"])result = graph.invoke(None, config)
print(f"model calls in total: {USAGE['calls']}\n")
print(result["results"]["title"]) ✓ compare
✓ title
✓ report
model calls in total: 6
Comparative Analysis of Architectural Efficiency, Patch-Based Representation, and Foundation Model Scaling in Time-Series Forecasting
4. สิ่งที่ framework เพิ่มให้: ประวัติทุก checkpoint และการแตกกิ่ง
Lab 2 เก็บแค่ checkpoint ล่าสุด และ rollback ลบ ผลเก่าทิ้ง LangGraph เก็บ ทุก checkpoint — ย้อนไปจุดไหนก็ได้ แก้ state แล้วแตกเป็น กิ่งใหม่ โดยกิ่งเดิมยังอยู่
history = list(graph.get_state_history(config))
print(f"{len(history)} checkpoints, newest first:")
for h in history:
print(" next:", h.next, "· done:", len(h.values.get("results", {})))8 checkpoints, newest first:
next: () · done: 6
next: ('report',) · done: 5
next: ('title',) · done: 4
next: ('compare',) · done: 3
next: ('note_P3',) · done: 2
next: ('note_P2',) · done: 1
next: ('note_P1',) · done: 0
next: ('__start__',) · done: 0
# ✏️ TODO 5 (▶ วิดีโอ 4:28): สร้างกิ่งใหม่จาก before_title โดยเปลี่ยน audience เป็นนักศึกษาปีหนึ่ง
USAGE["calls"] = 0
before_title = next(h for h in history if h.next == ("title",))
fork = ___
new = graph.invoke(None, fork)
print(f"model calls: {USAGE['calls']}\n\n{new['results']['report']}")USAGE["calls"] = 0
before_title = next(h for h in history if h.next == ("title",))
fork = graph.update_state(before_title.config, {"audience": "first-year students"})
new = graph.invoke(None, fork)
print(f"model calls: {USAGE['calls']}\n\n{new['results']['report']}") ✓ title
✓ report
model calls: 2
This report provides a comparative analysis of three influential Transformer-based models for time series forecasting: Informer, PatchTST, and TimesFM. While Informer optimizes computational efficiency through ProbSparse self-attention, PatchTST enhances feature representation by utilizing local sub-series patches. In contrast, TimesFM focuses on scalability, leveraging a pre-trained foundation model for zero-shot performance. By examining these distinct approaches—architectural efficiency, feature localization, and large-scale generalization—this study evaluates how each model advances the field of predictive modeling.
print(len(list(graph.get_state_history(config))), "checkpoints now")
print("old branch:", history[0].values["results"]["report"][:90], "…")11 checkpoints now
old branch: This report provides a comparative analysis of three pivotal advancements in time-series f …
สรุป
| สิ่งที่ทำ | Lab 2 (เขียนเอง) | Lab 5 (LangGraph) |
|---|---|---|
| state | dataclass + version |
TypedDict + reducer (เวอร์ชันของ schema ยังต้องดูแลเอง) |
| บันทึก | save_state เองหลังทุกขั้น |
checkpointer บันทึกหลังทุก node ลงไฟล์ SQLite |
| พังที่ขั้น 4 แล้วทำต่อ | 6 calls | 6 calls · ไม่ได้เขียน load/skip เอง |
| ย้อน 2 ขั้น | ลบผลเก่า · 2 calls | แตกกิ่งใหม่ · 2 calls · กิ่งเดิมยังอยู่ (8 → 11 checkpoints) |
framework ประหยัดโค้ด และเพิ่มสิ่งที่เขียนเองยาก (ประวัติทุกจุด, แตกกิ่ง) — แต่เราต้องรู้ว่ามันบันทึกอะไร เมื่อไร และเก็บไว้ที่ไหน
แบบฝึกหัด
- Restart จริง: หลังเน็ตหลุดในส่วนที่ 3 ให้ restart kernel (Runtime → Restart) รัน cell ที่นิยาม
State,STEPS,make_nodeและสร้างbuilderใหม่ แล้วinvoke(None, config)— ทำต่อได้ไหม - ใช้
thread_idใหม่ ("report-2") รันงานเดียวกัน แล้วนับว่าget_state_historyของแต่ละ thread มีกี่จุด
ถัดไป — Recap ของ EP08