Skip to main content

Lab 2 — ทดสอบ harness โดยไม่เรียก model

Lab walkthrough · EP09 Building a Production Harness

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

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

▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP09 Building a Production Harness

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

ตำรา (§18.10 “How Do You Test an Agent Harness?”) เสนอห้าวิธี แล็บนี้ทำสามวิธีที่ ไม่ต้องเรียก model เลย:

วิธี ในแล็บนี้
① unit test ทดสอบ ContextManager, LoopDetector, การตัด output ทีละชิ้น
② mock LLM harness ทั้งตัว คุยกับ “model ปลอม” ที่ตอบตามบทที่เราเขียน
④ adversarial จงใจส่งของพังเข้าไป: tool ที่ไม่มีอยู่, tool ที่พัง, tool ที่ค้าง, JSON ไม่ครบ, คำขอซ้ำ

ไม่ต้องใช้ API key และไม่เสียเงิน ทุกการทดสอบเสร็จในไม่กี่วินาที (③ evaluation ทำไปแล้วใน EP06 Lab 2 · ⑤ regression อยู่ใน Lab 3)

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

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
Packages openai, tokenizers (ติดตั้งใน cell ถัดไป)
API key ไม่ต้องใช้ — แล็บนี้ไม่เรียก model จริงเลย
%pip install -q "openai>=1.50" "tokenizers==0.23.3"

1. harness จาก Lab 1

โค้ดเดียวกับ Lab 1 ทุกบรรทัด ยกเว้นจุดเดียว ซึ่งตรงกับตำรา: AgentHarness รับ client เป็น argument (client or AsyncOpenAI(...)) — นี่คือสิ่งที่ทำให้เราสลับ model จริงเป็น model ปลอมได้

import asyncio, hashlib, json, logging, os, time
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Optional
from openai import AsyncOpenAI
from tokenizers import Tokenizer

MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False},
         "provider": {"order": ["makora"], "allow_fallbacks": False}}
tok = Tokenizer.from_pretrained(MODEL)
logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True)
logger = logging.getLogger("agent_harness")
logger.setLevel(logging.INFO)

class Role(str, Enum):
    SYSTEM = "system"
    USER = "user"
    ASSISTANT = "assistant"
    TOOL = "tool"

@dataclass
class Message:
    role: Role
    content: str
    tool_calls: Optional[list[dict]] = None
    tool_call_id: Optional[str] = None

    def to_api_dict(self) -> dict:
        d = {"role": self.role.value, "content": self.content or None}
        if self.tool_calls:
            d["tool_calls"] = self.tool_calls
        if self.tool_call_id:
            d["tool_call_id"] = self.tool_call_id
        return d

@dataclass
class ToolDefinition:
    name: str
    description: str
    parameters: dict
    handler: Callable
    requires_approval: bool = False

    def to_api_dict(self) -> dict:
        return {"type": "function",
                "function": {"name": self.name, "description": self.description,
                             "parameters": self.parameters}}

def count_tokens(text: str) -> int:
    return len(tok.encode(text).ids)

class ContextManager:
    BUDGET_FRACTIONS = {"system": 0.10, "memory": 0.20, "tools": 0.10,
                        "history": 0.50, "reserved": 0.10}

    def __init__(self, max_tokens: int):
        self.max_tokens = max_tokens
        self.history: list[Message] = []
        self.system_msg: Optional[Message] = None

    def count_message_tokens(self, msg: Message) -> int:
        return count_tokens(msg.content or "") + 4

    def total_history_tokens(self) -> int:
        return sum(self.count_message_tokens(m) for m in self.history)

    def history_budget(self) -> int:
        return int(self.max_tokens * self.BUDGET_FRACTIONS["history"])

    def add_message(self, msg: Message) -> None:
        self.history.append(msg)
        self._enforce_budget()

    def _enforce_budget(self) -> None:
        while self.total_history_tokens() > self.history_budget() and len(self.history) > 2:
            dropped = self.history.pop(1)
            if dropped.tool_calls:
                while len(self.history) > 1 and self.history[1].role == Role.TOOL:
                    self.history.pop(1)

    def preflight_check(self, tool_tokens: int) -> bool:
        sys_tokens = self.count_message_tokens(self.system_msg) if self.system_msg else 0
        total = sys_tokens + tool_tokens + self.total_history_tokens()
        limit = self.max_tokens - int(self.max_tokens * self.BUDGET_FRACTIONS["reserved"])
        if total > limit:
            logger.warning("Context overflow: %d > %d", total, limit)
        return total <= limit

    def build_messages(self) -> list[dict]:
        msgs = [self.system_msg.to_api_dict()] if self.system_msg else []
        return msgs + [m.to_api_dict() for m in self.history]
Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
class ToolExecutor:
    MAX_OUTPUT_TOKENS = 2000
    MAX_RETRIES = 3
    TIMEOUT = 30.0

    def __init__(self, tools: list[ToolDefinition], approval_callback: Optional[Callable] = None):
        self.tools = {t.name: t for t in tools}
        self.approval = approval_callback

    async def execute(self, tool_name: str, args: dict) -> str:
        tool = self.tools.get(tool_name)
        if not tool:
            return f"Error: unknown tool '{tool_name}'"
        if tool.requires_approval and self.approval:
            if not await self.approval(tool_name, args):
                return "Action rejected by human reviewer."
        for attempt in range(self.MAX_RETRIES):
            try:
                result = await asyncio.wait_for(self._call(tool, args), timeout=self.TIMEOUT)
                return self._truncate(result)
            except asyncio.TimeoutError:
                logger.warning("Tool %s timed out (attempt %d)", tool_name, attempt + 1)
                if attempt == self.MAX_RETRIES - 1:
                    return f"Error: tool '{tool_name}' timed out"
                await asyncio.sleep(2 ** attempt)
            except Exception as exc:
                logger.error("Tool %s error: %s", tool_name, exc)
                if attempt == self.MAX_RETRIES - 1:
                    return f"Error: {exc}"
                await asyncio.sleep(2 ** attempt)
        return "Error: max retries exceeded"

    async def _call(self, tool: ToolDefinition, args: dict) -> str:
        if asyncio.iscoroutinefunction(tool.handler):
            return str(await tool.handler(**args))
        loop = asyncio.get_running_loop()
        return str(await loop.run_in_executor(None, lambda: tool.handler(**args)))

    def _truncate(self, text: str) -> str:
        enc = tok.encode(text)
        if len(enc.ids) <= self.MAX_OUTPUT_TOKENS:
            return text
        end = enc.offsets[self.MAX_OUTPUT_TOKENS - 1][1]
        return text[:end] + "\n[... output truncated ...]"

class LoopDetector:
    def __init__(self, window: int = 5, max_repeats: int = 2):
        self.window = window
        self.max_repeats = max_repeats
        self.action_hashes: list[str] = []

    def record(self, tool_name: str, args: dict) -> bool:
        h = hashlib.md5(f"{tool_name}:{json.dumps(args, sort_keys=True)}".encode()).hexdigest()
        self.action_hashes.append(h)
        recent = self.action_hashes[-self.window:]
        if recent.count(h) >= self.max_repeats:
            logger.warning("Loop detected: %s called %d times", tool_name, recent.count(h))
            return True
        return False
class AgentHarness:
    MAX_ITERATIONS = 50

    def __init__(self, system_prompt: str, tools: list[ToolDefinition],
                 max_tokens: int = 256_000, approval_cb: Optional[Callable] = None, client=None):
        self.client = client or AsyncOpenAI(base_url="https://openrouter.ai/api/v1",
                                            api_key=os.environ.get("OPENROUTER_API_KEY", "no-key"))
        self.ctx_mgr = ContextManager(max_tokens)
        self.executor = ToolExecutor(tools, approval_cb)
        self.loop_det = LoopDetector()
        self.tools = tools
        self.ctx_mgr.system_msg = Message(Role.SYSTEM, system_prompt)
        self.usage = {"in": 0, "out": 0}

    async def run(self, user_input: str) -> str:
        run_id = hashlib.md5(f"{time.time()}:{user_input}".encode()).hexdigest()[:8]
        start_ts = time.monotonic()
        logger.info("[%s] Starting run: %s", run_id, user_input[:80])
        self.ctx_mgr.add_message(Message(Role.USER, user_input))
        tool_defs = [t.to_api_dict() for t in self.tools]
        tool_tokens = sum(count_tokens(json.dumps(t)) for t in tool_defs)
        msg = None

        for iteration in range(self.MAX_ITERATIONS):
            if not self.ctx_mgr.preflight_check(tool_tokens):
                logger.error("[%s] Context overflow at iter %d", run_id, iteration)
                return "I've run out of context space. Please start a new conversation."
            try:
                response = await self.client.chat.completions.create(
                    model=MODEL, messages=self.ctx_mgr.build_messages(),
                    tools=tool_defs or None, tool_choice="auto", temperature=0.0, extra_body=EXTRA)
            except Exception as exc:
                logger.error("[%s] LLM call failed: %s", run_id, exc)
                return f"I encountered an error: {exc}"
            self.usage["in"] += response.usage.prompt_tokens
            self.usage["out"] += response.usage.completion_tokens
            msg, finish = response.choices[0].message, response.choices[0].finish_reason
            self.ctx_mgr.add_message(Message(Role.ASSISTANT, msg.content or "",
                tool_calls=[tc.model_dump() for tc in msg.tool_calls] if msg.tool_calls else None))
            if finish == "stop" or not msg.tool_calls:
                logger.info("[%s] Done in %d iters, %.2fs", run_id, iteration + 1, time.monotonic() - start_ts)
                return msg.content or "Task complete."

            results = await self._execute_tool_calls(msg.tool_calls, run_id)
            for tc in msg.tool_calls:
                if self.loop_det.record(tc.function.name, json.loads(tc.function.arguments)):
                    return "I seem to be stuck in a loop. Please clarify your request."
            for tool_call_id, result in results.items():
                self.ctx_mgr.add_message(Message(Role.TOOL, result, tool_call_id=tool_call_id))

        logger.warning("[%s] Max iterations reached", run_id)
        return ("I reached the maximum number of steps without completing the task. "
                "Here is what I found so far: " + (msg.content or ""))

    async def _execute_tool_calls(self, tool_calls: list, run_id: str) -> dict[str, str]:
        tasks = {}
        for tc in tool_calls:
            try:
                args = json.loads(tc.function.arguments)
            except json.JSONDecodeError:
                args = {}
            logger.info("[%s] Tool call: %s(%s)", run_id, tc.function.name, args)
            tasks[tc.id] = self.executor.execute(tc.function.name, args)
        t0 = time.monotonic()
        results = await asyncio.gather(*tasks.values(), return_exceptions=True)
        logger.info("[%s] %d tool(s) done in %.1fs", run_id, len(tasks), time.monotonic() - t0)
        return {tid: (f"Error: {r}" if isinstance(r, Exception) else r)
                for tid, r in zip(tasks.keys(), results)}

2. Mock LLM — model ปลอมที่ตอบตามบท

harness ใช้คำตอบของ model แค่ไม่กี่อย่าง: choices[0].message.content, .tool_calls (แต่ละตัวมี id, function.name, function.arguments, model_dump()), choices[0].finish_reason และ usage — เราสร้างของหน้าตาแบบนี้เองได้ โดยไม่ต้องเรียก API

from types import SimpleNamespace

class FakeToolCall:
    def __init__(self, id, name, arguments):
        self.id = id
        self.function = SimpleNamespace(name=name, arguments=arguments)

    def model_dump(self):
        return {"id": self.id, "type": "function",
                "function": {"name": self.function.name, "arguments": self.function.arguments}}

def call(name, args, id=None):
    raw = args if isinstance(args, str) else json.dumps(args)
    return FakeToolCall(id or f"call_{name}_{abs(hash(raw)) % 1000}", name, raw)

def reply(text=None, calls=None):
    msg = SimpleNamespace(content=text, tool_calls=calls)
    choice = SimpleNamespace(message=msg, finish_reason="tool_calls" if calls else "stop")
    return SimpleNamespace(choices=[choice], usage=SimpleNamespace(prompt_tokens=0, completion_tokens=0))
class MockLLM:
    def __init__(self, script):
        self.script = list(script)
        self.requests = []
        self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))

    # ✏️ TODO 1 (▶ วิดีโอ 2:42): จดข้อความที่ harness ส่งมาลง self.requests แล้วคืนคำตอบตัวแรกของบท (และเอาออกจากบท)

    async def create(self, **kwargs):
        self.requests.append(kwargs["messages"])
        return ___

def check(name, ok):
    print("✅" if ok else "❌", name)
class MockLLM:
    def __init__(self, script):
        self.script = list(script)
        self.requests = []
        self.chat = SimpleNamespace(completions=SimpleNamespace(create=self.create))

    async def create(self, **kwargs):
        self.requests.append(kwargs["messages"])
        return self.script.pop(0)

def check(name, ok):
    print("✅" if ok else "❌", name)

3. tool สำหรับทดสอบ

tool ปกติสามตัว (ค้น · อ่าน · บันทึก) และ tool ที่ตั้งใจให้พังอีกสองตัว: broken_tool (throw error ทุกครั้ง) และ slow_tool (ค้าง 10 วินาที) RAN จดว่า tool ไหนถูกรันจริงบ้าง

LIBRARY = {"P1": ("Informer (2021)", "ProbSparse self-attention."),
           "P2": ("PatchTST (2023)", "Patches of 16 steps."),
           "P3": ("TimesFM (2024)", "Zero-shot foundation model.")}
RAN = []

async def search_papers(query: str) -> str:
    RAN.append("search")
    return json.dumps([{"id": k, "title": t} for k, (t, a) in LIBRARY.items()])

async def read_paper(paper_id: str) -> str:
    RAN.append(paper_id)
    await asyncio.sleep(0.3)
    title, abstract = LIBRARY[paper_id]
    return json.dumps({"id": paper_id, "title": title, "abstract": abstract})

def save_report(filename: str, text: str) -> str:
    RAN.append("save")
    return f"saved {len(text)} characters"

async def broken_tool(x: str) -> str:
    raise ConnectionError("database is down")

async def slow_tool(x: str) -> str:
    await asyncio.sleep(10)
    return "too late"

def tools():
    schema = {"type": "object", "properties": {}}
    return [ToolDefinition("search_papers", "", schema, search_papers),
            ToolDefinition("read_paper", "", schema, read_paper),
            ToolDefinition("save_report", "", schema, save_report, requires_approval=True),
            ToolDefinition("broken_tool", "", schema, broken_tool),
            ToolDefinition("slow_tool", "", schema, slow_tool)]

async def approve_all(tool_name, args):
    return True

4. Integration test — harness ทั้งตัวกับ mock LLM

บท: รอบที่ 1 ขอ search_papers → รอบที่ 2 ขอ read_paper สามตัวพร้อมกัน → รอบที่ 3 ตอบ

llm = MockLLM([
    reply(calls=[call("search_papers", {"query": "time series"})]),
    reply(calls=[call("read_paper", {"paper_id": p}) for p in ("P1", "P2", "P3")]),
    reply(text="PatchTST [P2] splits each series into patches."),
])

harness = AgentHarness("You are a research assistant.", tools(), client=llm)
t0 = time.monotonic()
answer = await harness.run("Find papers on time series")
elapsed = time.monotonic() - t0

# ✏️ TODO 2 (▶ วิดีโอ 4:01): ตรวจว่า mock LLM ถูกเรียกครบ 3 ครั้ง (ดูจาก llm.requests)

check("the answer is the scripted text", answer == "PatchTST [P2] splits each series into patches.")
check("the model was called 3 times", ___)
check("3 reads ran at once (< 0.5 s)", elapsed < 0.5)
sent = llm.requests[-1]
call_ids = {tc["id"] for m in sent if m.get("tool_calls") for tc in m["tool_calls"]}
check("every tool result answers a real call", all(m["tool_call_id"] in call_ids for m in sent if m["role"] == "tool"))
print([m["role"] for m in sent], f"{elapsed * 1000:.0f} ms")
llm = MockLLM([
    reply(calls=[call("search_papers", {"query": "time series"})]),
    reply(calls=[call("read_paper", {"paper_id": p}) for p in ("P1", "P2", "P3")]),
    reply(text="PatchTST [P2] splits each series into patches."),
])

harness = AgentHarness("You are a research assistant.", tools(), client=llm)
t0 = time.monotonic()
answer = await harness.run("Find papers on time series")
elapsed = time.monotonic() - t0

check("the answer is the scripted text", answer == "PatchTST [P2] splits each series into patches.")
check("the model was called 3 times", len(llm.requests) == 3)
check("3 reads ran at once (< 0.5 s)", elapsed < 0.5)
sent = llm.requests[-1]
call_ids = {tc["id"] for m in sent if m.get("tool_calls") for tc in m["tool_calls"]}
check("every tool result answers a real call", all(m["tool_call_id"] in call_ids for m in sent if m["role"] == "tool"))
print([m["role"] for m in sent], f"{elapsed * 1000:.0f} ms")
[1758db0d] Starting run: Find papers on time series
[1758db0d] Tool call: search_papers({'query': 'time series'})
[1758db0d] 1 tool(s) done in 0.0s
[1758db0d] Tool call: read_paper({'paper_id': 'P1'})
[1758db0d] Tool call: read_paper({'paper_id': 'P2'})
[1758db0d] Tool call: read_paper({'paper_id': 'P3'})
[1758db0d] 3 tool(s) done in 0.3s
[1758db0d] Done in 3 iters, 0.31s

✅ the answer is the scripted text
✅ the model was called 3 times
✅ 3 reads ran at once (< 0.5 s)
✅ every tool result answers a real call
['system', 'user', 'assistant', 'tool', 'assistant', 'tool', 'tool', 'tool'] 309 ms

5. Unit test — ทีละชิ้น

  1. ContextManager ที่ context เล็กมาก (400 token → งบประวัติ 200) — ตัดแล้ว ข้อความแรกยังอยู่ไหม มีผลของ tool ที่ไม่มีคำขอเหลือไหม
  2. LoopDetector — argument ชุดเดียวกันแต่สลับลำดับ key · คำค้นที่เรียบเรียงใหม่ (ตำราบอกว่าจับ “near-repeats” ได้ด้วย)
  3. ToolExecutor._truncate — ข้อความยาว 5,000 token
cm = ContextManager(max_tokens=400)
cm.add_message(Message(Role.USER, "question"))
cm.add_message(Message(Role.ASSISTANT, "", tool_calls=[{"id": "a"}, {"id": "b"}]))
cm.add_message(Message(Role.TOOL, "word " * 60, tool_call_id="a"))
cm.add_message(Message(Role.TOOL, "word " * 60, tool_call_id="b"))
cm.add_message(Message(Role.ASSISTANT, "", tool_calls=[{"id": "c"}]))
cm.add_message(Message(Role.TOOL, "word " * 60, tool_call_id="c"))

# ✏️ TODO 3 (▶ วิดีโอ 4:53): ตรวจว่าข้อความที่สองในประวัติไม่ใช่ role TOOL

print([m.role.value for m in cm.history], cm.total_history_tokens(), "/", cm.history_budget())
check("the first message is kept", cm.history[0].content == "question")
check("no tool result without its call", ___)
cm = ContextManager(max_tokens=400)
cm.add_message(Message(Role.USER, "question"))
cm.add_message(Message(Role.ASSISTANT, "", tool_calls=[{"id": "a"}, {"id": "b"}]))
cm.add_message(Message(Role.TOOL, "word " * 60, tool_call_id="a"))
cm.add_message(Message(Role.TOOL, "word " * 60, tool_call_id="b"))
cm.add_message(Message(Role.ASSISTANT, "", tool_calls=[{"id": "c"}]))
cm.add_message(Message(Role.TOOL, "word " * 60, tool_call_id="c"))

print([m.role.value for m in cm.history], cm.total_history_tokens(), "/", cm.history_budget())
check("the first message is kept", cm.history[0].content == "question")
check("no tool result without its call", cm.history[1].role != Role.TOOL)
['user', 'assistant', 'tool'] 74 / 200
✅ the first message is kept
✅ no tool result without its call
ld = LoopDetector()
first = ld.record("search_papers", {"query": "time series transformer", "max_results": 3})
again = ld.record("search_papers", {"max_results": 3, "query": "time series transformer"})
check("same args, keys in another order → loop", (first, again) == (False, True))

ld = LoopDetector()
ld.record("search_papers", {"query": "time series transformer"})
reworded = ld.record("search_papers", {"query": "transformers for time series"})
print("reworded query → loop?", reworded)
Loop detected: search_papers called 2 times

✅ same args, keys in another order → loop
reworded query → loop? False
cut = ToolExecutor([])._truncate("token " * 5000)
print(count_tokens(cut), "tokens ·", repr(cut[-30:]))
check("cut to about 2,000 tokens, with a marker", cut.endswith("[... output truncated ...]") and count_tokens(cut) < 2020)
2006 tokens · 'ken\n[... output truncated ...]'
✅ cut to about 2,000 tokens, with a marker

6. Adversarial test — จงใจส่งของพังเข้าไป

ตำรา: “deliberately inject malformed tool outputs and verify graceful failure” — harness ต้องล้มอย่างสุภาพ ไม่ใช่ล่ม

ของพัง คาดว่า
model ขอ tool ที่ไม่มีอยู่ ได้ข้อความ error · งานจบได้
tool โยน error ทุกครั้ง ลองใหม่ 3 ครั้ง แล้วส่ง error ให้ model
tool ค้าง timeout · ลองใหม่ · ส่ง error
argument เป็น JSON ไม่ครบ ?
คำขอเดิมสองรอบ LoopDetector หยุด — แต่ tool ถูกรันกี่ครั้ง?
llm = MockLLM([reply(calls=[call("delete_everything", {})]), reply(text="Sorry, I can't do that.")])
answer = await AgentHarness("sys", tools(), client=llm).run("clean up")
tool_msg = next(m["content"] for m in llm.requests[-1] if m["role"] == "tool")
print(tool_msg)
check("unknown tool → error text, and the run finishes", tool_msg.startswith("Error: unknown tool") and answer == "Sorry, I can't do that.")
[f2857ed7] Starting run: clean up
[f2857ed7] Tool call: delete_everything({})
[f2857ed7] 1 tool(s) done in 0.0s
[f2857ed7] Done in 2 iters, 0.00s

Error: unknown tool 'delete_everything'
✅ unknown tool → error text, and the run finishes
llm = MockLLM([reply(calls=[call("broken_tool", {"x": "1"})]), reply(text="The database is down.")])
t0 = time.monotonic()
await AgentHarness("sys", tools(), client=llm).run("x")
tool_msg = next(m["content"] for m in llm.requests[-1] if m["role"] == "tool")
print(tool_msg, f"· {time.monotonic() - t0:.1f} s")
[cc5549a4] Starting run: x
[cc5549a4] Tool call: broken_tool({'x': '1'})
Tool broken_tool error: database is down
Tool broken_tool error: database is down
Tool broken_tool error: database is down
[cc5549a4] 1 tool(s) done in 3.0s
[cc5549a4] Done in 2 iters, 3.01s

Error: database is down · 3.0 s
ToolExecutor.TIMEOUT = 0.5  # a short limit, just for this test
llm = MockLLM([reply(calls=[call("slow_tool", {"x": "1"})]), reply(text="It timed out.")])
t0 = time.monotonic()
await AgentHarness("sys", tools(), client=llm).run("x")
ToolExecutor.TIMEOUT = 30.0
tool_msg = next(m["content"] for m in llm.requests[-1] if m["role"] == "tool")
print(tool_msg, f"· {time.monotonic() - t0:.1f} s")
[d08bc336] Starting run: x
[d08bc336] Tool call: slow_tool({'x': '1'})
Tool slow_tool timed out (attempt 1)
Tool slow_tool timed out (attempt 2)
Tool slow_tool timed out (attempt 3)
[d08bc336] 1 tool(s) done in 4.5s
[d08bc336] Done in 2 iters, 4.51s

Error: tool 'slow_tool' timed out · 4.5 s
llm = MockLLM([reply(calls=[call("search_papers", '{"query": ')]), reply(text="ok")])
try:
    print(await AgentHarness("sys", tools(), client=llm).run("x"))
except Exception as e:
    print("💥 the harness crashed:", type(e).__name__, "-", e)
[b7d55a3f] Starting run: x
[b7d55a3f] Tool call: search_papers({})
Tool search_papers error: search_papers() missing 1 required positional argument: 'query'
Tool search_papers error: search_papers() missing 1 required positional argument: 'query'
Tool search_papers error: search_papers() missing 1 required positional argument: 'query'
[b7d55a3f] 1 tool(s) done in 3.0s

💥 the harness crashed: JSONDecodeError - Expecting value: line 1 column 11 (char 10)
# ✏️ TODO 4 (▶ วิดีโอ 8:10): ถ้า tc.function.arguments แปลงเป็น JSON ไม่ได้ ให้แทนด้วย "{}"
class SaferHarness(AgentHarness):
    async def _execute_tool_calls(self, tool_calls, run_id):
        for tc in tool_calls:
            try:
                json.loads(tc.function.arguments)
            except json.JSONDecodeError:
                ___
        return await super()._execute_tool_calls(tool_calls, run_id)

llm = MockLLM([reply(calls=[call("search_papers", '{"query": ')]), reply(text="ok")])
print(await SaferHarness("sys", tools(), client=llm).run("x"))
print(next(m["content"] for m in llm.requests[-1] if m["role"] == "tool"))
class SaferHarness(AgentHarness):
    async def _execute_tool_calls(self, tool_calls, run_id):
        for tc in tool_calls:
            try:
                json.loads(tc.function.arguments)
            except json.JSONDecodeError:
                tc.function.arguments = "{}"
        return await super()._execute_tool_calls(tool_calls, run_id)

llm = MockLLM([reply(calls=[call("search_papers", '{"query": ')]), reply(text="ok")])
print(await SaferHarness("sys", tools(), client=llm).run("x"))
print(next(m["content"] for m in llm.requests[-1] if m["role"] == "tool"))
[a3d1b778] Starting run: x
[a3d1b778] Tool call: search_papers({})
Tool search_papers error: search_papers() missing 1 required positional argument: 'query'
Tool search_papers error: search_papers() missing 1 required positional argument: 'query'
Tool search_papers error: search_papers() missing 1 required positional argument: 'query'
[a3d1b778] 1 tool(s) done in 3.0s
[a3d1b778] Done in 2 iters, 3.01s

ok
Error: search_papers() missing 1 required positional argument: 'query'
# ✏️ TODO 5 (▶ วิดีโอ 8:48): นับว่า save_report ถูกรันจริงกี่ครั้ง (ดูจาก RAN)
RAN.clear()
same = {"filename": "report.md", "text": "draft"}
llm = MockLLM([reply(calls=[call("save_report", same, id="c1")]),
               reply(calls=[call("save_report", same, id="c2")]),
               reply(text="done")])
print(await AgentHarness("sys", tools(), approval_cb=approve_all, client=llm).run("x"))
print("save_report ran", ___, "times")
RAN.clear()
same = {"filename": "report.md", "text": "draft"}
llm = MockLLM([reply(calls=[call("save_report", same, id="c1")]),
               reply(calls=[call("save_report", same, id="c2")]),
               reply(text="done")])
print(await AgentHarness("sys", tools(), approval_cb=approve_all, client=llm).run("x"))
print("save_report ran", RAN.count("save"), "times")
[e8c197d9] Starting run: x
[e8c197d9] Tool call: save_report({'filename': 'report.md', 'text': 'draft'})
[e8c197d9] 1 tool(s) done in 0.0s
[e8c197d9] Tool call: save_report({'filename': 'report.md', 'text': 'draft'})
[e8c197d9] 1 tool(s) done in 0.0s
Loop detected: save_report called 2 times

I seem to be stuck in a loop. Please clarify your request.
save_report ran 2 times

สรุป

วิธี ที่เราเห็นในแล็บ
mock LLM harness ทั้งตัวผ่าน 4 ข้อในไม่ถึงครึ่งวินาที ไม่เสียเงิน
unit test ตัดประวัติแล้วไม่มีผลของ tool ค้าง · สลับลำดับ key ยังจับวนได้ · คำค้นที่เรียบเรียงใหม่ จับไม่ได้ · ตัด output เหลือ 2,000 token
adversarial tool ไม่มีอยู่ / พัง / ค้าง → ล้มอย่างสุภาพ · JSON ไม่ครบ → harness ล่ม (แก้ด้วย SaferHarness) · คำขอซ้ำ → tool ถูกรัน 2 ครั้ง ก่อนถูกหยุด

แบบฝึกหัด

  1. แก้ run() ให้ตรวจ LoopDetector ก่อน เรียก _execute_tool_calls แล้วรันข้อสุดท้ายอีกครั้ง — save_report ควรถูกรันแค่ 1 ครั้ง
  2. ให้ ToolExecutor ไม่ลองใหม่เมื่อ error เป็น TypeError หรือ KeyError (ลองกี่ครั้งก็ได้ผลเดิม) — ข้อ JSON ไม่ครบ ควรเหลือไม่ถึง 1 วินาที

ถัดไป — Lab 3: prompt คือ code — เก็บ system prompt เป็นเวอร์ชัน แล้วเล่นงานเดิมซ้ำกับ model จริง เทียบ v1 กับ v2