Skip to main content

Lab 4 — Tool-Use Patterns (§19.2.4)

Lab walkthrough · EP05 Autonomous Agent Patterns

หมายเหตุวิธีใช้หน้านี้

หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด

▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP05 Autonomous Agent Patterns

model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้

Pattern คำอธิบาย ตัวอย่างใน lab
Single-turn tool call เดียว, LLM 2 calls calculator
Multi-tool หลาย tool พร้อมกันใน response เดียว morning brief
Sequential output ของ tool หนึ่งเป็น input ของอีกตัว search → fetch
Nested tool call เรียก agent อีกตัว math sub-agent
Fallback tool หลักล้มเหลว → ลองตัวสำรอง primary → backup → cache

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.2.4 — 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 + tools + react_agent (+ ตัวนับ LLM calls และจับเวลา tools) ----
import os, json, time
from concurrent.futures import ThreadPoolExecutor
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}}  # lab นี้ไม่ใช้ Thought
CALLS = {"n": 0}

def ask_llm(messages, tools=None, system=None):
    if system:
        messages = [{"role": "system", "content": system}] + messages
    kwargs = dict(model=MODEL, messages=messages, extra_body=EXTRA)
    if tools:
        kwargs["tools"] = tools
    CALLS["n"] += 1
    return client.chat.completions.create(**kwargs).choices[0].message

TOOLS = {}

def tool(description, properties):
    def wrap(fn):
        TOOLS[fn.__name__] = {"fn": fn, "schema": {"type": "function", "function": {
            "name": fn.__name__, "description": description,
            "parameters": {"type": "object", "properties": properties,
                           "required": list(properties), "additionalProperties": False}}}}
        return fn
    return wrap

def schemas(names):
    return [TOOLS[n]["schema"] for n in names]

def run_tool(call):
    try:
        out = TOOLS[call.function.name]["fn"](**json.loads(call.function.arguments))
    except Exception as e:
        out = f"Error: {e}"
    return {"role": "tool", "tool_call_id": call.id, "content": str(out)}

def react_agent(task, tool_names, system=None, max_iterations=8, indent=""):
    messages = [{"role": "user", "content": task}]
    for i in range(1, max_iterations + 1):
        msg = ask_llm(messages, tools=schemas(tool_names), system=system)
        calls = msg.tool_calls or []
        if not calls:
            return msg.content
        messages.append({"role": "assistant", "content": msg.content or "",
                         "tool_calls": [c.model_dump() for c in calls]})
        for c in calls:
            print(f"{indent}🔧 [{i}] {c.function.name}({c.function.arguments})")
        t0 = time.time()
        with ThreadPoolExecutor() as pool:
            results = list(pool.map(run_tool, calls))
        if len(calls) > 1:
            print(f"{indent}⏱️ {len(calls)} tools ran in parallel: {time.time() - t0:.1f}s")
        for r in results:
            print(f"{indent}👀 [{i}] {r['content'][:120]}")
        messages.extend(results)
    return "⚠️ Stopped: reached max_iterations"

1. Single-turn — tool เดียว, LLM 2 calls

# ✏️ TODO 1 (▶ วิดีโอ 1:26): ป้องกัน eval: ยอมให้มีเฉพาะตัวเลข และ + - * / ( ) . กับช่องว่าง
@tool("Evaluate an arithmetic expression, e.g. '(3+4)*2'.", {"expression": {"type": "string"}})
def calculator(expression):
    if not ___:
        return "Error: only numbers and + - * / ( ) are allowed"
    return str(eval(expression))
@tool("Evaluate an arithmetic expression, e.g. '(3+4)*2'.", {"expression": {"type": "string"}})
def calculator(expression):
    if not set(expression) <= set("0123456789+-*/(). "):
        return "Error: only numbers and + - * / ( ) are allowed"
    return str(eval(expression))
before = CALLS["n"]
print(react_agent("What is (17 * 23) + 9? Use the calculator.", ["calculator"]))
print("LLM calls:", CALLS["n"] - before)
🔧 [1] calculator({"expression": "(17 * 23) + 9"})
👀 [1] 400
(17 * 23) + 9 = 400
LLM calls: 2

2. Multi-tool (parallel)

tool ต้อง อิสระต่อกัน → harness รันพร้อมกัน → latency = max(…) แทนผลรวม

def slow(value):
    time.sleep(1.5)
    return value

@tool("Get the latest stock price for a ticker.", {"ticker": {"type": "string"}})
def get_stock_price(ticker):
    return slow(json.dumps({"ticker": ticker, "price_usd": 187.4}))

@tool("Get today's weather for a city.", {"city": {"type": "string"}})
def get_weather(city):
    return slow(json.dumps({"city": city, "forecast": "rain, 29°C"}, ensure_ascii=False))

@tool("Get calendar events for a date (YYYY-MM-DD).", {"date": {"type": "string"}})
def get_calendar(date):
    return slow(json.dumps([{"time": "14:00", "event": "Thesis meeting"}]))
import datetime
today = datetime.date.today().isoformat()
print(react_agent(f"Today is {today}. Give me a morning brief: AAPL stock price, Bangkok weather, "
                  "and my calendar for today. Fetch all three at once.",
                  ["get_stock_price", "get_weather", "get_calendar"]))
🔧 [1] get_stock_price({"ticker": "AAPL"})
🔧 [1] get_weather({"city": "Bangkok"})
🔧 [1] get_calendar({"date": "2026-11-15"})
⏱️ 3 tools ran in parallel: 1.5s
👀 [1] {"ticker": "AAPL", "price_usd": 187.4}
👀 [1] {"city": "Bangkok", "forecast": "rain, 29°C"}
👀 [1] [{"time": "14:00", "event": "Thesis meeting"}]
Good morning! Here is your brief for November 15, 2026:

*   **AAPL Stock Price:** $187.40
*   **Bangkok Weather:** Rain, 29°C
*   **Your Calendar:** 
    *   14:00: Thesis meeting

3. Sequential (pipeline)

output ของ tool หนึ่งเป็น input ของ tool ถัดไป — model ตัดสินใจ tool ถัดไปจากผลก่อนหน้า

DOCS = {  # ข้อมูลจำลอง
    "https://docs.example/patchtst": "PatchTST splits each series into patches of 16 steps "
                                     "and models each channel independently.",
    "https://docs.example/itransformer": "iTransformer applies attention across variates instead of time steps.",
}

# ✏️ TODO 2 (▶ วิดีโอ 3:22): fetch_page: คืนเนื้อหาจาก DOCS ตาม url ถ้าไม่มี url นั้นให้คืนข้อความ Error แทนการ crash
@tool("Search the docs. Returns a JSON list of {title, url}.", {"query": {"type": "string"}})
def search_docs(query):
    return json.dumps([{"title": u.rsplit("/", 1)[1], "url": u} for u in DOCS])

@tool("Fetch a page by url and return its text.", {"url": {"type": "string"}})
def fetch_page(url):
    return ___
DOCS = {  # ข้อมูลจำลอง
    "https://docs.example/patchtst": "PatchTST splits each series into patches of 16 steps "
                                     "and models each channel independently.",
    "https://docs.example/itransformer": "iTransformer applies attention across variates instead of time steps.",
}

@tool("Search the docs. Returns a JSON list of {title, url}.", {"query": {"type": "string"}})
def search_docs(query):
    return json.dumps([{"title": u.rsplit("/", 1)[1], "url": u} for u in DOCS])

@tool("Fetch a page by url and return its text.", {"url": {"type": "string"}})
def fetch_page(url):
    return DOCS.get(url, f"Error: page not found: {url}")
print(react_agent("How long is each patch in PatchTST? Search the docs, then fetch the right page.",
                  ["search_docs", "fetch_page"]))
🔧 [1] search_docs({"query": "PatchTST patch length"})
👀 [1] [{"title": "patchtst", "url": "https://docs.example/patchtst"}, {"title": "itransformer", "url": "https://docs.example/i
🔧 [2] fetch_page({"url": "https://docs.example/patchtst"})
👀 [2] PatchTST splits each series into patches of 16 steps and models each channel independently.
In PatchTST, each patch is **16 steps** long.

4. Nested (agent-as-tool)

parent agent เห็น sub-agent เป็นแค่ tool ตัวหนึ่ง (black box) แต่ข้างในคือ agent อีกตัวที่มี prompt และ tool ของตัวเอง

# ✏️ TODO 3 (▶ วิดีโอ 4:17): agent-as-tool: tool นี้ภายในคือ react_agent อีกตัวที่มี calculator เป็น tool
@tool("Delegate a math word problem to a specialist math agent. Returns the worked answer.",
      {"problem": {"type": "string"}})
def ask_math_agent(problem):
    print("      ↳ 🤖 math sub-agent started")
    return ___(problem, ___,
               system="You are a careful math agent. Always use the calculator for arithmetic.",
               indent="      ")
@tool("Delegate a math word problem to a specialist math agent. Returns the worked answer.",
      {"problem": {"type": "string"}})
def ask_math_agent(problem):
    print("      ↳ 🤖 math sub-agent started")
    return react_agent(problem, ["calculator"],
                       system="You are a careful math agent. Always use the calculator for arithmetic.",
                       indent="      ")
print(react_agent("A class has 3 sections of 42 students. Each student needs 2 notebooks "
                  "costing 18.5 baht each. How much do all notebooks cost? Delegate the math.",
                  ["ask_math_agent"]))
🔧 [1] ask_math_agent({"problem": "A class has 3 sections of 42 students. Each student needs 2 notebooks costing 18.5 baht each. How much do all notebooks cost?"})
      ↳ 🤖 math sub-agent started
      🔧 [1] calculator({"expression": "3 * 42 * 2 * 18.5"})
      👀 [1] 4662.0
👀 [1] To find the total cost of the notebooks, we can follow these steps:

1.  **Find the total number of students:** There ar
The total cost for all the notebooks is **4,662 baht**.

Here is the breakdown of the calculation:
1.  **Total number of students:** 3 sections × 42 students = 126 students.
2.  **Total number of notebooks:** 126 students × 2 notebooks each = 252 notebooks.
3.  **Total cost:** 252 notebooks × 18.5 baht = 4,662 baht.

5. Fallback (graceful degradation)

harness ลอง tool ตามลำดับความสำคัญ — model ไม่ต้องรู้เรื่อง fallback เลย (หลัก Plan for failure, §19.3)

def primary_search(q): raise TimeoutError("primary API timed out")
def backup_search(q):  raise RuntimeError("429 rate limited")
def cached_search(q):  return json.dumps([{"title": "PatchTST", "source": "cache (2 days old)"}])

# ✏️ TODO 4 (▶ วิดีโอ 5:21): ลองแหล่งค้นหาทีละตัวตามลำดับ ตัวไหนสำเร็จคืนผลทันที ถ้าล้มหมดให้คืนข้อความบอก model อย่างสุภาพ
@tool("Search the web for a topic.", {"query": {"type": "string"}})
def web_search(query):
    for name, fn in [("primary", primary_search), ("backup", backup_search), ("cache", cached_search)]:
        try:
            result = ___
            print(f"      ✅ {name} succeeded")
            return result
        except Exception as e:
            print(f"      ❌ {name} failed: {e}")
    return ___
def primary_search(q): raise TimeoutError("primary API timed out")
def backup_search(q):  raise RuntimeError("429 rate limited")
def cached_search(q):  return json.dumps([{"title": "PatchTST", "source": "cache (2 days old)"}])

@tool("Search the web for a topic.", {"query": {"type": "string"}})
def web_search(query):
    for name, fn in [("primary", primary_search), ("backup", backup_search), ("cache", cached_search)]:
        try:
            result = fn(query)
            print(f"      ✅ {name} succeeded")
            return result
        except Exception as e:
            print(f"      ❌ {name} failed: {e}")
    return "Search is currently unavailable."
print(react_agent("Search the web for a patch-based time-series transformer and name one.", ["web_search"]))
🔧 [1] web_search({"query": "patch-based time-series transformer model name"})
      ❌ primary failed: primary API timed out
      ❌ backup failed: 429 rate limited
      ✅ cache succeeded
👀 [1] [{"title": "PatchTST", "source": "cache (2 days old)"}]
One prominent patch-based time-series transformer is **PatchTST** (Patch Time Series Transformer).

สรุป

Pattern สิ่งที่เห็นใน lab
Single-turn LLM calls = 2
Multi-tool 3 tools ใช้ ~1.5s ไม่ใช่ 4.5s
Sequential search_docs → fetch_page
Nested sub-agent ที่มี prompt + tool ของตัวเอง
Fallback primary ❌ → backup ❌ → cache ✅

ลองทำต่อ: สร้าง tool ที่ต้องใช้ผลของอีก tool แล้วขอให้ model “fetch all at once” — จะเกิดอะไรขึ้น?