Lab 1 — สร้าง harness ทั้งไฟล์
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 ด้วย Listing 18.1 — harness เต็มชุดในไฟล์เดียว (§18.10) แล็บนี้เราเขียนมันทีละ class ให้ research assistant ของเรา แล้วรันงานจริง
สิ่งที่จะได้เขียน
- ข้อมูลสองชนิด:
MessageและToolDefinition ContextManager— งบห้าช่อง ตรวจทุกครั้งที่เพิ่มข้อความ และ preflight checkToolExecutor— approval gate, timeout + retry, ตัด outputLoopDetector— hash ของการกระทำในหน้าต่าง 5 ครั้งAgentHarness— ลูป ReAct ที่มีrun_idในทุกบรรทัดของ log- รันงานจริงสองรอบ: อนุมัติ การบันทึกรายงาน กับ ไม่อนุมัติ
ต่างจากตำราสองจุด: เรานับ token ด้วย tokenizer ของ Gemma (ไม่ใช่ tiktoken ของ GPT-4o — ตามที่ EP07 สอน) และเพิ่มตัวนับ token กับ log บรรทัดเดียวที่บอกว่า tool ใช้เวลาเท่าไร
คลัง paper และ tool เป็น ข้อมูลจำลองที่เขียนขึ้นเพื่อการสอน ส่วน tool call และคำตอบของ model มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §18.10 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv, tokenizers (ติดตั้งใน 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 "tokenizers==0.23.3"1. Model, provider และ log
ทำไมใช้ google/gemma-4-26b-a4b-it — เรียก tool ได้ และ ขอหลาย tool ในรอบเดียวได้ ซึ่ง harness ของตำรารันพร้อมกันด้วย asyncio.gather tokenizer ก็เปิดให้โหลด เราจึงนับ token บนเครื่องได้ตรงกับที่ model นับ
ทำไมล็อก provider เป็น Makora — เจ้าเดียวกับ EP08 ทดสอบซ้ำ 2026-11-17: เรียก tool ได้ และขอ read_paper สามตัวในรอบเดียวทุกครั้ง มีบางครั้งที่ตอบ 429 (ส่งคำขอถี่เกิน) เราจึงให้ client ลองใหม่เองได้ถึง 5 ครั้ง
ไม่ฟรี แต่ถูกมาก: 0.09 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.28 ต่อล้าน token ขาออก — ท้าย lab เรารวมค่าใช้จ่ายจริงให้ดู · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-17: 2 ใน 3 ครั้งได้ 429 “rate-limited upstream” และอีกครั้งตอบเองโดยไม่เรียก tool)
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
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"]MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False},
"provider": {"order": ["makora"], "allow_fallbacks": False}}
client = AsyncOpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5)
tok = Tokenizer.from_pretrained(MODEL)
logging.basicConfig(level=logging.WARNING, format="%(message)s", force=True)
logger = logging.getLogger("agent_harness")
logger.setLevel(logging.INFO)Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.
2. ข้อมูลสองชนิด: Message และ ToolDefinition
Message— ทุกอย่างที่คุยกับ model มี role สี่แบบ ข้อความของ tool มีtool_call_idบอกว่าเป็นผลของคำขอไหน (EP08)ToolDefinition— บัตรประจำตัวของ tool: สามช่องส่งให้ model อ่าน อีกสองช่อง (handler,requires_approval) model ไม่เห็น
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}}3. ContextManager — ตรวจงบทุกครั้งที่เพิ่มข้อความ
| ส่วน | สัดส่วน (ตำรา) |
|---|---|
| system · memory · tools · history · reserved | 10% · 20% · 10% · 50% · 10% |
- ประวัติเกินงบ → ทิ้งข้อความที่เก่าที่สุด แต่เก็บข้อความแรกไว้เสมอ และถ้าทิ้งคำขอเรียก tool ต้องทิ้งผลของ tool ที่ตามมาด้วย
- preflight check ก่อนเรียก model ทุกครั้ง: system + tools + history ≤ ขนาด context − ส่วนที่กันไว้
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)
# ✏️ TODO 1 (▶ วิดีโอ 4:55): ถ้าข้อความที่ทิ้งมี tool_calls ให้ทิ้งข้อความ role TOOL ที่ตามมาทั้งหมด
if dropped.tool_calls:
while len(self.history) > 1 and ___:
self.history.pop(1)
# ✏️ TODO 2 (▶ วิดีโอ 5:09): เทียบ total กับ limit แล้วคืน True เมื่อยังอยู่ในงบ
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 ___
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]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]4. ToolExecutor — รัน tool อย่างไม่ไว้ใจ
สี่ขั้น: ① tool ที่ไม่มีอยู่ → error · ② ต้องอนุมัติ → ถามคน · ③ timeout + retry (รอ 1 → 2 วินาที, สูงสุด 3 ครั้ง) · ④ ตัด output ที่เกิน 2,000 token
ทุกทางออกเป็นข้อความที่ส่งกลับให้ model — ไม่มีทางไหนทำให้โปรแกรมล่ม
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}'"
# ✏️ TODO 3 (▶ วิดีโอ 6:03): ถ้า tool ต้องอนุมัติ ให้ await approval แล้วคืนข้อความปฏิเสธเมื่อคนไม่อนุมัติ
if tool.requires_approval and self.approval:
if not ___:
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 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 ...]"5. LoopDetector — ลายนิ้วมือของการกระทำ
hash ของ ชื่อ tool + argument → ดู 5 ครั้งล่าสุด → ซ้ำ 2 ครั้ง = วน
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:]
# ✏️ TODO 4 (▶ วิดีโอ 7:38): นับว่า h อยู่ใน recent กี่ครั้ง ถ้าถึง max_repeats ให้ถือว่าวน
if ___:
logger.warning("Loop detected: %s called %d times", tool_name, recent.count(h))
return True
return Falseclass 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 False6. AgentHarness — ลูป ReAct ทั้งเส้น
แต่ละรอบ: preflight → เรียก model → เก็บคำตอบ → ไม่ขอ tool แล้ว? คืนคำตอบ → รัน tool พร้อมกัน → ตรวจวน → ใส่ผลกลับ
ทางออกพิเศษสามทาง (context เต็ม · วน · ครบ 50 รอบ) จบด้วยข้อความที่บอกผู้ใช้ว่าเกิดอะไรขึ้น · ทุกบรรทัดของ log มี run_id
class AgentHarness:
MAX_ITERATIONS = 50
def __init__(self, system_prompt: str, tools: list[ToolDefinition],
max_tokens: int = 256_000, approval_cb: Optional[Callable] = None):
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 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))
# ✏️ TODO 5 (▶ วิดีโอ 9:04): จบลูปเมื่อ finish เป็น stop หรือ model ไม่ได้ขอ tool
if ___:
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)
# ✏️ TODO 6 (▶ วิดีโอ 9:58): รันงานทั้งหมดพร้อมกันด้วย asyncio.gather โดยไม่ให้ error ของงานหนึ่งทำให้งานอื่นพัง
t0 = time.monotonic()
results = ___
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)}class AgentHarness:
MAX_ITERATIONS = 50
def __init__(self, system_prompt: str, tools: list[ToolDefinition],
max_tokens: int = 256_000, approval_cb: Optional[Callable] = None):
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 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)}7. tool สามตัวของ research assistant
| tool | ทำอะไร | ต้องอนุมัติ |
|---|---|---|
search_papers |
ค้นคลัง paper จำลอง คืน id + ชื่อ (รอ 0.5 วินาที) | ไม่ |
read_paper |
อ่านบทคัดย่อตาม id (รอ 1.5 วินาที เหมือน API ที่ช้า) | ไม่ |
save_report |
บันทึกรายงาน (จำลอง: เก็บไว้ใน dict ไม่ได้เขียนไฟล์จริง) | ใช่ 🔒 |
LIBRARY = {
"P1": ("Informer (2021)", "ProbSparse self-attention makes long-sequence time-series forecasting faster."),
"P2": ("PatchTST (2023)", "Splits each series into patches of 16 steps; each channel is handled on its own."),
"P3": ("TimesFM (2024)", "A decoder-only foundation model that forecasts new series zero-shot."),
"P4": ("Autoformer (2021)", "Replaces attention with auto-correlation and decomposes trend and season."),
"P5": ("DLinear (2023)", "A single linear layer that beats many transformers on long-term forecasting."),
"P6": ("BERT (2019)", "Pre-trains a bidirectional transformer on text with masked language modelling."),
}
SAVED = {} # the simulated diskasync def search_papers(query: str, max_results: int = 3) -> str:
await asyncio.sleep(0.5)
words = [w.rstrip("s") for w in query.lower().replace("-", " ").split() if len(w) > 3]
hits = [(pid, t) for pid, (t, a) in LIBRARY.items() if any(w in (t + " " + a).lower() for w in words)]
return json.dumps([{"id": pid, "title": t} for pid, t in hits[:max_results]])
async def read_paper(paper_id: str) -> str:
await asyncio.sleep(1.5)
title, abstract = LIBRARY[paper_id]
return json.dumps({"id": paper_id, "title": title, "abstract": abstract})
def save_report(filename: str, text: str) -> str:
SAVED[filename] = text
return f"saved {len(text)} characters to {filename}"
TOOLS = [
ToolDefinition("search_papers", "Search the paper library. Returns ids and titles.",
{"type": "object", "properties": {"query": {"type": "string"},
"max_results": {"type": "integer", "default": 3}}, "required": ["query"]}, search_papers),
ToolDefinition("read_paper", "Read one paper's abstract by its id (P1, P2, ...).",
{"type": "object", "properties": {"paper_id": {"type": "string"}}, "required": ["paper_id"]}, read_paper),
ToolDefinition("save_report", "Save a finished report to a file.",
{"type": "object", "properties": {"filename": {"type": "string"}, "text": {"type": "string"}},
"required": ["filename", "text"]}, save_report, requires_approval=True),
]8. รันงานจริง — รอบที่ 1: อนุมัติ ✅
ในแอปจริง approval callback จะถามคน (เช่น input() หรือปุ่มบนหน้าเว็บ) ในแล็บนี้เราส่งคำตอบเข้าไปล่วงหน้า เพื่อให้รันซ้ำได้
SYSTEM = ("You are a research assistant for a university course. Use the tools to find and read papers "
"before answering. When you need several papers, request them all in the same turn. "
"Always cite paper ids like [P2].")
TASK = ("Find papers on transformers for time-series forecasting, read the three most relevant ones, "
"and save a short report to report.md.")
def make_approver(decision: bool):
async def approve(tool_name: str, args: dict) -> bool:
print(f"🔒 approval needed: {tool_name}(filename={args.get('filename')!r}, "
f"text={len(args.get('text', ''))} chars) → {'✅ yes' if decision else '❌ no'}")
return decision
return approve
harness = AgentHarness(SYSTEM, TOOLS, approval_cb=make_approver(True))
answer = await harness.run(TASK)
print("\nANSWER:", answer)
print("\nsaved:", list(SAVED), "· usage:", harness.usage)[2440b2a5] Starting run: Find papers on transformers for time-series forecasting, read the three most rel
[2440b2a5] Tool call: search_papers({'query': 'transformers for time-series forecasting'})
[2440b2a5] 1 tool(s) done in 0.5s
[2440b2a5] Tool call: read_paper({'paper_id': 'P1'})
[2440b2a5] Tool call: read_paper({'paper_id': 'P2'})
[2440b2a5] Tool call: read_paper({'paper_id': 'P3'})
[2440b2a5] 3 tool(s) done in 1.5s
[2440b2a5] Tool call: save_report({'filename': 'report.md', 'text': '# Report: Transformers for Time-Series Forecasting\n\nThis report summarizes three key advancements in using Transformer architectures for time-series forecasting.\n\n## Summary of Key Papers\n\n### 1. Informer (2021) [P1]\nThe Informer model introduces the **ProbSparse self-attention** mechanism. This innovation addresses the quadratic complexity of standard self-attention, making long-sequence time-series forecasting significantly more efficient and faster.\n\n### 2. PatchTST (2023) [P2]\nPatchTST improves forecasting performance by adopting a **patching mechanism**. Instead of looking at individual time steps, it splits each series into patches (e.g., 16 steps). This approach allows the model to capture local semantic information and handles each channel independently, leading to better temporal dependency modeling.\n\n### 3. TimesFM (2024) [P3]\nTimesFM represents a shift towards **foundation models** for time series. It is a decoder-only architecture designed to perform **zero-shot forecasting**, meaning it can forecast new, unseen time series without requiring task-specific fine-tuning.\n\n## Conclusion\nThe evolution of Transformers in time-series forecasting has moved from optimizing attention mechanisms for efficiency (Informer), to improving feature representation through patching (PatchTST), and finally towards large-scale foundation models capable of zero-shot generalization (TimesFM).'})
[2440b2a5] 1 tool(s) done in 0.0s
🔒 approval needed: save_report(filename='report.md', text=1404 chars) → ✅ yes
[2440b2a5] Done in 4 iters, 7.59s
ANSWER: I have completed the research. I searched for papers on transformers for time-series forecasting, selected the three most relevant ones (Informer, PatchTST, and TimesFM), read their abstracts, and compiled a summary report.
The report has been saved to `report.md`.
### Summary of Findings:
* **Informer [P1]**: Introduced ProbSparse self-attention to reduce the computational complexity of long-sequence forecasting.
* **PatchTST [P2]**: Utilizes a patching mechanism to capture local semantic information and improve temporal dependency modeling.
* **TimesFM [P3]**: A modern decoder-only foundation model capable of zero-shot forecasting on unseen time series.
saved: ['report.md'] · usage: {'in': 2101, 'out': 530}
print(SAVED["report.md"][:600])# Report: Transformers for Time-Series Forecasting
This report summarizes three key advancements in using Transformer architectures for time-series forecasting.
## Summary of Key Papers
### 1. Informer (2021) [P1]
The Informer model introduces the **ProbSparse self-attention** mechanism. This innovation addresses the quadratic complexity of standard self-attention, making long-sequence time-series forecasting significantly more efficient and faster.
### 2. PatchTST (2023) [P2]
PatchTST improves forecasting performance by adopting a **patching mechanism**. Instead of looking at individual t
9. รอบที่ 2: ไม่อนุมัติ ❌
งานเดิม แต่คราวนี้เราตอบ ไม่ — save_report จะไม่ถูกรัน model ได้แค่ข้อความ “Action rejected by human reviewer.” แล้วมันทำอะไรต่อ?
SAVED.clear()
harness = AgentHarness(SYSTEM, TOOLS, approval_cb=make_approver(False))
answer = await harness.run(TASK)
print("\nANSWER:", answer)
print("\nsaved:", list(SAVED), "· usage:", harness.usage)[76c70c7c] Starting run: Find papers on transformers for time-series forecasting, read the three most rel
[76c70c7c] Tool call: search_papers({'query': 'transformers for time-series forecasting'})
[76c70c7c] 1 tool(s) done in 0.5s
[76c70c7c] Tool call: read_paper({'paper_id': 'P1'})
[76c70c7c] Tool call: read_paper({'paper_id': 'P2'})
[76c70c7c] Tool call: read_paper({'paper_id': 'P3'})
[76c70c7c] 3 tool(s) done in 1.5s
[76c70c7c] Tool call: save_report({'filename': 'report.md', 'text': '# Report: Transformers for Time-Series Forecasting\n\nThis report summarizes three key advancements in using Transformer architectures for time-series forecasting.\n\n## 1. Informer (2021) [P1]\nThe Informer model introduces the **ProbSparse self-attention** mechanism. This approach addresses the quadratic complexity of standard self-attention, making it significantly more efficient for long-sequence time-series forecasting tasks.\n\n## 2. PatchTST (2023) [P2]\nPatchTST improves forecasting performance by breaking down time series into **patches** (e.g., 16 steps per patch). By treating these patches as tokens and handling each channel independently, the model captures local semantic information more effectively than point-wise approaches.\n\n## 3. TimesFM (2024) [P3]\nTimesFM represents a shift towards **foundation models** for time series. It is a decoder-only model designed for **zero-shot forecasting**, meaning it can predict new, unseen time series without requiring task-specific fine-tuning.'})
[76c70c7c] 1 tool(s) done in 0.0s
🔒 approval needed: save_report(filename='report.md', text=1001 chars) → ❌ no
[76c70c7c] Tool call: save_report({'filename': 'report.md', 'text': '# Report: Transformers for Time-Series Forecasting\n\nThis report summarizes three key advancements in using Transformer architectures for time-series forecasting.\n\n## 1. Informer (2021) [P1]\nThe Informer model introduces the **ProbSparse self-attention** mechanism. This approach addresses the quadratic complexity of standard self-attention, making it significantly more efficient for long-sequence time-series forecasting tasks.\n\n## 2. PatchTST (2023) [P2]\nPatchTST improves forecasting performance by breaking down time series into **patches** (e.g., 16 steps per patch). By treating these patches as tokens and handling each channel independently, the model captures local semantic information more effectively than point-wise approaches.\n\n## 3. TimesFM (2024) [P3]\nTimesFM represents a shift towards **foundation models** for time series. It is a decoder-only model designed for **zero-shot forecasting**, meaning it can predict new, unseen time series without requiring task-specific fine-tuning.'})
[76c70c7c] 1 tool(s) done in 0.0s
Loop detected: save_report called 2 times
🔒 approval needed: save_report(filename='report.md', text=1001 chars) → ❌ no
ANSWER: I seem to be stuck in a loop. Please clarify your request.
saved: [] · usage: {'in': 2029, 'out': 558}
cost = harness.usage["in"] / 1e6 * 0.09 + harness.usage["out"] / 1e6 * 0.28
print(f"run 2: {harness.usage['in']:,} input + {harness.usage['out']:,} output tokens ≈ ${cost:.5f}")run 2: 2,029 input + 558 output tokens ≈ $0.00034
สรุป
| ชิ้นของ harness | ที่เราเห็นใน lab |
|---|---|
ContextManager |
ตรวจงบทุก add_message · ถ้าทิ้งคำขอเรียก tool ผลของ tool ออกไปด้วย · preflight ก่อนเรียก model ทุกครั้ง |
ToolExecutor |
save_report ต้องอนุมัติ: อนุมัติ → บันทึก · ไม่อนุมัติ → tool ไม่ถูกรันเลย |
| parallel tool calls | read_paper สามเรื่องในรอบเดียว เสร็จพร้อมกันในราว 1.5 วินาที |
LoopDetector |
บางรอบ model ขอ save_report ซ้ำหลังถูกปฏิเสธ → ลายนิ้วมือซ้ำ → หยุด |
run_id |
ทุกบรรทัดของ log ของงานเดียวกันมี id เดียวกัน |
แบบฝึกหัด
- ลบประโยค “When you need several papers, request them all in the same turn.” ออกจาก
SYSTEMแล้วรันส่วนที่ 8 อีกครั้ง — ใช้กี่รอบ กี่วินาที - ให้ model ขอ
read_paper("P9")(ไม่มีในคลัง) —ToolExecutorลองใหม่กี่ครั้ง และใช้เวลารอเท่าไร ควรลองใหม่ไหมสำหรับ error แบบนี้
ถัดไป — Lab 2: ทดสอบ harness นี้โดยไม่เรียก model เลยสักครั้ง ด้วย mock LLM, unit test และของพังๆ ที่เราจงใจส่งเข้าไป