Skip to main content

Lab 1 — ReAct Loop (§19.2.1)

Lab walkthrough · EP05 Autonomous Agent Patterns

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

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

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

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

ใน lab นี้เราจะเขียน ReAct agent ขึ้นเองตั้งแต่ศูนย์ ไม่ใช้ framework เพื่อให้เห็นว่า harness ทำงานอย่างไร

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

  1. เรียก LLM ผ่าน API และอ่านผลลัพธ์
  2. สร้าง tool ให้ LLM เรียกใช้
  3. เขียน ReAct loop ที่มีองค์ประกอบครบ 4 อย่างตามตำรา

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.2.1 — CC BY-SA 4.0

0. เตรียมเครื่องก่อนเริ่ม

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key สมัครที่ openrouter.ai → Keys → Create Key
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. เรียก LLM ผ่าน OpenRouter

เราใช้ Gemma 4 26B (open weights) ผ่าน OpenRouter ซึ่งใช้ API แบบ OpenAI-compatible

import os, json, time
from concurrent.futures import ThreadPoolExecutor
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 = {"provider": {"order": ["deepinfra/fp8"], "allow_fallbacks": False}, "reasoning": {"effort": "medium"}}
def ask_llm(messages, tools=None):
    kwargs = dict(model=MODEL, messages=messages, extra_body=EXTRA)
    if tools:
        kwargs["tools"] = tools
    # ✏️ TODO 1 (▶ วิดีโอ 4:53): เรียก chat completions API ด้วย kwargs แล้วคืน message ของคำตอบแรก
    resp = ___(**kwargs)
    return ___
def ask_llm(messages, tools=None):
    kwargs = dict(model=MODEL, messages=messages, extra_body=EXTRA)
    if tools:
        kwargs["tools"] = tools
    resp = client.chat.completions.create(**kwargs)
    return resp.choices[0].message
msg = ask_llm([{"role": "user", "content": "Explain what an AI agent is in one sentence."}])
print("💭", (getattr(msg, "reasoning", None) or "")[:300])
print("💬", msg.content)
💭 *   Topic: AI agent.
    *   Constraint: Exactly one sentence.
    *   Goal: Explain what it is.

    *   Autonomy (acts on its own).
    *   Perception (senses/receives input from environment).
    *   Action (performs tasks/outputs).
    *   Goal-oriented (works toward a specific objective).
    *
💬 An AI agent is an autonomous system that perceives its environment, reasons through complex tasks, and takes independent actions to achieve specific goals.

2. สร้าง Tools

Tool = Python function + JSON schema ที่บอก model ว่า tool ทำอะไรและต้องส่ง argument อะไร ตำราเน้น “Provide good tools” (§19.3): description ชัดเจน schema เข้มงวด

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]
PAPERS = {  # ข้อมูลจำลองเพื่อการสอน
    "P1": {"title": "Crossformer", "year": 2023, "method": "two-stage attention across dimensions"},
    "P2": {"title": "TimesFM", "year": 2024, "method": "decoder-only foundation model"},
    "P3": {"title": "PatchTST", "year": 2023, "method": "patching + channel independence"},
    "P4": {"title": "iTransformer", "year": 2024, "method": "attention over variates, not time steps"},
}

@tool("Search papers on a topic. Returns a JSON list of {id, title, year}.",
      {"query": {"type": "string"}})
def search_papers(query):
    return json.dumps([{"id": k, "title": p["title"], "year": p["year"]} for k, p in PAPERS.items()])

@tool("Read papers by id (e.g. 'P1') and return their key methods.",
      {"paper_ids": {"type": "array", "items": {"type": "string"}}})
def read_papers(paper_ids):
    unknown = [i for i in paper_ids if i not in PAPERS]
    if unknown:
        return f"Error: unknown ids {unknown}. Use ids from search_papers, e.g. 'P1'."
    return json.dumps([{"title": PAPERS[i]["title"], "method": PAPERS[i]["method"]} for i in paper_ids])
print(search_papers("time series"))
print(json.dumps(schemas(["search_papers"]), indent=2))
[{"id": "P1", "title": "Crossformer", "year": 2023}, {"id": "P2", "title": "TimesFM", "year": 2024}, {"id": "P3", "title": "PatchTST", "year": 2023}, {"id": "P4", "title": "iTransformer", "year": 2024}]
[
  {
    "type": "function",
    "function": {
      "name": "search_papers",
      "description": "Search papers on a topic. Returns a JSON list of {id, title, year}.",
      "parameters": {
        "type": "object",
        "properties": {
          "query": {
            "type": "string"
          }
        },
        "required": [
          "query"
        ],
        "additionalProperties": false
      }
    }
  }
]

3. ReAct loop

\[\text{Thought}_t \rightarrow \text{Action}_t \rightarrow \text{Observation}_t \rightarrow \text{Thought}_{t+1}\]

Harness ต้องมี 4 อย่าง: ① scratchpad ② tool parsing ③ max iterations ④ termination

# ✏️ TODO 2 (▶ วิดีโอ 8:04): แปลง arguments (string JSON) เป็น dict แล้วเรียก function ของ tool ตามชื่อด้วย **args
def run_tool(call):
    try:
        args = ___
        out = ___
    except Exception as e:
        out = f"Error: {e}"
    return {"role": "tool", "tool_call_id": call.id, "content": str(out)}
def run_tool(call):
    try:
        args = json.loads(call.function.arguments)
        out = TOOLS[call.function.name]["fn"](**args)
    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, max_iterations=10):
    messages = [{"role": "user", "content": task}]
    for i in range(1, max_iterations + 1):           # ③ max iterations
        msg = ask_llm(messages, tools=schemas(tool_names))
        thought = getattr(msg, "reasoning", None)    # ① scratchpad
        if thought:
            print(f"💭 [{i}]", thought[:200])
        # ✏️ TODO 3 (▶ วิดีโอ 9:08): ② ดึง tool_calls ออกจาก msg (ถ้าไม่มีให้เป็น list ว่าง) และ ④ หยุดเมื่อ model ไม่เรียก tool แล้ว
        calls = ___                                  # ② tool parsing
        if ___:                                      # ④ termination
            return msg.content
        # ✏️ TODO 4 (▶ วิดีโอ 9:22): บันทึกคำตอบของ model (รวม tool_calls ที่แปลงเป็น dict) ลงใน messages
        messages.append({"role": "assistant", "content": msg.content or "",
                         "tool_calls": ___})
        for c in calls:
            print(f"🔧 [{i}] {c.function.name}({c.function.arguments})")
        with ThreadPoolExecutor() as pool:
            results = list(pool.map(run_tool, calls))
        # ✏️ TODO 5 (▶ วิดีโอ 9:39): ส่งผลจาก tool (observation) กลับเข้า messages เพื่อให้รอบถัดไป model เห็น
        for r in results:
            print(f"👀 [{i}]", r["content"][:150])
        ___
    return "⚠️ Stopped: reached max_iterations"
def react_agent(task, tool_names, max_iterations=10):
    messages = [{"role": "user", "content": task}]
    for i in range(1, max_iterations + 1):           # ③ max iterations
        msg = ask_llm(messages, tools=schemas(tool_names))
        thought = getattr(msg, "reasoning", None)    # ① scratchpad
        if thought:
            print(f"💭 [{i}]", thought[:200])
        calls = msg.tool_calls or []                 # ② tool parsing
        if not calls:                                # ④ termination
            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"🔧 [{i}] {c.function.name}({c.function.arguments})")
        with ThreadPoolExecutor() as pool:
            results = list(pool.map(run_tool, calls))
        for r in results:
            print(f"👀 [{i}]", r["content"][:150])
        messages.extend(results)
    return "⚠️ Stopped: reached max_iterations"
answer = react_agent("Find transformer models for time-series forecasting, read them, "
                     "and explain in 3 bullet points how they differ.",
                     ["search_papers", "read_papers"])
print("\n✅", answer)
💭 [1] The user wants to find Transformer models specifically designed for time-series forecasting.
Then, I need to read these models to understand their methods.
Finally, I need to summarize the differences
🔧 [1] search_papers({"query": "Transformer models for time-series forecasting"})
👀 [1] [{"id": "P1", "title": "Crossformer", "year": 2023}, {"id": "P2", "title": "TimesFM", "year": 2024}, {"id": "P3", "title": "PatchTST", "year": 2023}, 
💭 [2] The user wants to know the differences between transformer models for time-series forecasting based on three specific models (or more, but I should pick a representative set from the search results). 
🔧 [2] read_papers({"paper_ids": ["P1", "P3", "P4"]})
👀 [2] [{"title": "Crossformer", "method": "two-stage attention across dimensions"}, {"title": "PatchTST", "method": "patching + channel independence"}, {"ti
💭 [3] The user wants to know the differences between three transformer models for time-series forecasting based on the retrieved information.

I have:
- P1: Crossformer - "two-stage attention across dimensi

✅ Based on the models researched, here are the three key ways they differ in their approach to time-series forecasting:

* **Attention Target (Time vs. Variates):** While standard transformers focus on temporal dependencies, **iTransformer** reverses this by applying attention across different variables (variates) rather than time steps, treating the entire time series of a single variable as a token.
* **Dimensionality Handling:** **PatchTST** employs "channel independence," treating each variable as an isolated sequence to simplify the task, whereas **Crossformer** uses a "two-stage attention" mechanism to explicitly model complex dependencies across different dimensions.
* **Temporal Representation:** **PatchTST** breaks time series into local "patches" to capture semantic information and reduce complexity, whereas **iTransformer** preserves the full temporal profile of a variable within a single high-dimensional embedding.
print(react_agent("Find transformer models for time-series forecasting, read them, then compare them.",
                  ["search_papers", "read_papers"], max_iterations=1))
💭 [1] The user wants me to find transformer models for time-series forecasting, read them, and then compare them.

First, I need to search for relevant papers using `search_papers`. A good query would be so
🔧 [1] search_papers({"query": "transformer models for time-series forecasting"})
👀 [1] [{"id": "P1", "title": "Crossformer", "year": 2023}, {"id": "P2", "title": "TimesFM", "year": 2024}, {"id": "P3", "title": "PatchTST", "year": 2023}, 
⚠️ Stopped: reached max_iterations

สรุป

องค์ประกอบ ในโค้ด
① Scratchpad getattr(msg, "reasoning") — log แต่ไม่ส่งให้ผู้ใช้
② Tool parsing msg.tool_calls
③ Max iterations for i in range(1, max_iterations + 1)
④ Termination if not calls: return msg.content

ลองทำต่อ: เพิ่ม tool calculator แล้วถามคำถามที่ต้องคำนวณ