Lab 3 — เลือก pattern จากตาราง 19.3: วัดก่อน แล้วค่อยลง
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.4 บอกให้ใช้ตาราง 19.3 เป็น decision matrix: เริ่มจากแถวบนสุด (ง่ายที่สุด) แล้วลงมาเมื่อแบบที่ง่ายกว่าพังให้เห็นจริงๆ เท่านั้น และให้ดูสามเรื่อง: โครงสร้างงานคาดเดาได้แค่ไหน · จ่าย LLM call ได้กี่ครั้ง (เวลา + เงิน) · คุณภาพต้องอาศัยการทำซ้ำไหม
สิ่งที่จะได้เรียน
- ตัววัด: นับ LLM call, tool call, token, ค่าใช้จ่าย และเวลา ของแต่ละ pattern
- pattern แถวบน: prompt chaining — ขั้นตอนตายตัว 2 LLM call
- pattern แถวกลาง: ReAct — model เลือกเองว่าจะเรียก tool อะไร กี่ครั้ง
- งาน A: chain พอไหม? · งาน B: chain พังจริงไหม? แล้วลงไป ReAct คุ้มไหม
คลัง paper (ชื่อ ปี เป็นของจริง) สรุปเนื้อหา และ คะแนนจากผู้เรียนเป็นข้อมูลจำลองที่เขียนขึ้นเพื่อการสอน ส่วนการเรียก tool คำตอบของ model และตัวเลขที่วัดได้ทั้งหมดมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.4 และตาราง 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. คลัง paper + tool สองตัว
คลังเดิม 12 ฉบับ เพิ่ม สรุปเนื้อหา และ คะแนนจากผู้เรียน (เต็ม 5) ที่ดูได้ด้วย tool ใหม่ read_paper เท่านั้น search_papers คืนแค่ id ชื่อ และปี (STOP มีคำว่า learning แล้ว — จาก Lab 2)
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,
"summary": "ProbSparse self-attention makes transformers fast enough for very long input sequences.", "rating": 4.0},
{"id": "P02", "title": "Autoformer: decomposition transformers for long-term series forecasting", "year": 2021,
"summary": "Splits a series into trend and seasonal parts and replaces attention with auto-correlation.", "rating": 3.8},
{"id": "P03", "title": "FEDformer: frequency enhanced decomposed transformer for time series", "year": 2022,
"summary": "Combines trend-seasonal decomposition with attention computed in the frequency domain.", "rating": 3.6},
{"id": "P04", "title": "Are transformers effective for time series forecasting?", "year": 2023,
"summary": "Shows that a one-layer linear model often beats transformer forecasters on standard benchmarks.", "rating": 4.7},
{"id": "P05", "title": "PatchTST: a time series is worth 64 words", "year": 2023,
"summary": "Cuts each series into patches used as tokens, and models each channel independently.", "rating": 4.8},
{"id": "P06", "title": "iTransformer: inverted transformers for time series forecasting", "year": 2024,
"summary": "Treats each variable's whole series as one token, so attention runs across variables.", "rating": 4.3},
{"id": "P07", "title": "TimesFM: a decoder-only foundation model for time-series forecasting", "year": 2024,
"summary": "A decoder-only model pretrained on a large time-series corpus that forecasts new series zero-shot.", "rating": 4.4},
{"id": "P08", "title": "Chronos: learning the language of time series", "year": 2024,
"summary": "Scales and quantizes values into tokens and trains language-model architectures on them.", "rating": 3.9},
{"id": "P09", "title": "Attention is all you need", "year": 2017,
"summary": "Introduces the Transformer, built only from attention, for machine translation.", "rating": 4.9},
{"id": "P10", "title": "BERT: pre-training of deep bidirectional transformers", "year": 2019,
"summary": "Pretrains a bidirectional transformer encoder on text, then fine-tunes it for NLP tasks.", "rating": 4.5},
{"id": "P11", "title": "Temporal fusion transformers for interpretable time series forecasting", "year": 2019,
"summary": "An attention model for multi-horizon forecasting whose weights can be interpreted.", "rating": 3.7},
{"id": "P12", "title": "Moirai: unified training of universal time series forecasting transformers", "year": 2024,
"summary": "A universal forecaster pretrained on a large multi-domain dataset, used zero-shot.", "rating": 4.1},
]
STOP = {"with", "from", "paper", "papers", "model", "models", "using", "published", "since", "research", "about", "learning"}
def find_papers(query, year_from=0):
words = [w for w in query.lower().replace("-", " ").split() if len(w) > 3 and w not in STOP]
return [{"id": p["id"], "title": p["title"], "year": p["year"]} for p in PAPERS
if p["year"] >= year_from and any(w in p["title"].lower().replace("-", " ") for w in words)]
def read_paper(paper_id):
return next((p for p in PAPERS if p["id"] == paper_id), "ไม่มี paper ไอดีนี้")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"]}}},
{"type": "function", "function": {
"name": "read_paper",
"description": "อ่านรายละเอียดของ paper หนึ่งฉบับ คืน {id, title, year, summary, rating} โดย rating คือคะแนนเฉลี่ยจากผู้เรียน Cogito Learn (เต็ม 5)",
"parameters": {"type": "object", "properties": {
"paper_id": {"type": "string", "description": "ไอดีจาก search_papers เช่น 'P05'"}},
"required": ["paper_id"]}}},
]
def run_tool(name, args):
if name == "search_papers":
return find_papers(args["query"], args["year_from"])
return read_paper(args["paper_id"])
SYSTEM = "คุณคือผู้ช่วยค้น paper ของ Cogito Learn ใช้ tool หาข้อมูลจริงเสมอ ห้ามตอบจากความจำ วันนี้คือ " + str(datetime.date.today())2. ตัววัด
ทุก LLM call ผ่านฟังก์ชัน llm ซึ่งนับ call และ token · measure รัน pattern หนึ่งครั้ง แล้วคืนตัวเลขทั้งหมด
# ✏️ TODO 1 (▶ วิดีโอ 1:41): นับ LLM call เพิ่มหนึ่ง และบวก token ขาเข้าลงใน STATS
STATS = {}
def llm(**kwargs):
reply = client.chat.completions.create(model=MODEL, extra_body=EXTRA, **kwargs)
___
STATS["tokens_in"] += ___
STATS["tokens_out"] += reply.usage.completion_tokens
return reply.choices[0].message
def measure(pattern, question, check):
STATS.update(calls=0, tools=0, tokens_in=0, tokens_out=0)
t0 = time.time()
answer = pattern(question)
sec = time.time() - t0
cost = STATS["tokens_in"] / 1e6 * 0.07 + STATS["tokens_out"] / 1e6 * 0.34
return check(answer), dict(STATS), cost, sec, answer
def report(pattern, question, check, rounds=3):
for i in range(rounds):
ok, s, cost, sec, answer = measure(pattern, question, check)
print(f"{pattern.__name__:6} {'ถูก' if ok else 'ผิด'} · {s['calls']} LLM call · {s['tools']} tool call · {s['tokens_in'] + s['tokens_out']:,} token · {cost:.5f} ดอลลาร์ · {sec:.1f} วิ")
return answerSTATS = {}
def llm(**kwargs):
reply = client.chat.completions.create(model=MODEL, extra_body=EXTRA, **kwargs)
STATS["calls"] += 1
STATS["tokens_in"] += reply.usage.prompt_tokens
STATS["tokens_out"] += reply.usage.completion_tokens
return reply.choices[0].message
def measure(pattern, question, check):
STATS.update(calls=0, tools=0, tokens_in=0, tokens_out=0)
t0 = time.time()
answer = pattern(question)
sec = time.time() - t0
cost = STATS["tokens_in"] / 1e6 * 0.07 + STATS["tokens_out"] / 1e6 * 0.34
return check(answer), dict(STATS), cost, sec, answer
def report(pattern, question, check, rounds=3):
for i in range(rounds):
ok, s, cost, sec, answer = measure(pattern, question, check)
print(f"{pattern.__name__:6} {'ถูก' if ok else 'ผิด'} · {s['calls']} LLM call · {s['tools']} tool call · {s['tokens_in'] + s['tokens_out']:,} token · {cost:.5f} ดอลลาร์ · {sec:.1f} วิ")
return answer3. แถวบน: prompt chaining
ขั้นตอนตายตัว เขียนไว้ในโค้ด: ① LLM แปลงคำขอเป็นคำค้น (structured output) → ② ค้น แล้วอ่านฉบับแรก (โค้ดทำ ไม่ใช่ model) → ③ LLM ตอบจากข้อมูลนั้น
QUERY = {"type": "json_schema", "json_schema": {"name": "query", "strict": True, "schema": {
"type": "object", "properties": {"query": {"type": "string"}, "year_from": {"type": "integer"}},
"required": ["query", "year_from"], "additionalProperties": False}}}
def chain(question):
q = json.loads(llm(response_format=QUERY, messages=[
{"role": "system", "content": "แปลงคำขอเป็นคำค้นภาษาอังกฤษ และปี ค.ศ. ที่เก่าที่สุด (ถ้าไม่ระบุใช้ 0)"},
{"role": "user", "content": question}]).content)
# ✏️ TODO 2 (▶ วิดีโอ 2:51): ขั้นตายตัว: ค้นด้วยคำค้นที่ได้ แล้วอ่านรายละเอียดของฉบับแรก
hits = ___
detail = ___ if hits else None
STATS["tools"] += 2
prompt = f"คำขอ: {question}\nผลค้น: {hits}\nรายละเอียดฉบับแรก: {detail}\nตอบคำขอจากข้อมูลนี้เท่านั้น"
return llm(messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}]).contentQUERY = {"type": "json_schema", "json_schema": {"name": "query", "strict": True, "schema": {
"type": "object", "properties": {"query": {"type": "string"}, "year_from": {"type": "integer"}},
"required": ["query", "year_from"], "additionalProperties": False}}}
def chain(question):
q = json.loads(llm(response_format=QUERY, messages=[
{"role": "system", "content": "แปลงคำขอเป็นคำค้นภาษาอังกฤษ และปี ค.ศ. ที่เก่าที่สุด (ถ้าไม่ระบุใช้ 0)"},
{"role": "user", "content": question}]).content)
hits = find_papers(q["query"], q["year_from"])
detail = read_paper(hits[0]["id"]) if hits else None
STATS["tools"] += 2
prompt = f"คำขอ: {question}\nผลค้น: {hits}\nรายละเอียดฉบับแรก: {detail}\nตอบคำขอจากข้อมูลนี้เท่านั้น"
return llm(messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}]).content4. แถวกลาง: ReAct
agent loop เดิม — model เลือกเองว่าจะค้นอะไร อ่านฉบับไหน กี่ครั้ง จนพอใจแล้วตอบ
def react(question, max_steps=8):
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
for step in range(max_steps):
msg = llm(messages=messages, tools=TOOLS)
messages.append(msg.model_dump(exclude_none=True))
if not msg.tool_calls:
return msg.content
# ✏️ TODO 3 (▶ วิดีโอ 3:35): รัน tool ที่ model ขอ และนับ tool call
for call in msg.tool_calls:
result = ___
STATS["tools"] += 1
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False)})
return "หยุด: ครบจำนวนรอบ"def react(question, max_steps=8):
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
for step in range(max_steps):
msg = llm(messages=messages, tools=TOOLS)
messages.append(msg.model_dump(exclude_none=True))
if not msg.tool_calls:
return msg.content
for call in msg.tool_calls:
result = run_tool(call.function.name, json.loads(call.function.arguments))
STATS["tools"] += 1
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result, ensure_ascii=False)})
return "หยุด: ครบจำนวนรอบ"5. งาน A: สรุป PatchTST สามข้อ
ขั้นตอนรู้ล่วงหน้า (ค้น → อ่าน → สรุป) · ผ่านเมื่อคำตอบพูดถึง patch
TASK_A = "สรุป paper PatchTST ให้หน่อย สามข้อ"
check_a = lambda answer: "patch" in answer.lower()
answer = report(chain, TASK_A, check_a)
print(answer)chain right · 2 LLM calls · 2 tool calls · 338 tokens · $0.00005 · 2.8 s
chain right · 2 LLM calls · 2 tool calls · 334 tokens · $0.00005 · 1.6 s
chain right · 2 LLM calls · 2 tool calls · 360 tokens · $0.00006 · 2.1 s
Based on the provided information, the PatchTST paper can be summarized in these three points:
* **Patch-based Tokenization:** It treats a time series as a collection of patches, where each series is divided into patches that serve as tokens (e.g., "a time series is worth 64 words").
* **Channel Independence:** The model processes each channel within the time series independently.
* **Transformer-based Approach:** It utilizes a patch-based mechanism to represent time series data for modeling.
answer = report(react, TASK_A, check_a)react right · 3 LLM calls · 2 tool calls · 1,323 tokens · $0.00015 · 3.5 s
react right · 3 LLM calls · 2 tool calls · 1,335 tokens · $0.00016 · 3.3 s
react right · 3 LLM calls · 2 tool calls · 1,350 tokens · $0.00016 · 4.0 s
6. งาน B: paper ตั้งแต่ปี 2023 ที่ผู้เรียนให้คะแนน ≥ 4.5
คำตอบที่ถูก: P04 (4.7) และ P05 PatchTST (4.8) — แต่คะแนนอยู่ใน read_paper เท่านั้น และไม่รู้ล่วงหน้าว่าต้องอ่านกี่ฉบับ
# ✏️ TODO 4 (▶ วิดีโอ 4:58): เขียนฟังก์ชันตรวจของงาน B: ต้องมีทั้ง PatchTST และ Are transformers effective
TASK_B = "แนะนำ paper เรื่อง time-series ตั้งแต่ปี 2023 ที่ผู้เรียนให้คะแนนตั้งแต่ 4.5 ขึ้นไป"
check_b = lambda answer: ___
answer = report(chain, TASK_B, check_b)
print(answer)TASK_B = "แนะนำ paper เรื่อง time-series ตั้งแต่ปี 2023 ที่ผู้เรียนให้คะแนนตั้งแต่ 4.5 ขึ้นไป"
check_b = lambda answer: "PatchTST" in answer and "effective" in answer
answer = report(chain, TASK_B, check_b)
print(answer)chain wrong · 2 LLM calls · 2 tool calls · 497 tokens · $0.00006 · 1.7 s
chain wrong · 2 LLM calls · 2 tool calls · 510 tokens · $0.00006 · 2.4 s
chain wrong · 2 LLM calls · 2 tool calls · 509 tokens · $0.00006 · 1.6 s
Based on the available information, here are the time-series papers from 2023 onward that received a learner rating of 4.5 or higher:
* **Are transformers effective for time series forecasting?** (2023) – Rating: 4.7
answer = report(react, TASK_B, check_b)
print(answer)react right · 3 LLM calls · 7 tool calls · 2,241 tokens · $0.00024 · 4.3 s
react right · 3 LLM calls · 7 tool calls · 2,245 tokens · $0.00024 · 4.1 s
react right · 3 LLM calls · 7 tool calls · 2,245 tokens · $0.00024 · 11.8 s
Based on your criteria, here are the highly-rated time-series papers (rated 4.5 or higher) published from 2023 onward:
* **PatchTST: a time series is worth 64 words (2023)**
* **Rating:** 4.8/5
* **Summary:** This paper proposes a method that cuts each time series into "patches" to be used as tokens and models each channel independently, significantly improving transformer effectiveness for time series.
* **Are transformers effective for time series forecasting? (2023)**
* **Rating:** 4.7/5
* **Summary:** An important critical analysis that demonstrates how simple one-layer linear models can often outperform complex transformer-based forecasters on standard benchmarks.
สรุป
| งาน | chain (แถวบน) | ReAct (แถวกลาง) | เลือก |
|---|---|---|---|
| A: สรุป PatchTST | ถูก 3/3 · 2 LLM call | ถูก 3/3 · 3 LLM call · แพงกว่า ~3–4 เท่า ช้ากว่าเกือบเท่าตัว | chain |
| B: คะแนน ≥ 4.5 | ผิด 3/3 · อ่านแค่ฉบับแรก PatchTST หาย | ถูก 3/3 · ค้น 1 + อ่าน 6 · 3–8 LLM call (ไม่คงที่) · แพงกว่าหลายเท่า | ReAct |
เริ่มจากแถวบนเสมอ · ลงเมื่อพังให้เห็นจริงๆ (วัดด้วยฟังก์ชันตรวจ) · ราคาที่แพงขึ้นคุ้มก็ต่อเมื่อแบบที่ถูกกว่าตอบผิด
แบบฝึกหัด
- แก้ขั้นตายตัวของ
chainให้อ่าน ทุกฉบับ ที่ค้นเจอ (ไม่ใช่แค่ฉบับแรก) แล้วรันreportกับงาน B — ผ่านไหม กี่ LLM call? ถ้าผ่าน งาน B ควรใช้ pattern ไหน? - ลองงาน C: “paper ที่ได้คะแนนสูงสุดในคลังคือฉบับไหน” กับทั้งสอง pattern แล้วตัดสินจากตัวเลข
ถัดไป — Lab 4: ทำหลักออกแบบทั้งหมดของ EP นี้อีกครั้ง ด้วย middleware ของ LangChain