Lab 3 — เมื่อทุกอย่างพัง
Lab walkthrough · EP08 Tools, State and Error Handling
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP08 Tools, State and Error Handling
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
จากคลิปทฤษฎี (§18.7): retry แบบ exponential backoff + jitter, fallback model, loop detection และ graceful failure ใน EP06 Lab 1 เรา retry แบบรอ 1 แล้ว 2 วินาที — lab นี้ใช้สูตรเต็มของตำรา
สิ่งที่จะได้เรียน
- สูตร backoff (สมการ 18.14) และ retry กับ API ที่ตอบ 429
- ทำไมต้องมี jitter: agent สิบตัวที่โดนจำกัดพร้อมกัน
- fallback model: model หลักใช้ไม่ได้ → สลับไปตัวสำรอง
- agent ที่ติดวนเรียก tool เดิมซ้ำ → จับด้วย hash ในหน้าต่างเลื่อน (สมการ 18.15) แล้วหยุดอย่างมีมารยาท
API ที่ตอบ 429, model หลักที่ล่ม และ PDF ที่แปลงไม่เสร็จ เป็น ความล้มเหลวจำลองเพื่อการสอน ส่วนการเรียก tool ซ้ำของ model และคำตอบทั้งหมดมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §18.7 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | ใช้ key เดียวกับ Lab 1 (lab นี้ใช้ไม่ถึง 1 เซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv |
วิธีใส่ key และเหตุผลที่เลือก model กับ provider อยู่ใน Lab 1
%pip install -q "openai>=1.50" python-dotenvimport hashlib, json, os, random, time
from collections import deque
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 = {"reasoning": {"enabled": False}, "provider": {"order": ["makora"], "allow_fallbacks": False}}
USAGE = {"calls": 0, "in": 0, "out": 0}1. Exponential backoff + jitter (สมการ 18.14)
\[t_k = \min\left(2^k \cdot t_0 + U(0, t_0),\ t_{max}\right)\]
k = retry ครั้งที่เท่าไร (เริ่ม 0) · \(t_0\) = เวลารอตั้งต้น · \(U(0, t_0)\) = ค่าสุ่ม (jitter) · \(t_{max}\) = เพดาน · lab นี้ใช้ \(t_0\) = 0.5 วินาที ให้รันไม่นาน
# ✏️ TODO 1 (▶ วิดีโอ 1:06): เขียนสมการ 18.14: 2^k · t0 + ค่าสุ่ม แต่ไม่เกิน t_max
def backoff_delay(k, t0=0.5, t_max=8.0, jitter=True):
extra = random.uniform(0, t0) if jitter else 0
return ___def backoff_delay(k, t0=0.5, t_max=8.0, jitter=True):
extra = random.uniform(0, t0) if jitter else 0
return min(2 ** k * t0 + extra, t_max)class RateLimited(Exception):
pass
TRANSIENT = (RateLimited, ConnectionError, TimeoutError)
# ✏️ TODO 2 (▶ วิดีโอ 1:40): เมื่อได้ error ชั่วคราว ให้รอตาม backoff_delay(k) ก่อนลองใหม่
def call_with_retry(fn, retries=4):
for k in range(retries + 1):
try:
return fn()
except TRANSIENT as e:
if k == retries:
raise
wait = ___
print(f" retry {k}: {type(e).__name__} → wait {wait:.2f} s")
time.sleep(wait)class RateLimited(Exception):
pass
TRANSIENT = (RateLimited, ConnectionError, TimeoutError)
def call_with_retry(fn, retries=4):
for k in range(retries + 1):
try:
return fn()
except TRANSIENT as e:
if k == retries:
raise
wait = backoff_delay(k)
print(f" retry {k}: {type(e).__name__} → wait {wait:.2f} s")
time.sleep(wait)BUSY = {"left": 3}
def search_api():
if BUSY["left"] > 0:
BUSY["left"] -= 1
raise RateLimited("429 too many requests")
return ["Informer (2021)", "PatchTST (2023)", "TimesFM (2024)"]
t0 = time.time()
print(call_with_retry(search_api), f"after {time.time() - t0:.1f} s") retry 0: RateLimited → wait 0.75 s
retry 1: RateLimited → wait 1.28 s
retry 2: RateLimited → wait 2.40 s
['Informer (2021)', 'PatchTST (2023)', 'TimesFM (2024)'] after 4.4 s
2. ทำไมต้องมี jitter
agent สิบตัวใช้ key เดียวกัน และโดน 429 พร้อมกัน ที่เวลา 0 — แต่ละตัวจะกลับมาลองใหม่เมื่อไร
def retry_times(jitter, agents=10, retries=3):
times = []
for _ in range(agents):
t, mine = 0.0, []
for k in range(retries):
t += backoff_delay(k, jitter=jitter)
mine.append(round(t, 2))
times.append(mine)
return times
random.seed(0)
for jitter in (False, True):
first = sorted(t[0] for t in retry_times(jitter))
print(f"jitter={jitter!s:5} 1st retry of the 10 agents: {first}")jitter=False 1st retry of the 10 agents: [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5]
jitter=True 1st retry of the 10 agents: [0.63, 0.63, 0.64, 0.74, 0.79, 0.81, 0.86, 0.89, 0.91, 0.92]
3. Fallback model
ตำรา §18.7.1: model หลักใช้ไม่ได้ → สลับไป model สำรอง ที่อาจเก่งน้อยกว่าแต่ใช้ได้
| model | provider | |
|---|---|---|
| หลัก | Gemma 4 26B | Makora |
| สำรอง | Gemma 3 12B (เล็กกว่า ถูกกว่า) | DeepInfra |
การล่มของ model หลักเป็นการจำลอง (OUTAGE) ส่วนคำตอบของ model สำรองมาจากการรันจริง
MODELS = [
("google/gemma-4-26b-a4b-it", {"order": ["makora"], "allow_fallbacks": False}), # main
("google/gemma-3-12b-it", {"order": ["deepinfra/bf16"], "allow_fallbacks": False}), # backup
]
OUTAGE = set() # models we pretend are down
def ask_model(model, provider, messages):
if model in OUTAGE:
raise ConnectionError(f"503 {model} unavailable")
reply = client.chat.completions.create(model=model, messages=messages, max_tokens=200,
extra_body={"provider": provider})
USAGE["calls"] += 1; USAGE["in"] += reply.usage.prompt_tokens; USAGE["out"] += reply.usage.completion_tokens
return reply.choices[0].message.content
# ✏️ TODO 3 (▶ วิดีโอ 3:41): ถ้า model นี้ยังพังหลัง retry ให้พิมพ์แล้วลอง model ถัดไป
def ask_with_fallback(messages):
for model, provider in MODELS:
try:
return model, call_with_retry(lambda: ask_model(model, provider, messages), retries=2)
except ___ as e:
print(f" ✖ {model}: {e} → next model")
raise RuntimeError("every model failed")MODELS = [
("google/gemma-4-26b-a4b-it", {"order": ["makora"], "allow_fallbacks": False}), # main
("google/gemma-3-12b-it", {"order": ["deepinfra/bf16"], "allow_fallbacks": False}), # backup
]
OUTAGE = set() # models we pretend are down
def ask_model(model, provider, messages):
if model in OUTAGE:
raise ConnectionError(f"503 {model} unavailable")
reply = client.chat.completions.create(model=model, messages=messages, max_tokens=200,
extra_body={"provider": provider})
USAGE["calls"] += 1; USAGE["in"] += reply.usage.prompt_tokens; USAGE["out"] += reply.usage.completion_tokens
return reply.choices[0].message.content
def ask_with_fallback(messages):
for model, provider in MODELS:
try:
return model, call_with_retry(lambda: ask_model(model, provider, messages), retries=2)
except TRANSIENT as e:
print(f" ✖ {model}: {e} → next model")
raise RuntimeError("every model failed")OUTAGE.add("google/gemma-4-26b-a4b-it")
model, answer = ask_with_fallback([{"role": "user", "content": "In one sentence: what is PatchTST?"}])
print(f"\nanswered by {model}:\n{answer}")
OUTAGE.clear() retry 0: ConnectionError → wait 0.74 s
retry 1: ConnectionError → wait 1.43 s
✖ google/gemma-4-26b-a4b-it: 503 google/gemma-4-26b-a4b-it unavailable → next model
answered by google/gemma-3-12b-it:
PatchTST is a powerful time series forecasting model that leverages the transformer architecture, breaking down time series data into patches similar to how images are processed, to capture long-range dependencies and achieve state-of-the-art forecasting accuracy.
4. agent ที่ติดวน
get_full_text จำลอง tool ที่แปลง PDF ไม่เสร็จสักที: ตอบ "processing … Call again" ทุกครั้ง agent ที่ไม่มีอะไรห้าม จะเรียกคำขอเดิมซ้ำไปเรื่อยๆ จนครบ max_steps (ตัวกันสุดท้ายตั้งแต่ EP03)
def get_full_text(paper_id):
return {"status": "processing", "message": "The PDF is still being converted. Call again to get the text."}
TOOLS = [{"type": "function", "function": {
"name": "get_full_text",
"description": "Get the full text of a paper by id. The PDF is converted on demand; if it is not ready yet, call again.",
"parameters": {"type": "object", "properties": {"paper_id": {"type": "string"}}, "required": ["paper_id"]}}}]
def chat(messages):
reply = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS, extra_body=EXTRA)
USAGE["calls"] += 1; USAGE["in"] += reply.usage.prompt_tokens; USAGE["out"] += reply.usage.completion_tokens
return reply.choices[0].messagedef run_agent(question, guard=None, max_steps=12):
messages = [{"role": "system", "content": "You are a research assistant. Use the tools to answer."},
{"role": "user", "content": question}]
for step in range(max_steps):
reply = chat(messages)
if not reply.tool_calls:
return reply.content
messages.append(reply.model_dump(exclude_none=True))
for call in reply.tool_calls:
args = json.loads(call.function.arguments)
print(f" step {step}: {call.function.name}({args})")
if guard and guard.is_loop(call.function.name, args):
return graceful_failure(guard, messages)
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(get_full_text(**args))})
return "stopped: max_steps"USAGE["calls"] = 0
print(run_agent("Get the full text of paper P3 and quote its first sentence."))
print(f"\nmodel calls: {USAGE['calls']}") step 0: get_full_text({'paper_id': 'P3'})
step 1: get_full_text({'paper_id': 'P3'})
step 2: get_full_text({'paper_id': 'P3'})
step 3: get_full_text({'paper_id': 'P3'})
step 4: get_full_text({'paper_id': 'P3'})
step 5: get_full_text({'paper_id': 'P3'})
step 6: get_full_text({'paper_id': 'P3'})
step 7: get_full_text({'paper_id': 'P3'})
step 8: get_full_text({'paper_id': 'P3'})
step 9: get_full_text({'paper_id': 'P3'})
step 10: get_full_text({'paper_id': 'P3'})
The PDF for paper P3 is still being converted. Please try your request again in a moment.
model calls: 12
class LoopGuard:
def __init__(self, window=5, k=3):
self.recent = deque(maxlen=window) # the sliding window W
self.k = k
# ✏️ TODO 4 (▶ วิดีโอ 5:48): ทำ hash ของ (tool, args) ใส่หน้าต่าง แล้วคืน True ถ้าซ้ำถึง k ครั้ง
def is_loop(self, tool, args):
h = hashlib.sha256(f"{tool}:{json.dumps(args, sort_keys=True)}".encode()).hexdigest()[:8]
self.recent.append(h)
return ___class LoopGuard:
def __init__(self, window=5, k=3):
self.recent = deque(maxlen=window) # the sliding window W
self.k = k
def is_loop(self, tool, args):
h = hashlib.sha256(f"{tool}:{json.dumps(args, sort_keys=True)}".encode()).hexdigest()[:8]
self.recent.append(h)
return self.recent.count(h) >= self.kdef graceful_failure(guard, messages):
with open("stuck_task.json", "w") as f:
json.dump(messages, f)
return ("✅ Done: asked for the full text of P3 (the request is valid).\n"
f"✖ Why: get_full_text answered 'processing' {guard.k} times in a row — I stopped repeating it.\n"
"➜ Next: try again in a few minutes, or use the abstract instead.\n"
"💾 State saved to stuck_task.json — the task can resume from here.")USAGE["calls"] = 0
print(run_agent("Get the full text of paper P3 and quote its first sentence.", guard=LoopGuard()))
print(f"\nmodel calls: {USAGE['calls']}") step 0: get_full_text({'paper_id': 'P3'})
step 1: get_full_text({'paper_id': 'P3'})
step 2: get_full_text({'paper_id': 'P3'})
✅ Done: asked for the full text of P3 (the request is valid).
✖ Why: get_full_text answered 'processing' 3 times in a row — I stopped repeating it.
➜ Next: try again in a few minutes, or use the abstract instead.
💾 State saved to stuck_task.json — the task can resume from here.
model calls: 3
cost = USAGE["in"] / 1e6 * 0.09 + USAGE["out"] / 1e6 * 0.28
print(f"≈ ${cost:.4f} for the whole lab (Makora prices; the backup model costs less)")≈ $0.0006 for the whole lab (Makora prices; the backup model costs less)
สรุป
| สิ่งที่ harness ทำ | ที่เราเห็นใน lab |
|---|---|
| exponential backoff | รอ ~0.5 → ~1 → ~2 วินาที แล้วครั้งที่สี่ได้ผล |
| jitter | ไม่มี: agent ทั้งสิบกลับมาที่ 0.5 วินาทีพร้อมกัน · มี: กระจายทั่ว 0.5–1 วินาที |
| fallback model | model หลักล่ม → ลอง 3 ครั้ง → Gemma 3 12B ตอบแทน |
| loop detection | ไม่มี guard: เรียกคำขอเดิมซ้ำหลายรอบ · มี guard: หยุดที่ 3 ครั้ง |
| graceful failure | ทำอะไรแล้ว · ทำไมหยุด · ทำอะไรต่อ · state ถูกบันทึก |
แบบฝึกหัด
- ลอง LoopGuard กับ
search_papersที่ตอบ “No results” ทุกครั้ง — model เปลี่ยนคำค้นทุกรอบ hash จึงไม่ซ้ำ จะจับการวนแบบนี้อย่างไร (คำใบ้: วิธีที่สามของตำรา — ดูว่า state เปลี่ยนไหม แทนการดู argument) - ให้ทั้งสอง model อยู่ใน
OUTAGE—ask_with_fallbackทำอะไร และ harness ควรบอกผู้ใช้อย่างไร
ถัดไป — Lab 4: ค่าใช้จ่ายต่องาน และดู prompt caching ทำงานจริงผ่าน cached_tokens