Lab 3 — Reflexion: เรียนรู้จากความผิดพลาดโดยไม่ต้อง train (§19.2.3)
Lab walkthrough · EP05 Autonomous Agent Patterns
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP05 Autonomous Agent Patterns
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Agent ที่ดีต้องหยุดประเมินตัวเองได้ ตำราแบ่ง reflection เป็น 3 ระดับ:
- Output validation — “ถูกไหม ลืมอะไรไหม”
- Trajectory review — ย้อนดู k ขั้นล่าสุด
- Strategy revision — “แก้ปัญหาถูกข้อไหม”
Reflexion เก็บบทเรียนจากความผิดพลาดไว้ใน reflection memory แล้วใส่ใน prompt รอบถัดไป → เรียนรู้ข้ามรอบได้ โดยไม่อัปเดต weight
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.2.3 — CC BY-SA 4.0
0. เตรียมเครื่อง
ต้องมี Python 3.10+ (หรือ Colab) และ OpenRouter API key — วิธีตั้งค่าอยู่ใน Lab 1
%pip install -q "openai>=1.50" python-dotenv# ---- จาก Lab 1: ตั้งค่า client + ask_llm ----
import os
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"}}
def ask_llm(prompt):
resp = client.chat.completions.create(model=MODEL, extra_body=EXTRA,
messages=[{"role": "user", "content": prompt}])
return resp.choices[0].message.content1. งาน + Evaluator
Agent ต้องเขียนฟังก์ชัน parse_duration() แล้ว evaluator ตรวจด้วย unit tests ที่ agent มองไม่เห็นล่วงหน้า (เหมือนงานจริงที่ requirement บางข้อไม่ได้เขียนไว้ในโจทย์)
SPEC = ("Write a Python function `parse_duration(s: str) -> float` that converts a duration "
"string like '1h30m' into minutes (e.g. '1h30m' -> 90). Return only the code in one "
"```python block, no explanation.")HIDDEN_TESTS = [
("1h30m", 90), ("2h", 120), ("45m", 45),
("90s", 1.5), # seconds
("1H 15M", 75), # uppercase + spaces
("1.5h", 90), # decimals
("1d", 1440), # days
("abc", ValueError), # invalid -> must raise ValueError
("10", ValueError), # no unit -> ambiguous -> ValueError
]def extract_code(text):
return text.split("```python")[-1].split("```")[0] if "```" in text else text# ✏️ TODO 1 (▶ วิดีโอ 2:12): รันโค้ดที่ model เขียนใน namespace ns แล้วดึงฟังก์ชัน parse_duration ออกมา
def evaluate(code_str):
ns = {}
try:
___
fn = ___
except Exception as e:
return [f"code does not run: {e}"]
failures = []
for inp, want in HIDDEN_TESTS:
expects_error = isinstance(want, type) and issubclass(want, Exception)
try:
got = fn(inp)
if expects_error:
failures.append(f"parse_duration({inp!r}) returned {got}, expected {want.__name__}")
elif abs(got - want) > 1e-9:
failures.append(f"parse_duration({inp!r}) returned {got}, expected {want}")
except Exception as e:
if not (expects_error and isinstance(e, want)):
failures.append(f"parse_duration({inp!r}) raised {type(e).__name__}: {e}")
return failuresdef evaluate(code_str):
ns = {}
try:
exec(code_str, ns)
fn = ns["parse_duration"]
except Exception as e:
return [f"code does not run: {e}"]
failures = []
for inp, want in HIDDEN_TESTS:
expects_error = isinstance(want, type) and issubclass(want, Exception)
try:
got = fn(inp)
if expects_error:
failures.append(f"parse_duration({inp!r}) returned {got}, expected {want.__name__}")
elif abs(got - want) > 1e-9:
failures.append(f"parse_duration({inp!r}) returned {got}, expected {want}")
except Exception as e:
if not (expects_error and isinstance(e, want)):
failures.append(f"parse_duration({inp!r}) raised {type(e).__name__}: {e}")
return failures2. Reflexion loop
attempt → evaluate → reflect → (บันทึกใน memory) → attempt ใหม่โดยอ่าน memory
# ✏️ TODO 2 (▶ วิดีโอ 3:33): ต่อบทเรียนทุกข้อเข้าไปใน prompt บรรทัดละข้อ ขึ้นต้นด้วย "- "
def write_code(reflections):
prompt = SPEC
if reflections:
prompt += "\n\nLessons from your previous failed attempts:\n"
prompt += ___
return extract_code(ask_llm(prompt))def write_code(reflections):
prompt = SPEC
if reflections:
prompt += "\n\nLessons from your previous failed attempts:\n"
prompt += "\n".join(f"- {r}" for r in reflections)
return extract_code(ask_llm(prompt))# ✏️ TODO 3 (▶ วิดีโอ 3:49): ส่งโค้ด + test ที่ fail ให้ model แล้วขอบทเรียน 1 ประโยค ขึ้นต้นด้วย 'I failed because'
def reflect(code_str, failures):
return ask_llm(___).strip()def reflect(code_str, failures):
return ask_llm(f"Your code:\n{code_str}\nFailed tests:\n" + "\n".join(failures) +
"\nIn ONE sentence, write a lesson for your next attempt "
"(start with 'I failed because').").strip()# ✏️ TODO 4 (▶ วิดีโอ 4:13): แต่ละรอบ: เขียนโค้ดโดยใช้ memory แล้วประเมินด้วย hidden tests
def reflexion(max_attempts=4):
memory = []
for attempt in range(1, max_attempts + 1):
code_str = ___
failures = ___
print(f"\n🧪 attempt {attempt}: {len(HIDDEN_TESTS) - len(failures)}/{len(HIDDEN_TESTS)} tests passed")
if not failures:
print("✅ all tests passed")
return code_str, memory
# ✏️ TODO 5 (▶ วิดีโอ 4:34): สะท้อนความผิดพลาดเป็นบทเรียน แล้วเก็บลง memory สำหรับรอบถัดไป
for f in failures:
print(" ❌", f)
lesson = ___
___
print(" 📝", lesson)
return code_str, memorydef reflexion(max_attempts=4):
memory = []
for attempt in range(1, max_attempts + 1):
code_str = write_code(memory)
failures = evaluate(code_str)
print(f"\n🧪 attempt {attempt}: {len(HIDDEN_TESTS) - len(failures)}/{len(HIDDEN_TESTS)} tests passed")
if not failures:
print("✅ all tests passed")
return code_str, memory
for f in failures:
print(" ❌", f)
lesson = reflect(code_str, failures)
memory.append(lesson)
print(" 📝", lesson)
return code_str, memoryfinal_code, memory = reflexion()
print("\n📓 REFLECTION MEMORY:")
for m in memory:
print(" -", m)
🧪 attempt 1: 5/9 tests passed
❌ parse_duration('1H 15M') returned 0.0, expected 75
❌ parse_duration('1d') returned 0.0, expected 1440
❌ parse_duration('abc') returned 0.0, expected ValueError
❌ parse_duration('10') returned 0.0, expected ValueError
📝 I failed because I did not account for case insensitivity, omitted the 'd' unit, and failed to validate the input to raise a ValueError for invalid or unit-less strings.
🧪 attempt 2: 9/9 tests passed
✅ all tests passed
📓 REFLECTION MEMORY:
- I failed because I did not account for case insensitivity, omitted the 'd' unit, and failed to validate the input to raise a ValueError for invalid or unit-less strings.
print(final_code)
import re
def parse_duration(s: str) -> float:
"""
Converts a duration string like '1h30m' or '2d1h' into total minutes.
Supported units: d (days), h (hours), m (minutes), s (seconds).
Raises ValueError for invalid formats or unit-less strings.
"""
s_clean = s.lower().replace(" ", "")
if not s_clean:
raise ValueError("Empty duration string")
# Pattern matches: (number including decimals) followed by (one of d, h, m, s)
# (\d+\.?\d*|\.\d+) handles formats like '1', '1.', '1.5', and '.5'
pattern = r'(\d+\.?\d*|\.\d+)([dhms])'
matches = list(re.finditer(pattern, s_clean))
if not matches:
raise ValueError("Invalid duration format or missing units")
unit_map = {
'd': 1440.0,
'h': 60.0,
'm': 1.0,
's': 1/60.0
}
total_minutes = 0.0
last_end = 0
for m in matches:
# If there is a gap between matches, the string contains invalid characters
if m.start() != last_end:
raise ValueError("Invalid duration format")
val = float(m.group(1))
unit = m.group(2)
total_minutes += val * unit_map[unit]
last_end = m.end()
# If there is leftover text after the last valid match
if last_end != len(s_clean):
raise ValueError("Invalid duration format")
return total_minutes
สรุป
| องค์ประกอบ | ในโค้ด |
|---|---|
| Evaluator | evaluate() — hidden unit tests |
| Reflection | reflect() — บทเรียน 1 ประโยค “I failed because…” |
| Reflection memory | memory — สะสมทุกรอบ ใส่ใน prompt ผ่าน write_code() |
| Guard | max_attempts |
ลองทำต่อ: เรียก write_code([]) ทุกรอบ (ไม่ใช้ memory) แล้วเทียบจำนวนรอบที่ใช้ — เห็นผลของ reflection memory ชัดเจน