Lab 5 — จาก Scratch สู่ LangGraph (§25.3.1)
Lab walkthrough · EP05 Autonomous Agent Patterns
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP05 Autonomous Agent Patterns
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
ใน Lab 1–4 เราเขียน harness เองทุกบรรทัด lab นี้จะสร้าง ReAct agent จาก Lab 1 และ planning agent จาก Lab 2 ใหม่ด้วย LangGraph ซึ่งมองการทำงานของ agent เป็น graph — node คือขั้นตอนการคำนวณ, edge คือการเปลี่ยนจากขั้นหนึ่งไปอีกขั้น
| แนวคิดของ LangGraph | ตรงกับที่เราเขียนเองใน Lab 1 |
|---|---|
| State — dict ที่ไหลผ่าน graph | list messages |
| Node — ฟังก์ชันรับ state คืนส่วนที่อัปเดต | ask_llm, run_tool |
| Edge (มีเงื่อนไขได้) | if not calls: return, max_iterations |
| Checkpointing | — (ไม่มี: framework ให้มาเพิ่ม) |
| graph ของ planner → executor → replan | execute_plan() + replan() ใน Lab 2 |
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §25.3.1 — CC BY-SA 4.0
0. เตรียมเครื่อง
ต้องมี Python 3.10+ (หรือ Colab) และ OpenRouter API key — วิธีตั้งค่าอยู่ใน Lab 1
เวอร์ชันของ LangGraph ถูกล็อกไว้ เพราะ API ของ framework เปลี่ยนเร็ว ถ้าใช้เวอร์ชันใหม่กว่านี้ บางบรรทัดอาจต้องปรับ
%pip install -q "langgraph==1.2.16" "langchain-openai==1.7.2" "langchain-core==1.7.0" "grandalf==0.8" python-dotenvimport os, json, operator
from typing import TypedDict, Annotated, Literal
from pydantic import BaseModel
from langchain_openai import ChatOpenAI
from langchain_core.tools import tool
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import InMemorySaver# ---- จาก Lab 1: โหลด API key (Colab Secrets หรือไฟล์ .env) ----
def load_key():
try:
from google.colab import userdata
return userdata.get("OPENROUTER_API_KEY")
except ImportError:
from dotenv import load_dotenv
load_dotenv()
return os.environ["OPENROUTER_API_KEY"]llm = ChatOpenAI(model="google/gemma-4-26b-a4b-it",
base_url="https://openrouter.ai/api/v1", api_key=load_key(),
extra_body={"provider": {"order": ["deepinfra/fp8"], "allow_fallbacks": False}, "reasoning": {"enabled": False}})1. Tools ด้วย @tool
ใช้ข้อมูลจำลองชุดเดียวกับ Lab 2 (การค้นครั้งแรกเจอแค่ 3 ฉบับ) — @tool ของ LangChain สร้าง schema จาก docstring และ type hints ให้เอง
PAPERS = { # ข้อมูลจำลองเพื่อการสอน (ชุดเดียวกับ Lab 2)
"P1": {"title": "Crossformer", "year": 2023, "method": "two-stage attention across dimensions"},
"P2": {"title": "TimesFM", "year": 2024, "method": "decoder-only foundation model"},
"P3": {"title": "Chronos", "year": 2024, "method": "tokenizes values for a T5-style model"},
"P4": {"title": "PatchTST", "year": 2023, "method": "patching + channel independence"},
"P5": {"title": "iTransformer", "year": 2024, "method": "attention over variates"},
"P6": {"title": "Moirai", "year": 2024, "method": "any-variate attention, universal forecaster"},
}
STATE = {"search_step": 0, "found": []} # search_step: นับโดย executor ของ planning graph (ข้อมูลจำลอง)@tool
def search_papers(query: str) -> str:
"""Search papers on a topic. Returns a JSON list of {id, title, year}."""
ids = ["P1", "P2", "P3"] if STATE["search_step"] <= 1 else list(PAPERS)
STATE["found"] = ids
return json.dumps([{"id": i, "title": PAPERS[i]["title"], "year": PAPERS[i]["year"]} for i in ids])
@tool
def read_papers(paper_ids: list[str]) -> str:
"""Read papers by id (e.g. 'P1') and return their key methods."""
unknown = [i for i in paper_ids if i not in PAPERS]
if unknown:
return f"Error: unknown ids {unknown}. Use ids from search_papers, e.g. 'P1'."
return json.dumps([{"title": PAPERS[i]["title"], "method": PAPERS[i]["method"]} for i in paper_ids])
tools = [search_papers, read_papers]
print(read_papers.name, "|", read_papers.description)
print(read_papers.args)read_papers | Read papers by id (e.g. 'P1') and return their key methods.
{'paper_ids': {'items': {'type': 'string'}, 'title': 'Paper Ids', 'type': 'array'}}
2. State
State คือ dict ที่ไหลผ่านทุก node — แต่ละ node คืนเฉพาะ field ที่อยากอัปเดต field ที่มี reducer (เช่น add_messages) จะถูก ต่อท้าย ส่วน field ธรรมดาจะถูก เขียนทับ
# ✏️ TODO 1 (▶ วิดีโอ 3:46): state มี 2 field: messages (list ของ BaseMessage ที่ต่อท้ายด้วย reducer add_messages) และ iteration (int นับรอบ)
class AgentState(TypedDict):
messages: Annotated[list[BaseMessage], ___]
iteration: ___class AgentState(TypedDict):
messages: Annotated[list[BaseMessage], add_messages]
iteration: int3. Nodes
node คือฟังก์ชันธรรมดา: รับ state → คืน dict ของส่วนที่อัปเดต
MAX_ITERATIONS = 6
llm_with_tools = llm.bind_tools(tools)
def agent_node(state: AgentState):
reply = llm_with_tools.invoke(state["messages"])
return {"messages": [reply], "iteration": state["iteration"] + 1}
tool_node = ToolNode(tools)
def stop_node(state: AgentState):
return {"messages": [AIMessage("⚠️ Stopped: reached max iterations")]}4. Edges — ใครทำต่อ?
conditional edge คือฟังก์ชันที่ดู state แล้วตอบว่า ไป node ไหนต่อ — ตรงนี้คือ ④ termination และ ③ max iterations ของ Lab 1
# ✏️ TODO 2 (▶ วิดีโอ 5:21): ④ termination: ถ้า message ล่าสุดไม่มี tool call แปลว่า model ตอบเสร็จแล้ว ให้ไปที่ END
def route(state: AgentState):
last = state["messages"][-1]
if ___:
return ___
if state["iteration"] >= MAX_ITERATIONS:
return "stop"
return "tools"def route(state: AgentState):
last = state["messages"][-1]
if not last.tool_calls:
return END
if state["iteration"] >= MAX_ITERATIONS:
return "stop"
return "tools"builder = StateGraph(AgentState)
builder.add_node("agent", agent_node)
builder.add_node("tools", tool_node)
builder.add_node("stop", stop_node)
# ✏️ TODO 3 (▶ วิดีโอ 5:54): เชื่อม edge: เริ่มที่ agent → หลัง agent ให้ route ตัดสิน → tools วนกลับไป agent → stop จบที่ END
builder.add_edge(START, "agent")
builder.___("agent", route, ["tools", "stop", END])
builder.add_edge("tools", ___)
builder.add_edge("stop", END)
graph = builder.compile()
graph.get_graph().print_ascii()builder = StateGraph(AgentState)
builder.add_node("agent", agent_node)
builder.add_node("tools", tool_node)
builder.add_node("stop", stop_node)
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", route, ["tools", "stop", END])
builder.add_edge("tools", "agent")
builder.add_edge("stop", END)
graph = builder.compile()
graph.get_graph().print_ascii() +-----------+
| __start__ |
+-----------+
*
*
*
+-------+
| agent |.
..+-------+ ...
.. . ...
... . ..
.. . ...
+-------+ +------+ ..
| tools | | stop | ..
+-------+ +------+ .
* .
** ..
* .
+---------+
| __end__ |
+---------+
5. รัน graph
graph.stream(..., stream_mode="updates") คืนผลทีละ node — เห็นว่า node ไหนทำอะไร
def show(update):
for node, change in update.items():
for m in change.get("messages", []):
calls = getattr(m, "tool_calls", None)
if calls:
for c in calls:
print(f"🔧 [{node}] {c['name']}({c['args']})")
else:
print(f"{'👀' if node == 'tools' else '💬'} [{node}]", str(m.content)[:150])task = ("Find transformer models for time-series forecasting, read them, "
"and explain in 3 bullet points how they differ.")
for update in graph.stream({"messages": [HumanMessage(task)], "iteration": 0}, stream_mode="updates"):
show(update)🔧 [agent] search_papers({'query': 'transformer models for time-series forecasting'})
👀 [tools] [{"id": "P1", "title": "Crossformer", "year": 2023}, {"id": "P2", "title": "TimesFM", "year": 2024}, {"id": "P3", "title": "Chronos", "year": 2024}]
🔧 [agent] read_papers({'paper_ids': ['P1', 'P2', 'P3']})
👀 [tools] [{"title": "Crossformer", "method": "two-stage attention across dimensions"}, {"title": "TimesFM", "method": "decoder-only foundation model"}, {"title
💬 [agent] Based on the analysis of recent transformer-based models for time-series forecasting, here is how **Crossformer**, **TimesFM**, and **Chronos** differ
6. Checkpoint + human-in-the-loop
สิ่งที่ Lab 1 ไม่มี: checkpointer บันทึก state หลังทุก node ทำให้ หยุดรอคนอนุมัติ ก่อนรัน tool แล้ว ทำต่อจากจุดเดิม ได้
ตัวอย่างในตำราใช้ SqliteSaver (เก็บลงไฟล์) — ใน lab นี้ใช้ InMemorySaver (เก็บในหน่วยความจำ) เพื่อให้รันใน Colab ได้ง่าย
# ✏️ TODO 4 (▶ วิดีโอ 8:03): compile อีกครั้งโดยใส่ checkpointer และสั่งให้หยุดก่อนเข้า node tools
safe_graph = builder.compile(checkpointer=___, interrupt_before=___)
config = {"configurable": {"thread_id": "lab5-demo"}}safe_graph = builder.compile(checkpointer=InMemorySaver(), interrupt_before=["tools"])
config = {"configurable": {"thread_id": "lab5-demo"}}safe_graph.invoke({"messages": [HumanMessage("Find transformer models for time-series forecasting and name them.")],
"iteration": 0}, config)
paused = safe_graph.get_state(config)
print("⏸️ next node:", paused.next)
for c in paused.values["messages"][-1].tool_calls:
print(f" 🔧 รออนุมัติ: {c['name']}({c['args']})")⏸️ next node: ('tools',)
🔧 รออนุมัติ: search_papers({'query': 'transformer models for time-series forecasting'})
approved = True # ในงานจริง: รอคนกดอนุมัติ
if approved:
result = safe_graph.invoke(None, config)
print("▶️ resumed →", result["messages"][-1].content[:300])
print("💾 checkpoints saved:", len(list(safe_graph.get_state_history(config))))▶️ resumed → Based on recent research, several specialized transformer models have been developed specifically for time-series forecasting. Here are some notable examples:
* **Crossformer (2023):** A model designed to capture cross-dimension dependencies and temporal patterns simultaneously.
* **TimesFM (20
💾 checkpoints saved: 5
7. Planning graph — plan → execute → replan
planning agent ของ Lab 2 เขียนเป็น graph ได้ 3 node — executor ใช้ ReAct graph จากส่วนที่ 4 ข้างใน (graph ซ้อน graph)
START → planner → executor ──(ยังมี step)──→ executor
│
├──(ค้นได้ไม่พอ)──→ replan → executor
└──(ครบทุก step)──→ END
graph นี้มี edge วนกลับเข้าตัวเอง (executor → executor) ซึ่ง print_ascii() วาดไม่ได้ จึงวาดไว้ด้านบนแทน
class Step(BaseModel):
task: str
tool: Literal["search_papers", "read_papers", "none"]
class Plan(BaseModel):
steps: list[Step]
PLANNER_RULES = ("You are a planner. Return 3-4 steps. Each step uses exactly one tool:\n"
"- search_papers: find papers\n- read_papers: read papers found earlier\n"
"- none: write text (no tool)\nThe LAST step must write the final report (tool=none).\n")
planner = llm.with_structured_output(Plan)# ✏️ TODO 5 (▶ วิดีโอ 10:27): results ต้องต่อท้ายผลของแต่ละ step (ใช้ reducer operator.add) ส่วน steps เขียนทับได้เมื่อ replan
class PlanState(TypedDict):
request: str
steps: list[Step]
results: Annotated[list[str], ___]
replans: int
def show_plan(steps, done=0):
for i, s in enumerate(steps):
print(f" {'✅' if i < done else '⬜'} {i + 1}. {s.task[:90]} (tool={s.tool})")class PlanState(TypedDict):
request: str
steps: list[Step]
results: Annotated[list[str], operator.add]
replans: int
def show_plan(steps, done=0):
for i, s in enumerate(steps):
print(f" {'✅' if i < done else '⬜'} {i + 1}. {s.task[:90]} (tool={s.tool})")def planner_node(state: PlanState):
plan = planner.invoke(PLANNER_RULES + f"Request: {state['request']}")
print("📋 PLAN"); show_plan(plan.steps)
return {"steps": plan.steps}def executor_node(state: PlanState):
step = state["steps"][len(state["results"])]
print(f"⚙️ step {len(state['results']) + 1}: {step.task[:90]}")
if step.tool == "search_papers":
STATE["search_step"] += 1 # สำหรับฐานข้อมูลจำลองเท่านั้น
task = (f"Overall goal: {state['request']}\nResults so far:\n" + "\n".join(state["results"]) +
f"\nYour step: {step.task}\nDo only this step. Be concise. Keep paper ids (e.g. P1) in your output.")
out = graph.invoke({"messages": [HumanMessage(task)], "iteration": 0})
return {"results": [out["messages"][-1].content]}# ✏️ TODO 6 (▶ วิดีโอ 11:32): ต้อง replan เมื่อ step ที่เพิ่งทำเป็นการค้นหา แต่เจอ paper น้อยกว่า MIN_PAPERS (และ replan ไม่เกิน 2 ครั้ง)
MIN_PAPERS = 5
def check(state: PlanState):
step = state["steps"][len(state["results"]) - 1]
if step.tool == "search_papers" and ___ and state["replans"] < 2:
print(f" ⚠️ found only {len(STATE['found'])} papers (need {MIN_PAPERS}) → REPLAN")
return "replan"
return "executor" if len(state["results"]) < len(state["steps"]) else ENDMIN_PAPERS = 5
def check(state: PlanState):
step = state["steps"][len(state["results"]) - 1]
if step.tool == "search_papers" and len(STATE["found"]) < MIN_PAPERS and state["replans"] < 2:
print(f" ⚠️ found only {len(STATE['found'])} papers (need {MIN_PAPERS}) → REPLAN")
return "replan"
return "executor" if len(state["results"]) < len(state["steps"]) else ENDdef replan_node(state: PlanState):
done = len(state["results"])
history = "\n".join(f"- {s.task}: {r[:200]}" for s, r in zip(state["steps"], state["results"]))
plan = planner.invoke(PLANNER_RULES + f"Request: {state['request']}\nCompleted steps and results:\n{history}\n"
f"Problem: the search found only {len(STATE['found'])} papers; the report needs at least {MIN_PAPERS}.\n"
"Return ONLY the remaining steps (not the completed ones): "
"a broader search first, then reading, then the final report.")
steps = state["steps"][:done] + plan.steps
print("📋 REVISED PLAN"); show_plan(steps, done)
return {"steps": steps, "replans": state["replans"] + 1}pb = StateGraph(PlanState)
pb.add_node("planner", planner_node)
pb.add_node("executor", executor_node)
pb.add_node("replan", replan_node)
pb.add_edge(START, "planner")
pb.add_edge("planner", "executor")
pb.add_conditional_edges("executor", check, ["executor", "replan", END])
pb.add_edge("replan", "executor")
plan_graph = pb.compile()STATE.update(search_step=0, found=[])
final = plan_graph.invoke({"request": "Write a short report comparing transformer architectures for time-series forecasting.",
"steps": [], "results": [], "replans": 0})
print("\n📄 REPORT:\n", final["results"][-1][:1000])📋 PLAN
⬜ 1. Search for recent research papers comparing different transformer architectures specifical (tool=search_papers)
⬜ 2. Read the selected papers to extract key architectural differences, advantages, and disadva (tool=read_papers)
⬜ 3. Synthesize the findings to compare performance, complexity, and efficiency across the iden (tool=none)
⬜ 4. Write a short report comparing transformer architectures for time-series forecasting based (tool=none)
⚙️ step 1: Search for recent research papers comparing different transformer architectures specifical
⚠️ found only 3 papers (need 5) → REPLAN
📋 REVISED PLAN
✅ 1. Search for recent research papers comparing different transformer architectures specifical (tool=search_papers)
⬜ 2. Perform a broader search for additional transformer-based time-series forecasting models ( (tool=search_papers)
⬜ 3. Read the identified papers (P1, P2, P3, and the new findings) to extract key architectural (tool=read_papers)
⬜ 4. Write a short report comparing the transformer architectures for time-series forecasting b (tool=none)
⚙️ step 2: Perform a broader search for additional transformer-based time-series forecasting models (
⚙️ step 3: Read the identified papers (P1, P2, P3, and the new findings) to extract key architectural
⚙️ step 4: Write a short report comparing the transformer architectures for time-series forecasting b
📄 REPORT:
# Report: Comparative Analysis of Transformer Architectures for Time-Series Forecasting
## Executive Summary
Recent advancements in time-series forecasting have seen a shift from traditional temporal modeling to diverse Transformer-based architectures. These models can be broadly categorized into three strategic approaches: **dimension-centric modeling**, **patch-based temporal modeling**, and **foundation models for zero-shot generalization**.
## 1. Dimensionality & Multivariate Modeling
A key tension in recent research is how to handle the relationship between different variables (dimensions) in multivariate data.
* **Inverted Attention:** Unlike standard Transformers that focus on temporal steps, **iTransformer (P5)** inverts the architecture to apply attention across entire variate embeddings, prioritizing multivariate dependencies.
* **Two-Stage Processing:** **Crossformer (P1)** attempts a hybrid approach using a two-stage attention mechanism to capture both temporal patterns a
สรุป
| เขียนเอง (Lab 1–2) | LangGraph (Lab 5) |
|---|---|
messages.append(...) |
State + reducer add_messages |
ask_llm(...) + run_tool(...) |
node agent + ToolNode |
for i in range(max_iterations) |
edge tools → agent + iteration |
if not calls: return |
conditional edge route → END |
execute_plan() while loop + replan() |
node planner / executor / replan + conditional edge check |
PLAN_FORMAT (JSON schema เขียนเอง) |
with_structured_output(Plan) |
| — | checkpointer + interrupt_before (human-in-the-loop) |
เขียนเองเมื่อไร / ใช้ framework เมื่อไร — เขียนเองเพื่อเข้าใจกลไกและเมื่อ agent ยังเล็ก ใช้ framework เมื่อต้องการ checkpoint, human approval, การ debug และโครงสร้างที่ทีมอ่านร่วมกันได้
ลองทำต่อ: compile planning graph ด้วย checkpointer และ interrupt_before=["executor"] ให้คนอนุมัติแผนก่อนเริ่มทำ