Skip to main content

Lab 1 — tool ที่ดี + รับมือความล้มเหลว

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 ที่ทำงานคู่กัน:

สิ่งที่จะได้เรียน

  1. tool ที่คลุมเครือ vs tool ที่ชัดเจน — รันอย่างละ 5 รอบ แล้วนับว่า model ใช้ถูกกี่ครั้ง
  2. เมื่อระบบล่ม: error ว่า "Error" เฉยๆ vs error ที่บอกสาเหตุ
  3. retry ที่ harness — model ไม่ต้องรู้เลยว่าเคยล่ม
  4. graceful degradation — ตอบจาก cache แล้วบอกผู้ใช้ตรงๆ

คลัง paper, search API ที่ล่ม และ cache เป็น ข้อมูลจำลองที่เขียนขึ้นเพื่อการสอน ส่วนการเรียก 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 ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env

%pip install -q "openai>=1.50" python-dotenv

1. เรียก Gemma ผ่าน OpenRouter

ทำไมใช้ google/gemma-4-26b-a4b-it — ทำตามคำสั่งภาษาไทยได้ดี และ เรียก tool ได้ (tool calling) ซึ่งทุก lab ของ EP06 ต้องใช้

ทำไมล็อก provider เป็น DeepInfra — เจ้าเดียวกับ EP03 ที่เราทดสอบแล้วว่าเรียก tool ได้และให้ผลซ้ำได้ (provider ต่างเจ้า แม้ชื่อ model เดียวกัน ก็ให้ผลต่างกันได้ — EP01 Lab 3)

ไม่ฟรี แต่ถูกมาก: DeepInfra คิด 0.07 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.34 ต่อล้าน token ขาออก — ท้าย lab เราจะรวม token ที่ใช้จริงให้ดู · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-12: 3 ใน 3 ครั้งได้ 429 “rate-limited upstream”)

import json, os, time
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"
PROVIDER = {"order": ["deepinfra/fp8"], "allow_fallbacks": False}
EXTRA = {"reasoning": {"enabled": False}, "provider": PROVIDER}

2. คลัง paper จำลอง + agent loop

คลังนี้มี 12 paper (เขียนขึ้นเพื่อการสอน — ชื่อเป็น paper จริง แต่คลังและ id เป็นของเราเอง) find_papers คือ “ระบบค้นหา” ข้างหลัง tool: ค้นด้วยคำในชื่อ และกรองตามปี

run_agent คือ agent loop จาก EP03 Lab 1 (เรียก model → ถ้าขอ tool ก็รัน แล้ววนต่อ → จนตอบ) เพิ่มแค่การนับ token และเก็บว่าแต่ละรอบเรียก tool ด้วยอะไร ได้อะไรกลับมา

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)]
SYSTEM = "คุณคือผู้ช่วยค้น paper ของ Cogito Learn ใช้ tool หาข้อมูลจริงเสมอ ห้ามตอบจากความจำ"
USAGE = {"in": 0, "out": 0}

def run_agent(question, tools, run_tool, max_steps=6, show=True):
    messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
    calls = []
    for step in range(max_steps):
        reply = client.chat.completions.create(model=MODEL, extra_body=EXTRA, messages=messages, tools=tools)
        USAGE["in"] += reply.usage.prompt_tokens
        USAGE["out"] += reply.usage.completion_tokens
        msg = reply.choices[0].message
        messages.append(msg.model_dump(exclude_none=True))
        if not msg.tool_calls:
            return msg.content, calls
        for call in msg.tool_calls:
            args = json.loads(call.function.arguments)
            result = run_tool(call.function.name, args)
            calls.append({"args": args, "result": result})
            if show:
                print(f"🔧 {call.function.name}({args}) → {str(result)[:90]}")
            messages.append({"role": "tool", "tool_call_id": call.id,
                             "content": json.dumps(result, ensure_ascii=False)})
    return "หยุด: ครบจำนวนรอบ", calls

3. tool ที่คลุมเครือ

ชื่อ search · argument q และ n · คำอธิบายแค่ “ค้นหา” (คนเขียน tool รู้ว่า n คือปีเริ่มต้น — แต่ model เห็นแค่ schema)

VAGUE = [{"type": "function", "function": {
    "name": "search",
    "description": "ค้นหา",
    "parameters": {"type": "object",
                   "properties": {"q": {"type": "string"}, "n": {"type": "integer"}},
                   "required": ["q", "n"]}}}]

def run_vague(name, args):
    return find_papers(args["q"], year_from=args["n"])
QUESTION = "หา paper เรื่อง transformer สำหรับ time-series ที่ออกตั้งแต่ปี 2023 ขึ้นไป แล้วบอกชื่อมาทั้งหมด"

def test(tools, run_tool, year_key, rounds=5):
    for i in range(rounds):
        answer, calls = run_agent(QUESTION, tools, run_tool, show=False)
        for c in calls:
            old = sum(p["year"] < 2023 for p in c["result"])
            print(f"รอบ {i+1}: {year_key}={c['args'].get(year_key)} → ได้ {len(c['result'])} ฉบับ, เก่ากว่า 2023: {old}")
test(VAGUE, run_vague, "n")
round 1: n=10 → got 11 papers, older than 2023: 5
round 2: n=10 → got 11 papers, older than 2023: 5
round 3: n=10 → got 11 papers, older than 2023: 5
round 4: n=10 → got 11 papers, older than 2023: 5
round 5: n=10 → got 11 papers, older than 2023: 5

4. tool ที่ชัดเจน

ชื่อบอกว่าค้นอะไร · argument บอกความหมาย · คำอธิบายบอกว่าคืนอะไร และถ้าไม่เจอได้อะไร

CLEAR = [{"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'"},
        # ✏️ TODO 1 (▶ วิดีโอ 4:52): เขียนคำอธิบายของ year_from ให้ model รู้ว่าเป็นปีอะไร และใช้อย่างไร
        "year_from": {"type": "integer", "description": ___}},
    "required": ["query", "year_from"]}}}]

def run_clear(name, args):
    return find_papers(args["query"], year_from=args["year_from"])

test(CLEAR, run_clear, "year_from")
CLEAR = [{"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_clear(name, args):
    return find_papers(args["query"], year_from=args["year_from"])

test(CLEAR, run_clear, "year_from")
round 1: year_from=2023 → got 6 papers, older than 2023: 0
round 2: year_from=2023 → got 6 papers, older than 2023: 0
round 3: year_from=2023 → got 6 papers, older than 2023: 0
round 4: year_from=2023 → got 6 papers, older than 2023: 0
round 5: year_from=2023 → got 6 papers, older than 2023: 0

5. เมื่อระบบล่ม: error แบบไหนช่วย model

search_api คือ search จำลองที่เราสั่งให้ล่มได้: ตั้ง down["fails_left"] = จำนวนครั้งที่จะ timeout ติดกัน

class SearchTimeout(Exception):
    pass

down = {"fails_left": 0}

def search_api(query, year_from):
    if down["fails_left"] > 0:
        down["fails_left"] -= 1
        raise SearchTimeout("search API ไม่ตอบภายใน 10 วินาที")
    return find_papers(query, year_from)
def run_naive(name, args):
    try:
        return search_api(args["query"], args["year_from"])
    except Exception:
        return "Error"

down["fails_left"] = 99
answer, calls = run_agent(QUESTION, CLEAR, run_naive)
print(answer)
🔧 search_papers({'query': 'transformers for time series', 'year_from': 2023}) → Error
🔧 search_papers({'query': 'transformer time series forecasting', 'year_from': 2023}) → Error
🔧 search_papers({'query': 'transformer time series', 'year_from': 2023}) → Error
I am unable to retrieve the papers at this moment due to a technical error with the search tool. Please try again in a few minutes, or try a more specific sub-topic (e.g., "temporal transformer" or "informer time series").
# ✏️ TODO 2 (▶ วิดีโอ 6:48): จับเฉพาะ SearchTimeout แล้วคืนข้อความที่บอก model ว่าเกิดอะไรขึ้น
def run_honest(name, args):
    try:
        return search_api(args["query"], args["year_from"])
    except ___:
        return ___

down["fails_left"] = 99
answer, calls = run_agent(QUESTION, CLEAR, run_honest)
print(answer)
def run_honest(name, args):
    try:
        return search_api(args["query"], args["year_from"])
    except SearchTimeout:
        return "search_papers ใช้ไม่ได้ชั่วคราว (timeout) — ไม่ได้แปลว่าไม่มี paper"

down["fails_left"] = 99
answer, calls = run_agent(QUESTION, CLEAR, run_honest)
print(answer)
🔧 search_papers({'query': 'transformers for time series', 'year_from': 2023}) → search_papers is temporarily unavailable (timeout) — this does not mean there are no paper
I encountered a temporary error while searching the database. Please try again in a moment, and I will be happy to retrieve the titles of papers on transformers for time series published in 2023 or later for you.

6. retry ที่ harness

ลองใหม่ เฉพาะ error ชั่วคราว (timeout, 429) — รอก่อนลอง และรอนานขึ้นทุกครั้ง (1 → 2 วินาที) error จากการใช้ผิด (argument ผิด) ห้าม retry: ส่ง input เดิมก็ได้ error เดิม (EP02 Lab 4)

def with_retry(fn, *args, tries=3, wait=1):
    for attempt in range(1, tries + 1):
        try:
            return fn(*args)
        # ✏️ TODO 3 (▶ วิดีโอ 7:42): จับเฉพาะ error ชั่วคราว ถ้าครบจำนวนครั้งแล้วให้ raise ต่อ
        except ___ as e:
            if ___:
                raise
            # ✏️ TODO 4 (▶ วิดีโอ 7:58): รอแล้วค่อยลองใหม่ และให้รอนานขึ้นเป็นสองเท่าทุกครั้ง
            print(f"   ⚠️ ครั้งที่ {attempt}: {e} → รอ {wait} วินาที แล้วลองใหม่")
            ___
            ___
def with_retry(fn, *args, tries=3, wait=1):
    for attempt in range(1, tries + 1):
        try:
            return fn(*args)
        except SearchTimeout as e:
            if attempt == tries:
                raise
            print(f"   ⚠️ ครั้งที่ {attempt}: {e} → รอ {wait} วินาที แล้วลองใหม่")
            time.sleep(wait)
            wait *= 2
def run_retry(name, args):
    try:
        return with_retry(search_api, args["query"], args["year_from"])
    except SearchTimeout:
        return "search_papers ใช้ไม่ได้ชั่วคราว (timeout) — ไม่ได้แปลว่าไม่มี paper"

down["fails_left"] = 2
answer, calls = run_agent(QUESTION, CLEAR, run_retry)
print(answer)
   ⚠️ attempt 1: search API ไม่ตอบภายใน 10 วินาที → waiting 1 s, then retrying
   ⚠️ attempt 2: search API ไม่ตอบภายใน 10 วินาที → waiting 2 s, then retrying
🔧 search_papers({'query': 'transformers for time series', 'year_from': 2023}) → [{'id': 'P04', 'title': 'Are transformers effective for time series forecasting?', 'year':
Here are the titles of papers on transformers for time series published in 2023 or later:

*   Are transformers effective for time series forecasting?
*   PatchTST: a time series is worth 64 words
*   iTransformer: inverted transformers for time series forecasting
*   TimesFM: a decoder-only foundation model for time-series forecasting
*   Chronos: learning the language of time series
*   Moirai: unified training of universal time series forecasting transformers

7. graceful degradation: ตอบจาก cache แล้วบอกตรงๆ

ถ้า retry ครบแล้วยังล่ม (และทางสำรองแบบ EP05 Lab 4 ก็ล่ม) — ใช้ สำเนาคลังเก่า แทนการไม่ตอบ สำเนานี้บันทึกไว้เมื่อ 15 ม.ค. 2024 จึงยังไม่มี paper ปี 2024

SNAPSHOT_DATE = "2024-01-15"
SNAPSHOT = [p for p in PAPERS if p["year"] <= 2023]
notes = []

# ✏️ TODO 5 (▶ วิดีโอ 9:09): ถ้า retry ครบแล้วยังล่ม ให้เก็บคำเตือนลง notes แล้วค้นจาก SNAPSHOT แทน

def run_degrade(name, args):
    try:
        return with_retry(search_api, args["query"], args["year_from"])
    except SearchTimeout:
        notes.append(___)
        return {"source": f"สำเนาคลังวันที่ {SNAPSHOT_DATE} — อาจไม่ใหม่",
                "papers": ___}
SNAPSHOT_DATE = "2024-01-15"
SNAPSHOT = [p for p in PAPERS if p["year"] <= 2023]
notes = []

def run_degrade(name, args):
    try:
        return with_retry(search_api, args["query"], args["year_from"])
    except SearchTimeout:
        notes.append(f"⚠️ search ใช้ไม่ได้ ผลนี้มาจากสำเนาคลังวันที่ {SNAPSHOT_DATE} อาจไม่มี paper ใหม่")
        return {"source": f"สำเนาคลังวันที่ {SNAPSHOT_DATE} — อาจไม่ใหม่",
                "papers": find_papers(args["query"], args["year_from"], library=SNAPSHOT)}
down["fails_left"] = 99
answer, calls = run_agent(QUESTION, CLEAR, run_degrade)
print(answer)
   ⚠️ attempt 1: search API ไม่ตอบภายใน 10 วินาที → waiting 1 s, then retrying
   ⚠️ attempt 2: search API ไม่ตอบภายใน 10 วินาที → waiting 2 s, then retrying
🔧 search_papers({'query': 'transformers for time series', 'year_from': 2023}) → {'source': 'library copy of 2024-01-15 — may be out of date', 'papers': [{'id': 'P04', 'ti
Here are the titles of the papers on transformers for time series published in 2023 or later:

*   Are transformers effective for time series forecasting?
*   PatchTST: a time series is worth 64 words
# ✏️ TODO 6 (▶ วิดีโอ 9:48): ถ้ามีคำเตือนใน notes ให้วางไว้ก่อนคำตอบของ model
def final_answer(answer):
    return ___

print(final_answer(answer))
def final_answer(answer):
    return "\n".join(notes + [answer]) if notes else answer

print(final_answer(answer))
⚠️ search is unavailable; these results come from the library copy of 2024-01-15 and may miss newer papers
Here are the titles of the papers on transformers for time series published in 2023 or later:

*   Are transformers effective for time series forecasting?
*   PatchTST: a time series is worth 64 words
cost = USAGE["in"] / 1e6 * 0.07 + USAGE["out"] / 1e6 * 0.34
print(f"ทั้ง lab ใช้ {USAGE['in']:,} token ขาเข้า + {USAGE['out']:,} token ขาออก ≈ {cost:.4f} ดอลลาร์")
the whole lab used 8,853 input tokens + 2,139 output tokens ≈ $0.0013

สรุป

หลัก ที่เราเห็นใน lab
③ tool ที่ดี search(q, n) → model ส่ง n=10 (เดาว่าเป็นจำนวนผลลัพธ์) · search_papers(query, year_from) + คำอธิบาย → year_from=2023 ทุกรอบ
③ error ที่ดี "Error" → model เปลี่ยนคำค้นแล้วเรียกซ้ำ และเสนอให้ผู้ใช้เปลี่ยนคำค้น · error ที่บอกสาเหตุ → เรียกครั้งเดียว บอกผู้ใช้ตรงๆ
④ retry ลองใหม่เฉพาะ error ชั่วคราว รอ 1 → 2 วินาที · model ไม่รู้เลยว่าเคยล่ม
④ graceful degradation ตอบจากสำเนาคลัง · คำเตือนที่ต้องถึงผู้ใช้ harness แปะเอง ไม่ฝากไว้กับ model

แบบฝึกหัด

  1. ลบ description ของ year_from ใน CLEAR (เหลือแค่ชื่อ) แล้วรัน test อีกครั้ง — ชื่อที่ดีอย่างเดียวพอไหม?
  2. ให้ with_retry รับรายการ exception ที่จะ retry ได้ (เช่น timeout และ 429) แทนการเขียน SearchTimeout ตายตัว

ถัดไป — Lab 2: agent ที่พลาดแล้วเรารู้ว่าพลาดตรงไหน — ใส่ trace ทุกขั้น แล้วทดสอบด้วย input หลายแบบ