Lab 2 — trace + ทดสอบด้วย input หลายแบบ
Lab walkthrough · EP06 Design Principles and Choosing a Pattern
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP06 Design Principles and Choosing a Pattern
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
หลักออกแบบสองข้อจาก §19.3:
- ② Transparency over cleverness — ทุกขั้นของ agent ต้องเปิดดูได้ → เก็บ trace ว่าแต่ละขั้นคิดอะไร เรียก tool อะไร ได้อะไรกลับมา
- ⑥ Test with diverse inputs — พฤติกรรมของ agent ไม่นิ่ง → ทดสอบด้วย edge case, คำขอกำกวม, input ผิดรูป และรันซ้ำหลายรอบ
สิ่งที่จะได้เรียน
- ใส่ trace ใน agent loop แล้วพิมพ์ออกมาอ่านทีละขั้น
- ใช้ trace หาบั๊กที่คำตอบดูถูกแต่จริงๆ ผิด
- ชุดทดสอบ 7 แบบ × 3 รอบ ที่ตรวจผลเองอัตโนมัติ
- ใช้ trace ของเคสที่ไม่ผ่าน หาว่าพังตรงไหน แก้ แล้วรันชุดทดสอบซ้ำ
คลัง paper เป็น ข้อมูลจำลองที่เขียนขึ้นเพื่อการสอน (ชุดเดียวกับ Lab 1) ส่วนการเรียก tool และคำตอบของ model ทั้งหมดมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.3 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึง 10 สตางค์) |
| Packages | openai, python-dotenv (ติดตั้งใน cell ถัดไป) |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1
%pip install -q "openai>=1.50" python-dotenv1. ของจาก Lab 1
model + provider เดิม (Gemma 4 26B ล็อกที่ DeepInfra) · คลัง paper 12 ฉบับ · find_papers · tool search_papers ที่เขียนชัดแล้ว
import json, os, time, datetime
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": ["deepinfra/fp8"], "allow_fallbacks": False}}PAPERS = [
{"id": "P01", "title": "Informer: efficient transformer for long sequence time-series forecasting", "year": 2021},
{"id": "P02", "title": "Autoformer: decomposition transformers for long-term series forecasting", "year": 2021},
{"id": "P03", "title": "FEDformer: frequency enhanced decomposed transformer for time series", "year": 2022},
{"id": "P04", "title": "Are transformers effective for time series forecasting?", "year": 2023},
{"id": "P05", "title": "PatchTST: a time series is worth 64 words", "year": 2023},
{"id": "P06", "title": "iTransformer: inverted transformers for time series forecasting", "year": 2024},
{"id": "P07", "title": "TimesFM: a decoder-only foundation model for time-series forecasting", "year": 2024},
{"id": "P08", "title": "Chronos: learning the language of time series", "year": 2024},
{"id": "P09", "title": "Attention is all you need", "year": 2017},
{"id": "P10", "title": "BERT: pre-training of deep bidirectional transformers", "year": 2019},
{"id": "P11", "title": "Temporal fusion transformers for interpretable time series forecasting", "year": 2019},
{"id": "P12", "title": "Moirai: unified training of universal time series forecasting transformers", "year": 2024},
]
STOP = {"with", "from", "paper", "papers", "model", "models", "using", "published", "since", "research", "about"}
def find_papers(query, year_from=0, library=PAPERS):
words = [w for w in query.lower().replace("-", " ").split() if len(w) > 3 and w not in STOP]
return [p for p in library
if p["year"] >= year_from and any(w in p["title"].lower().replace("-", " ") for w in words)]
TOOLS = [{"type": "function", "function": {
"name": "search_papers",
"description": "ค้น paper วิชาการในคลังของ Cogito Learn ตามหัวข้อ คืน list ของ {id, title, year} ถ้าไม่เจอคืน []",
"parameters": {"type": "object", "properties": {
"query": {"type": "string", "description": "หัวข้อเป็นภาษาอังกฤษ เช่น 'time series transformer'"},
"year_from": {"type": "integer", "description": "ปี ค.ศ. ที่เก่าที่สุดที่ต้องการ เช่น 2023 = ตั้งแต่ปี 2023 ขึ้นไป"}},
"required": ["query", "year_from"]}}}]
def run_tool(name, args):
return find_papers(args["query"], args["year_from"])
SYSTEM = "คุณคือผู้ช่วยค้น paper ของ Cogito Learn ใช้ tool หาข้อมูลจริงเสมอ ห้ามตอบจากความจำ"2. ใส่ trace ใน agent loop
loop เดิมจาก Lab 1 เพิ่มแค่ list trace ที่เก็บทุกขั้น:
- ขั้น LLM — ใช้เวลากี่วินาที กี่ token และ model ขอ tool อะไร หรือตอบว่าอะไร
- ขั้น tool — เรียก tool ไหน ด้วย argument อะไร ได้อะไรกลับมา
def run_agent(question, max_steps=6):
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
trace = []
for step in range(1, max_steps + 1):
t0 = time.time()
reply = client.chat.completions.create(model=MODEL, extra_body=EXTRA, messages=messages, tools=TOOLS)
msg = reply.choices[0].message
messages.append(msg.model_dump(exclude_none=True))
# ✏️ TODO 1 (▶ วิดีโอ 1:47): เก็บขั้น LLM ลง trace: ใช้เวลากี่วินาที และ model ขอ tool อะไรบ้าง
trace.append({"step": step, "kind": "llm", "sec": ___,
"tokens": reply.usage.total_tokens,
"tools": ___, "text": msg.content})
if not msg.tool_calls:
return msg.content, trace
# ✏️ TODO 2 (▶ วิดีโอ 2:08): เก็บขั้น tool ลง trace: ชื่อ tool, argument และผลที่ได้
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = run_tool(call.function.name, args)
trace.append({"step": step, "kind": "tool", "name": ___, "args": ___, "result": ___})
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False)})
return "หยุด: ครบจำนวนรอบ", tracedef run_agent(question, max_steps=6):
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
trace = []
for step in range(1, max_steps + 1):
t0 = time.time()
reply = client.chat.completions.create(model=MODEL, extra_body=EXTRA, messages=messages, tools=TOOLS)
msg = reply.choices[0].message
messages.append(msg.model_dump(exclude_none=True))
trace.append({"step": step, "kind": "llm", "sec": round(time.time() - t0, 1),
"tokens": reply.usage.total_tokens,
"tools": [c.function.name for c in msg.tool_calls or []], "text": msg.content})
if not msg.tool_calls:
return msg.content, trace
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = run_tool(call.function.name, args)
trace.append({"step": step, "kind": "tool", "name": call.function.name, "args": args, "result": result})
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False)})
return "หยุด: ครบจำนวนรอบ", tracedef show_trace(trace):
for t in trace:
if t["kind"] == "llm":
what = f"ขอ tool {t['tools']}" if t["tools"] else f"ตอบ: {t['text'][:70]!r}"
print(f"ขั้น {t['step']} 🧠 LLM ({t['sec']} วิ, {t['tokens']} token) → {what}")
else:
ids = [p["id"] for p in t["result"]]
print(f"ขั้น {t['step']} 🔧 {t['name']}({t['args']}) → {len(ids)} ฉบับ {ids}")3. คำตอบที่ดูถูก แต่ trace บอกว่าไม่ใช่
ถาม “ช่วง 2 ปีล่าสุด” — คำตอบดูดี แต่ year_from ที่ model ส่งไปคือเท่าไร?
RECENT = "หา paper เรื่อง transformer สำหรับ time-series ช่วง 2 ปีล่าสุด"
answer, trace = run_agent(RECENT)
print(answer)I found several significant papers published in the last two years (2023–2024) regarding transformers for time series forecasting. The research has moved from questioning their effectiveness to developing specialized architectures and foundation models.
### 2024 Research (Foundation Models & Inverted Architectures)
* **iTransformer: inverted transformers for time series forecasting** (2024) - Proposes an "inverted" approach where dimensions are treated as tokens to better capture multivariate correlations.
* **TimesFM: a decoder-only foundation model for time-series forecasting** (2024) - Introduces a decoder-only architecture designed as a large-scale foundation model for time series.
* **Chronos: learning the language of time series** (2024) - Explores treating time series data as a language-like sequence for scaling.
* **Moirai: unified training of universal time series forecasting transformers** (2024) - Focuses on training a unified, universal transformer for diverse time series tasks.
### 2023 Research (Architectural Innovations & Critical Analysis)
* **PatchTST: a time series is worth 64 words** (2023) - A highly influential paper that introduces "patching," breaking time series into sub-segments to improve local semantic capture and reduce complexity.
* **Are transformers effective for time series forecasting?** (2023) - A critical analysis paper that investigates the actual performance gains of transformers compared to simpler linear models in time series contexts.
show_trace(trace)step 1 🧠 LLM (1.4 s, 213 tokens) → asks for tool ['search_papers']
step 1 🔧 search_papers({'query': 'transformers for time series', 'year_from': 2023}) → 6 papers ['P04', 'P05', 'P06', 'P07', 'P08', 'P12']
step 2 🧠 LLM (2.8 s, 752 tokens) → answers: 'I found several significant papers published in the last two years (20'
# ✏️ TODO 3 (▶ วิดีโอ 3:23): บอก model ว่าวันนี้คือวันที่เท่าไร โดยต่อท้าย SYSTEM
SYSTEM += ___
answer, trace = run_agent(RECENT)
show_trace(trace)SYSTEM += " วันนี้คือ " + str(datetime.date.today())
answer, trace = run_agent(RECENT)
show_trace(trace)step 1 🧠 LLM (1.0 s, 227 tokens) → asks for tool ['search_papers']
step 1 🔧 search_papers({'query': 'transformers for time series', 'year_from': 2024}) → 4 papers ['P06', 'P07', 'P08', 'P12']
step 2 🧠 LLM (1.4 s, 483 tokens) → answers: 'I found several recent papers (from 2024) focusing on transformer arch'
4. ชุดทดสอบ: input 7 แบบ × 3 รอบ
| เคส | input | ผ่านเมื่อ |
|---|---|---|
| ปกติ | ตั้งแต่ปี 2023 | มี PatchTST และไม่มี Informer (ปี 2021) |
| 2 ปีล่าสุด | ช่วง 2 ปีล่าสุด | year_from ≥ ปีนี้ − 2 |
| กำกวม | “หา paper ดีๆ ให้หน่อย” | ไม่ค้นมั่ว (ถามกลับ) |
| ว่าง | ข้อความว่าง | ไม่เรียก tool |
| ปี 2099 | ปีที่ยังมาไม่ถึง | ไม่มีชื่อ paper ในคำตอบ |
| ช่วงปี | 2021 ถึง 2022 | มี Autoformer และไม่มี PatchTST (ปี 2023) |
| นอกคลัง | reinforcement learning | ไม่มีชื่อ paper ในคำตอบ (คลังไม่มีเรื่องนี้) |
NAMES = ["Informer", "Autoformer", "FEDformer", "PatchTST", "iTransformer", "TimesFM", "Chronos", "Moirai"]
THIS_YEAR = datetime.date.today().year
def named(answer):
return [n for n in NAMES if n in answer]
def searched(trace):
return [t for t in trace if t["kind"] == "tool"]CASES = [
("ปกติ", "หา paper เรื่อง transformer สำหรับ time-series ที่ออกตั้งแต่ปี 2023 ขึ้นไป",
lambda a, tr: "PatchTST" in a and "Informer" not in a),
("2 ปีล่าสุด", RECENT,
lambda a, tr: all(t["args"]["year_from"] >= THIS_YEAR - 2 for t in searched(tr))),
("กำกวม", "หา paper ดีๆ ให้หน่อย", lambda a, tr: not searched(tr)),
("ว่าง", "", lambda a, tr: not searched(tr)),
("ปี 2099", "ขอ paper เรื่อง time-series ปี 2099", lambda a, tr: not named(a)),
("ช่วงปี", "หา paper เรื่อง time-series ที่ออกปี 2021 ถึง 2022",
lambda a, tr: "Autoformer" in a and "PatchTST" not in a),
# ✏️ TODO 4 (▶ วิดีโอ 5:08): เขียนฟังก์ชันตรวจของเคสนอกคลัง: คำตอบต้องไม่เอ่ยชื่อ paper ในคลังเลย
("นอกคลัง", "หา paper เรื่อง reinforcement learning ให้หน่อย", lambda a, tr: ___),
]CASES = [
("ปกติ", "หา paper เรื่อง transformer สำหรับ time-series ที่ออกตั้งแต่ปี 2023 ขึ้นไป",
lambda a, tr: "PatchTST" in a and "Informer" not in a),
("2 ปีล่าสุด", RECENT,
lambda a, tr: all(t["args"]["year_from"] >= THIS_YEAR - 2 for t in searched(tr))),
("กำกวม", "หา paper ดีๆ ให้หน่อย", lambda a, tr: not searched(tr)),
("ว่าง", "", lambda a, tr: not searched(tr)),
("ปี 2099", "ขอ paper เรื่อง time-series ปี 2099", lambda a, tr: not named(a)),
("ช่วงปี", "หา paper เรื่อง time-series ที่ออกปี 2021 ถึง 2022",
lambda a, tr: "Autoformer" in a and "PatchTST" not in a),
("นอกคลัง", "หา paper เรื่อง reinforcement learning ให้หน่อย", lambda a, tr: not named(a)),
]from concurrent.futures import ThreadPoolExecutor
def check(case):
name, question, ok = case
answer, trace = run_agent(question)
return name, ok(answer, trace), answer, trace
# ✏️ TODO 5 (▶ วิดีโอ 5:29): สร้างรายการงาน ให้แต่ละเคสอยู่ซ้ำ rounds ครั้ง
def run_suite(rounds=3):
jobs = ___
with ThreadPoolExecutor(8) as pool:
results = list(pool.map(check, jobs))
for name, _, _ in CASES:
marks = "".join("✅" if ok else "❌" for n, ok, a, tr in results if n == name)
print(f"{name:15} {marks}")
return resultsfrom concurrent.futures import ThreadPoolExecutor
def check(case):
name, question, ok = case
answer, trace = run_agent(question)
return name, ok(answer, trace), answer, trace
def run_suite(rounds=3):
jobs = [case for case in CASES for _ in range(rounds)]
with ThreadPoolExecutor(8) as pool:
results = list(pool.map(check, jobs))
for name, _, _ in CASES:
marks = "".join("✅" if ok else "❌" for n, ok, a, tr in results if n == name)
print(f"{name:15} {marks}")
return resultsresults = run_suite()normal ✅✅✅
last 2 years ✅✅✅
ambiguous ✅✅✅
empty ✅✅✅
year 2099 ✅✅✅
year range ✅✅✅
not in library ❌❌❌
5. ใช้ trace หาว่าพังตรงไหน
for name, ok, answer, trace in results:
if not ok:
show_trace(trace)
print(answer[:200])
breakstep 1 🧠 LLM (0.7 s, 219 tokens) → asks for tool ['search_papers']
step 1 🔧 search_papers({'query': 'reinforcement learning', 'year_from': 2020}) → 1 papers ['P08']
step 2 🧠 LLM (1.3 s, 361 tokens) → answers: 'I found the following paper related to your interest in reinforcement '
I found the following paper related to your interest in reinforcement learning (though please note the search results are currently limited):
* **Chronos: learning the language of time series** (2024
print(find_papers("reinforcement learning"))[{'id': 'P08', 'title': 'Chronos: learning the language of time series', 'year': 2024}]
# ✏️ TODO 6 (▶ วิดีโอ 7:00): เพิ่มคำที่กว้างเกินไปลงในเซต STOP
___
print(find_papers("reinforcement learning"))STOP.add("learning")
print(find_papers("reinforcement learning"))[]
results = run_suite()normal ✅✅✅
last 2 years ✅✅✅
ambiguous ✅✅✅
empty ✅✅✅
year 2099 ✅✅✅
year range ✅✅✅
not in library ✅✅✅
สรุป
| หลัก | ที่เราเห็นใน lab |
|---|---|
| ② trace | “ช่วง 2 ปีล่าสุด” → คำตอบดูดี แต่ trace เผยว่า year_from เก่าเกินไป เพราะ model ไม่รู้วันที่ → ใส่วันที่ใน system prompt |
| ⑥ ทดสอบหลาย input | 7 เคส × 3 รอบ · Gemma รับมือคำขอกำกวม ข้อความว่าง ปี 2099 และช่วงปีได้เอง · เคสนอกคลังพังทุกรอบ |
| ② + ⑥ | trace ของเคสที่พังชี้ว่าต้นเหตุคือ find_papers (คำว่า learning) ไม่ใช่ model → แก้ แล้วรันทั้งชุดซ้ำ: ผ่าน 21/21 |
แบบฝึกหัด
- เพิ่มเคสของตัวเองอีก 2 เคส (เช่น ถามเป็นปี พ.ศ. หรือขอ “paper ล่าสุด 3 ฉบับ”) พร้อมฟังก์ชันตรวจ แล้วรันชุดทดสอบ
- แทนที่จะเพิ่ม
learningลงในSTOPลองแก้find_papersให้ต้องตรง อย่างน้อย 2 คำ แล้วรันชุดทดสอบ — ผ่านทุกเคสไหม? ถ้าไม่ เปิด trace ดูว่าเพราะอะไร
ถัดไป — Lab 3: ใช้ตาราง 19.3 เลือก pattern ให้งานจริง โดยวัดจำนวน LLM call และต้นทุน