Skip to main content

Lab 2 — Planning Agent (§19.2.2)

Lab walkthrough · EP05 Autonomous Agent Patterns

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

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

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

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

ReAct ตัดสินใจทีละก้าว ส่วน planning agent สร้าง plan ทั้งหมดก่อน แล้วค่อยลงมือ (Plan-and-Execute, §18.5.2)

  1. Planning phase — LLM สร้าง plan เป็น DAG (แต่ละ step มี deps)
  2. Execution phase — รันเฉพาะ step ที่ deps เสร็จแล้ว แต่ละ step ใช้ ReAct agent จาก Lab 1
  3. Plan revision — ผลไม่เป็นไปตามคาด → replan (กลยุทธ์ Adaptive, ตาราง 19.1)

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

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

ต้องมี Python 3.10+ (หรือ Colab) และ OpenRouter API key — วิธีตั้งค่าอยู่ใน Lab 1 (Colab: 🔑 Secrets ชื่อ OPENROUTER_API_KEY · เครื่องตัวเอง: ไฟล์ .env)

%pip install -q "openai>=1.50" python-dotenv pydantic
# ---- จาก Lab 1: ตั้งค่า client + tools + react_agent ----
import os, json
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": {"effort": "medium"}}

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 ask_llm(messages, tools=None, system=None, response_format=None):
    if system:
        messages = [{"role": "system", "content": system}] + messages
    kwargs = dict(model=MODEL, messages=messages, extra_body=EXTRA)
    if tools:
        kwargs["tools"] = tools
    if response_format:
        kwargs["response_format"] = response_format
    return client.chat.completions.create(**kwargs).choices[0].message
# ---- จาก Lab 1: react_agent (ย่อ: ไม่พิมพ์ Thought) ----
def react_agent(task, tool_names, max_iterations=6, indent="      "):
    messages = [{"role": "user", "content": task}]
    for i in range(1, max_iterations + 1):
        msg = ask_llm(messages, tools=schemas(tool_names))
        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}🔧 {c.function.name}({c.function.arguments})")
        with ThreadPoolExecutor() as pool:
            messages.extend(pool.map(run_tool, calls))
    return "⚠️ Stopped: reached max_iterations"
PAPERS = {  # ข้อมูลจำลองเพื่อการสอน
    "P1": {"title": "Crossformer", "year": 2023, "method": "two-stage attention across dimensions"},
    "P2": {"title": "TimesFM", "year": 2024, "method": "decoder-only foundation model"},
    "P3": {"title": "Chronos", "year": 2024, "method": "tokenizes values for a T5-style model"},
    "P4": {"title": "PatchTST", "year": 2023, "method": "patching + channel independence"},
    "P5": {"title": "iTransformer", "year": 2024, "method": "attention over variates"},
    "P6": {"title": "Moirai", "year": 2024, "method": "any-variate attention, universal forecaster"},
}
STATE = {"search_step": 0, "found": []}   # search_step: นับโดย run_step (ข้อมูลจำลอง)

@tool("Search papers on a topic. Returns a JSON list of {id, title, year}.", {"query": {"type": "string"}})
def search_papers(query):
    ids = ["P1", "P2", "P3"] if STATE["search_step"] <= 1 else list(PAPERS)
    STATE["found"] = ids
    return json.dumps([{"id": i, "title": PAPERS[i]["title"], "year": PAPERS[i]["year"]} for i in ids])

@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])

1. Planning phase — plan เป็น DAG

แต่ละ step มี id, task, tool และ deps (step ที่ต้องเสร็จก่อน) → plan เป็น DAG (Directed Acyclic Graph)

from pydantic import BaseModel

class Step(BaseModel):
    id: int
    task: str
    tool: str
    deps: list[int]

class Plan(BaseModel):
    steps: list[Step]
PLAN_FORMAT = {"type": "json_schema", "json_schema": {"name": "plan", "strict": True, "schema": {
    "type": "object", "additionalProperties": False, "required": ["steps"],
    "properties": {"steps": {"type": "array", "minItems": 1, "items": {
        "type": "object", "additionalProperties": False, "required": ["id", "task", "tool", "deps"],
        "properties": {
            "id": {"type": "integer"},
            "task": {"type": "string"},
            "tool": {"type": "string", "enum": ["search_papers", "read_papers", "none"]},
            "deps": {"type": "array", "items": {"type": "integer"}},
        }}}}}}}
PLANNER_SYSTEM = (
    "You are a planner. Break the user's request into 4-7 steps forming a DAG.\n"
    "Each step has: id, task, tool (search_papers | read_papers | none), and deps.\n"
    "deps = ids of the earlier steps whose OUTPUT this step needs. Rules:\n"
    "- Only the first step(s) may have empty deps.\n"
    "- A step that reads, writes or reviews something must depend on the step that produced it.\n"
    "- Two steps that do not need each other's output must not depend on each other "
    "(so they can run in parallel)."
)
def validate_dag(plan):
    ids = {s.id for s in plan.steps}
    for s in plan.steps:
        missing = set(s.deps) - ids
        assert not missing, f"step {s.id} depends on unknown steps {missing}"
    # ✏️ TODO 1 (▶ วิดีโอ 4:36): step ที่ 'พร้อมรัน' คือ step ที่ deps ทั้งหมดอยู่ใน done แล้ว (ถ้าไม่มี step พร้อมเลย = มี cycle)
    done, remaining = set(), {s.id: set(s.deps) for s in plan.steps}
    while remaining:
        ready = [i for i, d in remaining.items() if ___]
        assert ready, f"cycle detected among steps {sorted(remaining)}"
        for i in ready:
            done.add(i)
            remaining.pop(i)
    return plan
def validate_dag(plan):
    ids = {s.id for s in plan.steps}
    for s in plan.steps:
        missing = set(s.deps) - ids
        assert not missing, f"step {s.id} depends on unknown steps {missing}"
    done, remaining = set(), {s.id: set(s.deps) for s in plan.steps}
    while remaining:
        ready = [i for i, d in remaining.items() if d <= done]
        assert ready, f"cycle detected among steps {sorted(remaining)}"
        for i in ready:
            done.add(i)
            remaining.pop(i)
    return plan
def show_plan(plan, results=None):
    for s in plan.steps:
        mark = "✅" if s.id in (results or {}) else "⬜"
        print(f"  {mark} {s.id}. {s.task}  (tool={s.tool}, deps={s.deps})")

# ✏️ TODO 2 (▶ วิดีโอ 5:05): บังคับให้ model ตอบตาม PLAN_FORMAT แล้วแปลง JSON ที่ได้เป็น Plan ก่อนตรวจ DAG
def ask_plan(prompt):
    msg = ask_llm([{"role": "user", "content": prompt}], system=PLANNER_SYSTEM, response_format=___)
    return validate_dag(___)
def show_plan(plan, results=None):
    for s in plan.steps:
        mark = "✅" if s.id in (results or {}) else "⬜"
        print(f"  {mark} {s.id}. {s.task}  (tool={s.tool}, deps={s.deps})")

def ask_plan(prompt):
    msg = ask_llm([{"role": "user", "content": prompt}], system=PLANNER_SYSTEM, response_format=PLAN_FORMAT)
    return validate_dag(Plan.model_validate_json(msg.content))
request = "Write a 2-page report comparing transformer architectures for time-series forecasting."
plan = ask_plan(request)
print("📋 PLAN")
show_plan(plan)
📋 PLAN
  ⬜ 1. Search for key transformer-based architectures specifically designed for time-series forecasting (e.g., Informer, Autoformer, FEDformer, PatchTST, etc.).  (tool=search_papers, deps=[])
  ⬜ 2. Read the selected papers to extract specific architectural details, such as attention mechanisms (probabilistic, decomposition-based, etc.), complexity, and performance benchmarks.  (tool=read_papers, deps=[1])
  ⬜ 3. Synthesize the extracted data into a comparison framework focusing on complexity, temporal dependency handling, and computational efficiency.  (tool=none, deps=[2])
  ⬜ 4. Draft the report sections: Introduction, Architecture Comparison (the core technical analysis), and a Summary of Findings.  (tool=none, deps=[3])
  ⬜ 5. Review and polish the draft into a cohesive 2-page report with professional technical terminology.  (tool=none, deps=[4])

2. Execution + adaptive replanning

กลยุทธ์ Adaptive (ตาราง 19.1): replan เฉพาะเมื่อ step ไม่ผ่านเงื่อนไข ในตัวอย่างนี้: รายงานต้องมี paper อย่างน้อย 5 ฉบับ

# ✏️ TODO 3 (▶ วิดีโอ 5:56): step ค้นหาถือว่า 'ไม่ผ่าน' เมื่อจำนวน paper ที่เจอน้อยกว่า MIN_PAPERS
MIN_PAPERS = 5

def check_step(step):
    if step.tool == "search_papers" and ___:
        return f"Step {step.id} found only {len(STATE['found'])} papers; the report needs at least {MIN_PAPERS}."
    return None
MIN_PAPERS = 5

def check_step(step):
    if step.tool == "search_papers" and len(STATE["found"]) < MIN_PAPERS:
        return f"Step {step.id} found only {len(STATE['found'])} papers; the report needs at least {MIN_PAPERS}."
    return None
def replan(plan, results, reason):
    done = {i: results[i][:300] for i in results}
    prompt = (f"REPLAN. Original request: {request}\n"
              f"Current plan: {plan.model_dump_json()}\n"
              f"Completed step outputs: {json.dumps(done)}\n"
              f"Problem: {reason}\n"
              "Return the full revised plan. Keep completed steps with the same ids and tasks. "
              "Add new step(s) with new ids to fix the problem and update deps of later steps.")
    return ask_plan(prompt)
def run_step(step, results):
    context = {d: results[d] for d in step.deps}
    task = (f"Overall goal: {request}\nYour step: {step.task}\n"
            f"Outputs of prerequisite steps: {json.dumps(context)}\n"
            "Do only this step. Be concise (under 200 words). "
            "Keep any ids from tool results (e.g. P1) in your output so later steps can use them.")
    if step.tool == "search_papers":
        STATE["search_step"] += 1          # สำหรับฐานข้อมูลจำลองเท่านั้น
    if step.tool in TOOLS:
        return react_agent(task, [step.tool])
    return ask_llm([{"role": "user", "content": task}]).content
def execute_plan(plan, max_replans=2):
    results, replans = {}, 0
    while any(s.id not in results for s in plan.steps):
        # ✏️ TODO 4 (▶ วิดีโอ 7:49): เลือก step ที่ยังไม่ได้รัน และ deps ทุกตัวมีผลลัพธ์แล้ว
        ready = [s for s in plan.steps
                 if ___]
        if not ready:
            print("❌ no runnable step"); break
        print(f"\n▶️ ready to run: {[s.id for s in ready]}")
        for step in ready:
            print(f"   ⚙️ step {step.id}: {step.task}")
            results[step.id] = run_step(step, results)
            reason = check_step(step)
            # ✏️ TODO 5 (▶ วิดีโอ 8:12): เมื่อ step ไม่ผ่าน ให้ขอแผนใหม่ (replan) แล้วออกจาก loop เพื่อเริ่มจากแผนใหม่
            if reason and replans < max_replans:
                print(f"   ⚠️ {reason} → REPLAN")
                plan = ___
                replans += 1
                print("📋 REVISED PLAN")
                show_plan(plan, results)
                break
    return plan, results
def execute_plan(plan, max_replans=2):
    results, replans = {}, 0
    while any(s.id not in results for s in plan.steps):
        ready = [s for s in plan.steps
                 if s.id not in results and all(d in results for d in s.deps)]
        if not ready:
            print("❌ no runnable step"); break
        print(f"\n▶️ ready to run: {[s.id for s in ready]}")
        for step in ready:
            print(f"   ⚙️ step {step.id}: {step.task}")
            results[step.id] = run_step(step, results)
            reason = check_step(step)
            if reason and replans < max_replans:
                print(f"   ⚠️ {reason} → REPLAN")
                plan = replan(plan, results, reason)
                replans += 1
                print("📋 REVISED PLAN")
                show_plan(plan, results)
                break
    return plan, results
STATE.update(search_step=0, found=[])
final_plan, results = execute_plan(plan)
print("\n📄 REPORT (last step):\n", results[final_plan.steps[-1].id][:1200])

▶️ ready to run: [1]
   ⚙️ step 1: Search for key transformer-based architectures specifically designed for time-series forecasting (e.g., Informer, Autoformer, FEDformer, PatchTST, etc.).
      🔧 search_papers({"query": "transformer architectures for time-series forecasting"})
   ⚠️ Step 1 found only 3 papers; the report needs at least 5. → REPLAN
📋 REVISED PLAN
  ✅ 1. Search for key transformer-based architectures specifically designed for time-series forecasting (e.g., Informer, Autoformer, FEDformer, PatchTST, etc.).  (tool=search_papers, deps=[])
  ⬜ 2. Search for additional transformer architectures (e.g., Informer, Autoformer, FEDformer, PatchTST, etc.) to ensure at least 5 papers are identified for the comparison.  (tool=search_papers, deps=[1])
  ⬜ 3. Read the selected papers to extract specific architectural details, such as attention mechanisms (probabilistic, decomposition-based, etc.), complexity, and performance benchmarks.  (tool=read_papers, deps=[1, 2])
  ⬜ 4. Synthesize the extracted data into a comparison framework focusing on complexity, temporal dependency handling, and computational efficiency.  (tool=none, deps=[3])
  ⬜ 5. Draft the report sections: Introduction, Architecture Comparison (the core technical analysis), and a Summary of Findings.  (tool=none, deps=[4])
  ⬜ 6. Review and polish the draft into a cohesive 2-page report with professional technical terminology.  (tool=none, deps=[5])

▶️ ready to run: [2]
   ⚙️ step 2: Search for additional transformer architectures (e.g., Informer, Autoformer, FEDformer, PatchTST, etc.) to ensure at least 5 papers are identified for the comparison.
      🔧 search_papers({"query": "transformer architectures for time-series forecasting Informer Autoformer FEDformer PatchTST"})

▶️ ready to run: [3]
   ⚙️ step 3: Read the selected papers to extract specific architectural details, such as attention mechanisms (probabilistic, decomposition-based, etc.), complexity, and performance benchmarks.
      🔧 read_papers({"paper_ids": ["P1", "P2", "P3", "P4", "P5", "P6"]})

▶️ ready to run: [4]
   ⚙️ step 4: Synthesize the extracted data into a comparison framework focusing on complexity, temporal dependency handling, and computational efficiency.

▶️ ready to run: [5]
   ⚙️ step 5: Draft the report sections: Introduction, Architecture Comparison (the core technical analysis), and a Summary of Findings.

▶️ ready to run: [6]
   ⚙️ step 6: Review and polish the draft into a cohesive 2-page report with professional technical terminology.

📄 REPORT (last step):
 **Comparative Analysis: Transformer Architectures for Time-Series Forecasting**

**Introduction**
As time-series forecasting transitions toward Transformer-based frameworks, analyzing structural trade-offs is essential for selecting optimal modeling paradigms. This report evaluates diverse architectures based on dependency modeling, computational efficiency, and underlying design philosophy.

**Comparative Analysis**
**Dependency Modeling:** Architectures diverge in how they capture temporal and inter-series relationships. **P1** and **P4** utilize time-centric approaches—employing hierarchical attention and temporal patching—while **P5** and **P6** prioritize cross-variate dependencies. **P3** employs a token-based methodology for unified representation.

**Computational Efficiency:** Resource requirements vary significantly. **P4** (patching) and **P2** (decoder-only) offer optimized throughput and reduced complexity. Conversely, **P1**, **P3**, and **P6** exhibit higher computational overhead due to multi-stage processing or the demands of universal modeling.

**Design Philosophy:** Models bifurcate into structural specialization and foundation modeling. **P1**, **P4**, and **P5

สรุป

ช่วง ในโค้ด
Planning ask_plan() + structured output + validate_dag()
Execution execute_plan() — รันเฉพาะ step ที่ deps เสร็จแล้ว, ใช้ react_agent() ในแต่ละ step
Revision check_step() → replan() (กลยุทธ์ Adaptive)

ลองทำต่อ: ตั้ง MIN_PAPERS = 3 แล้วรันใหม่ (จะไม่เกิด replan) หรือลองเปลี่ยนเป็นกลยุทธ์ Continuous โดย replan หลังทุก step