Lab 2 — Routing: คัดแยกครั้งเดียว แล้วส่งต่อผู้เชี่ยวชาญ (§19.1.2)
Lab walkthrough · EP04 Workflow Patterns
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP04 Workflow Patterns
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Routing = classifier (LLM หรือ model แบบดั้งเดิม) ดู input ก่อน แล้วส่งไปยัง handler เฉพาะทาง
ผู้ช่วยอาจารย์ของ Cogito Learn ได้คำถาม 3 ประเภท:
| ประเภท | ส่งไปที่ |
|---|---|
📘 concept แนวคิด |
prompt ที่อธิบายทฤษฎีเก่ง |
🐞 code_error โค้ด error |
prompt ที่มี tool รันโค้ด |
📅 admin ธุรการ (วันสอบ ฯลฯ) |
model ตัวเล็ก ราคาถูก |
ใช้เมื่อ: งานมีหลายประเภทที่ชัดเจน และแต่ละประเภทต้องการ prompt, tool หรือ model ต่างกัน
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.1.2 (p.370) — CC BY-SA 4.0
0. เตรียมเครื่อง
ต้องมี Python 3.10+ (หรือ Colab) และ OpenRouter API key — วิธีตั้งค่าอยู่ใน Lab 1
%pip install -q "openai>=1.50" python-dotenv# ---- จาก Lab 1: ตั้งค่า client + ask_llm ----
import os, json
from openai import OpenAI
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"]
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key())
MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"provider": {"order": ["deepinfra/fp8"], "allow_fallbacks": False}, "reasoning": {"enabled": False}}
def ask_llm(prompt, temperature=0.7, schema=None):
kw = {"response_format": {"type": "json_schema", "json_schema": {"name": "out", "strict": True, "schema": schema}}} if schema else {}
resp = client.chat.completions.create(model=MODEL, extra_body=EXTRA, temperature=temperature,
messages=[{"role": "user", "content": prompt}], **kw)
text = resp.choices[0].message.content
return json.loads(text) if schema else text1. คำถามจากนักศึกษา
คำถามจำลอง 6 ข้อ แต่ละข้อมี expect (คำตอบที่ถูก) ไว้ตรวจ router — router ไม่เห็น ช่องนี้
QUESTIONS = [
{"q": "ReAct ต่างจาก prompt chaining ยังไงครับ", "expect": "concept"},
{"q": "สอบกลางภาควันไหน ห้องอะไรคะ", "expect": "admin"},
{"q": "อยากดูคะแนน lab3 แต่รันแล้ว error ครับ",
"code": 'scores = {"lab1": 8, "lab2": 9}\nprint(scores["lab3"])', "expect": "code_error"},
{"q": "ส่งงาน Lab ช้าได้ไหม หักคะแนนเท่าไหร่ครับ", "expect": "admin"},
{"q": "ฟังก์ชันหาค่าเฉลี่ยพังตอนลิสต์ว่าง ทำไมคะ",
"code": "def average(xs):\n return sum(xs) / len(xs)\nprint(average([]))", "expect": "code_error"},
{"q": "ที่ LLM hallucinate นับเป็น error แบบหนึ่งไหมครับ แล้วมันเกิดจากอะไร", "expect": "concept"},
]2. Classifier
LLM ตอบเป็น JSON ที่ route ต้องเป็น 1 ใน 3 ค่า (enum) — ใช้ temperature 0 เพราะเราอยากได้คำตอบเดิมทุกครั้ง
# ✏️ TODO 1 (▶ วิดีโอ 2:02): บังคับให้ route เป็นได้แค่ 3 ค่า: concept, code_error, admin
ROUTE_SCHEMA = {
"type": "object",
"properties": {"route": {"type": "string", "enum": ___}},
"required": ["route"], "additionalProperties": False,
}
def classify(item):
prompt = ("Classify this student question for a university AI course into exactly one route:\n"
"- concept: asks to explain an idea or theory (no code to debug)\n"
"- code_error: the student's code fails and they attached it\n"
"- admin: course logistics such as exam dates, rooms, deadlines, grading policy\n\n"
# ✏️ TODO 2 (▶ วิดีโอ 2:32): เรียก LLM ด้วย temperature 0 และ ROUTE_SCHEMA แล้วดึงค่า route ออกมา
f"Question: {item['q']}\nAttached code: {item.get('code', '(none)')}")
return ___
print(classify(QUESTIONS[0]), classify(QUESTIONS[2]))ROUTE_SCHEMA = {
"type": "object",
"properties": {"route": {"type": "string", "enum": ["concept", "code_error", "admin"]}},
"required": ["route"], "additionalProperties": False,
}
def classify(item):
prompt = ("Classify this student question for a university AI course into exactly one route:\n"
"- concept: asks to explain an idea or theory (no code to debug)\n"
"- code_error: the student's code fails and they attached it\n"
"- admin: course logistics such as exam dates, rooms, deadlines, grading policy\n\n"
f"Question: {item['q']}\nAttached code: {item.get('code', '(none)')}")
return ask_llm(prompt, temperature=0, schema=ROUTE_SCHEMA)["route"]
print(classify(QUESTIONS[0]), classify(QUESTIONS[2]))concept code_error
3. Handler เฉพาะทาง 3 ตัว
| route | prompt | tool | model |
|---|---|---|---|
concept |
อธิบายทฤษฎี + เปรียบเทียบ | — | Gemma 4 26B |
code_error |
อ่าน error จริงแล้วบอกวิธีแก้ | run_snippet() รันโค้ด |
Gemma 4 26B |
admin |
ตอบจากข้อมูลวิชาเท่านั้น | — | Gemma 3 4B (เล็ก ถูก) |
def answer_concept(item):
return ask_llm("You are a patient teaching assistant for an AI course. Explain the idea clearly, "
"with one everyday analogy. Answer in Thai, at most 3 sentences.\n\n"
f"Question: {item['q']}")import subprocess, sys
def run_snippet(code):
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=10,
env={**os.environ, "PYTHON_COLORS": "0"})
return r.stderr.strip().splitlines()[-1] if r.returncode else "no error"
# ✏️ TODO 3 (▶ วิดีโอ 4:19): รันโค้ดที่นักศึกษาแนบมาด้วย tool ก่อน แล้วส่ง error จริงเข้าไปใน prompt
def answer_code(item):
error = ___
return ask_llm("You are a Python debugging tutor. Using the REAL error below, explain the cause "
"in Thai in at most 2 sentences, then give one fixed line of code.\n\n"
f"Code:\n{item['code']}\n\nError when run: {___}"), errorimport subprocess, sys
def run_snippet(code):
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=10,
env={**os.environ, "PYTHON_COLORS": "0"})
return r.stderr.strip().splitlines()[-1] if r.returncode else "no error"
def answer_code(item):
error = run_snippet(item["code"])
return ask_llm("You are a Python debugging tutor. Using the REAL error below, explain the cause "
"in Thai in at most 2 sentences, then give one fixed line of code.\n\n"
f"Code:\n{item['code']}\n\nError when run: {error}"), errorSMALL_MODEL = "google/gemma-3-4b-it"
COURSE_INFO = ("Midterm exam: Saturday 12 December, 09:00-12:00, room CL-301. Final exam: Saturday 6 February, room CL-301. "
"Late lab submission: -10% per day, not accepted after 3 days. Office hours: Wed 13:00-15:00.")
# ✏️ TODO 4 (▶ วิดีโอ 5:04): ส่งคำถามธุรการไปที่ model ตัวเล็ก SMALL_MODEL แทน MODEL หลัก
def answer_admin(item):
resp = client.chat.completions.create(model=___, temperature=0, messages=[{"role": "user", "content":
"Answer the student's question using ONLY this course info, copying dates and rooms exactly. "
"If it is not there, say to ask the instructor. "
f"Answer in Thai, 1-2 sentences.\n\nCourse info: {COURSE_INFO}\n\nQuestion: {item['q']}"}])
return resp.choices[0].message.contentSMALL_MODEL = "google/gemma-3-4b-it"
COURSE_INFO = ("Midterm exam: Saturday 12 December, 09:00-12:00, room CL-301. Final exam: Saturday 6 February, room CL-301. "
"Late lab submission: -10% per day, not accepted after 3 days. Office hours: Wed 13:00-15:00.")
def answer_admin(item):
resp = client.chat.completions.create(model=SMALL_MODEL, temperature=0, messages=[{"role": "user", "content":
"Answer the student's question using ONLY this course info, copying dates and rooms exactly. "
"If it is not there, say to ask the instructor. "
f"Answer in Thai, 1-2 sentences.\n\nCourse info: {COURSE_INFO}\n\nQuestion: {item['q']}"}])
return resp.choices[0].message.content4. Router: classify ครั้งเดียว แล้วส่งต่อ
question → classify() → ROUTES[route] → answer
# ✏️ TODO 5 (▶ วิดีโอ 5:30): สร้าง dict ที่จับคู่ชื่อ route แต่ละตัวกับฟังก์ชัน handler ของมัน
ROUTES = {"concept": ___, "code_error": ___, "admin": ___}
# ✏️ TODO 6 (▶ วิดีโอ 5:48): classify ครั้งเดียว แล้วเรียก handler ที่ตรงกับ label จาก ROUTES
def route(item):
label = ___
return label, ___ROUTES = {"concept": answer_concept, "code_error": answer_code, "admin": answer_admin}
def route(item):
label = classify(item)
return label, ROUTES[label](item)results = []
for item in QUESTIONS:
label, answer = route(item)
results.append((item, label, answer))
print(f"{'question':<46} {'expect':<11} {'route':<11} ok handler")
for item, label, _ in results:
ok = "✅" if label == item["expect"] else "❌"
print(f"{item['q'][:44]:<46} {item['expect']:<11} {label:<11} {ok} {ROUTES[label].__name__}")question expect route ok handler
ReAct ต่างจาก prompt chaining ยังไงครับ concept concept ✅ answer_concept
สอบกลางภาควันไหน ห้องอะไรคะ admin admin ✅ answer_admin
I want to see my lab3 score, but running thi code_error code_error ✅ answer_code
Can I submit a lab late? How many points are admin admin ✅ answer_admin
Why does my average function break on an emp code_error code_error ✅ answer_code
Does an LLM hallucination count as a kind of concept concept ✅ answer_concept
for item, label, answer in results:
print(f"\n[{label}] {item['q']}")
if label == "code_error":
answer, error = answer
print(" 🔧 tool:", error)
print(" →", answer.strip())
[concept] ReAct ต่างจาก prompt chaining ยังไงครับ
→ Prompt chaining คือการสั่งงานเป็นขั้นตอนเหมือนการทำตามสูตรอาหารที่ต้องทำทีละขั้นให้เสร็จก่อนไปขั้นถัดไป แต่ ReAct คือการให้ AI คิดและตัดสินใจเองว่าจะต้องไปหาข้อมูลอะไรเพิ่มในระหว่างทางเพื่อแก้ปัญหาครับ เปรียบเหมือน Prompt chaining คือการทำตามคู่มือการประกอบเฟอร์นิเจอร์ ส่วน ReAct คือการให้ช่างที่มีไหวพริบตัดสินใจเองว่าจะต้องหยิบเครื่องมืออะไรมาใช้เมื่อเจออุปสรรคครับ
[admin] สอบกลางภาควันไหน ห้องอะไรคะ
→ สอบกลางวันจะจัดขึ้นในวันเสาร์ที่ 12 ธันวาคม เวลา 09:00-12:00 ที่ห้อง CL-301 นะคะ หากต้องการข้อมูลเพิ่มเติม กรุณาปรึกษาอาจารย์ผู้สอนค่ะ
[code_error] อยากดูคะแนน lab3 แต่รันแล้ว error ครับ
🔧 tool: KeyError: 'lab3'
→ สาเหตุเกิดจากคุณพยายามเรียกใช้ Key ที่ไม่มีอยู่ใน Dictionary (`'lab3'`) ทำให้ Python หาข้อมูลไม่เจอ
**Fixed line of code:**
```python
print(scores.get("lab3", 0))
```
[admin] ส่งงาน Lab ช้าได้ไหม หักคะแนนเท่าไหร่ครับ
→ สามารถส่งงานห้องปฏิบัติการช้าได้ โดยจะหักคะแนน -10% ต่อวัน และจะไม่รับหลังจาก 3 วันค่ะ หากต้องการข้อมูลเพิ่มเติม กรุณาปรึกษาอาจารย์ผู้สอนนะคะ
[code_error] ฟังก์ชันหาค่าเฉลี่ยพังตอนลิสต์ว่าง ทำไมคะ
🔧 tool: ZeroDivisionError: division by zero
→ สาเหตุเกิดจากการพยายามหารด้วยศูนย์ เนื่องจากลิสต์ `xs` เป็นค่าว่าง ทำให้ `len(xs)` มีค่าเป็น 0 ครับ
```python
return sum(xs) / len(xs) if xs else 0
```
[concept] ที่ LLM hallucinate นับเป็น error แบบหนึ่งไหมครับ แล้วมันเกิดจากอะไร
→ ใช่ครับ Hallucination ถือเป็นข้อผิดพลาดประเภทหนึ่งที่เกิดจากการที่โมเดลพยายามคาดเดาคำถัดไปตามความน่าจะเป็นทางสถิติแทนที่จะอ้างอิงจากความจริง เปรียบเสมือนเพื่อนที่พยายามตอบคำถามคุณอย่างมั่นใจแม้จะไม่รู้เรื่องนั้นเลย โดยการ "แต่งเรื่องขึ้นมาใหม่" เพื่อให้บทสนทนาลื่นไหลครับ
สรุป
| องค์ประกอบ | ในโค้ด |
|---|---|
| Classifier | classify() — structured output, enum 3 ค่า, temperature 0 |
| Handler เฉพาะทาง | answer_concept (prompt) · answer_code (tool run_snippet) · answer_admin (model เล็ก) |
| Dispatch | ROUTES[label](item) — classify ครั้งเดียว แล้วส่งต่อ |
ลองทำต่อ: เพิ่ม route ใหม่ off_topic (เช่น “แนะนำร้านกาแฟแถวมหาลัยหน่อย”) ที่ตอบสุภาพว่าไม่อยู่ในขอบเขตวิชา — ต้องแก้แค่ enum, prompt ของ classifier และ ROUTES