Lab 4 — ประเมินแบบเดิมด้วย framework: Inspect AI
Lab walkthrough · EP17 Evaluating Agents: Metrics, Environments and LLM-as-Judge
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP17 Evaluating Agents: Metrics, Environments and LLM-as-Judge
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Lab 1–3 เราเขียนทุกชิ้นเอง: environment · harness · ตัวให้คะแนน · กรรมการ Lab นี้ใช้ Inspect AI — framework โอเพนซอร์สสำหรับประเมิน LLM และ agent ของ UK AI Security Institute — ทำงานเดิมสองชิ้น แล้วจับคู่ทุกชิ้นของ framework กับโค้ดที่เราเขียนเอง
| ที่เราเขียนเอง | Inspect AI |
|---|---|
งานหนึ่งชิ้นใน TASKS |
Sample (input · target · metadata · files) |
reset() เขียนไฟล์ลงโฟลเดอร์ |
files= + sandbox="local" |
action view · edit |
@tool: view_file · edit_file |
policy + run_episode |
react() agent |
tamper_proof_reward |
@scorer: hidden_tests |
run_suite(k=3) |
eval(..., epochs=3) |
tsr_ci · report แยกระดับ |
metric accuracy · stderr · grouped |
| บันทึก action ที่เราจดเอง | log file ของ Inspect (inspect view) |
| panel ของ Lab 3 | model_graded_qa(model=[...]) |
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §14.6–14.7, §20.7 — CC BY-SA 4.0 · Inspect AI (UK AI Security Institute) — MIT License
0. เตรียมเครื่องก่อนเริ่ม
เหมือน Lab 1: Python 3.10 ขึ้นไป (หรือ Colab) และ OpenRouter API key — วิธีตั้งค่า key อยู่ใน Lab 1 ล็อกเวอร์ชัน inspect-ai==0.3.290 (ออก 14 พ.ย. 2026) เพื่อให้ผลตรงกับวิดีโอ · lab นี้ใช้ราวหนึ่งเซ็นต์ดอลลาร์
%pip install -q "inspect-ai==0.3.290" pytest python-dotenvimport os, subprocess, sys, tempfile
import xml.etree.ElementTree as ET
from inspect_ai import Task, eval
from inspect_ai.agent import react
from inspect_ai.dataset import Sample
from inspect_ai.log import read_eval_log
from inspect_ai.model import GenerateConfig, ModelOutput, get_model
from inspect_ai.scorer import CORRECT, INCORRECT, Score, accuracy, grouped, model_graded_qa, scorer, stderr
from inspect_ai.solver import solver
from inspect_ai.tool import tool
from inspect_ai.util import sandboxdef 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"]
os.environ["OPENROUTER_API_KEY"] = load_key() # Inspect reads the key from the environmentGEMMA = get_model("openrouter/google/gemma-4-26b-a4b-it",
provider={"order": ["makora"], "allow_fallbacks": False},
config=GenerateConfig(temperature=0, reasoning_effort="none"))1. ชุดงานแก้ bug ของ Lab 2 ด้วย Inspect
ใช้ 12 งานเดิม (เตรียมไว้แล้ว) · agent เห็น test 2 ข้อแรกในไฟล์ · scorer ใช้ test ทั้งหมดในโฟลเดอร์ของตัวเอง
TASKS = []
def task(name, level, text, code, tests, n_public=2):
lines = tests.strip().splitlines()
head = [l for l in lines if not l.startswith("def test_")]
cases = [l for l in lines if l.startswith("def test_")]
public = "\n".join(head + cases[:n_public]) + "\n"
TASKS.append({"name": name, "level": level, "text": text, "code": code,
"tests": "\n".join(lines) + "\n", "public": public})
# ---- easy: one bug, the visible tests show almost everything ----
task("add", "easy", "Fix the add() function.", "def add(a, b):\n return a - b\n", """
from solution import add
def test_add(): assert add(2, 3) == 5
def test_negative(): assert add(-2, -3) == -5""")
task("is_even", "easy", "Fix is_even().", "def is_even(n):\n return n % 2 == 1\n", """
from solution import is_even
def test_even(): assert is_even(4)
def test_odd(): assert not is_even(7)""")
task("largest", "easy", "Fix largest().", "def largest(xs):\n return sorted(xs)[0]\n", """
from solution import largest
def test_basic(): assert largest([3, 9, 2]) == 9
def test_negative(): assert largest([-5, -2, -9]) == -2""")
task("c_to_f", "easy", "Fix c_to_f().", "def c_to_f(c):\n return c * 9 / 5\n", """
from solution import c_to_f
def test_freezing(): assert c_to_f(0) == 32
def test_boiling(): assert c_to_f(100) == 212""")
task("count_vowels", "easy", "count_vowels() should count vowels in any letter case.",
"def count_vowels(s):\n return sum(1 for ch in s if ch in 'aeiou')\n", """
from solution import count_vowels
def test_lower(): assert count_vowels("agent") == 2
def test_upper(): assert count_vowels("AGENT") == 2""")
task("slugify", "easy", "Turn a title into a URL slug: lowercase words joined by single dashes, no punctuation.",
"def slugify(title):\n return title.lower().replace(' ', '-')\n", """
from solution import slugify
def test_basic(): assert slugify("Hello World") == "hello-world"
def test_punctuation(): assert slugify("Hello, World!") == "hello-world"
def test_spaces(): assert slugify(" Agentic AI ") == "agentic-ai\"""")
# ---- hard: a short bug report; the hidden tests check the edge cases ----
task("roman_to_int", "hard", "Bug report: roman_to_int('IX') returns 11 instead of 9.",
"def roman_to_int(s):\n values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}\n return sum(values[ch] for ch in s)\n", """
import pytest
from solution import roman_to_int
def test_simple(): assert roman_to_int("XVI") == 16
def test_subtract(): assert roman_to_int("IX") == 9
def test_year(): assert roman_to_int("MCMXCIV") == 1994
def test_lower(): assert roman_to_int("xiv") == 14
def test_invalid(): pytest.raises(ValueError, roman_to_int, "ABC")
def test_empty(): pytest.raises(ValueError, roman_to_int, "")""")
task("compare_versions", "hard", "Bug report: compare_versions says 1.9 is newer than 1.10.",
"def compare_versions(a, b):\n return (a > b) - (a < b)\n", """
from solution import compare_versions
def test_equal(): assert compare_versions("1.2", "1.2") == 0
def test_numeric(): assert compare_versions("1.10", "1.9") == 1
def test_trailing_zero(): assert compare_versions("1.0", "1") == 0
def test_longer(): assert compare_versions("2.0.1", "2.0") == 1
def test_prefix(): assert compare_versions("v1.2", "1.3") == -1
def test_spaces(): assert compare_versions(" 1.2 ", "1.2") == 0""")
task("parse_duration", "hard", "Bug report: parse_duration only understands minutes. It should also accept d, h and s, like '1h30m15s'.",
"def parse_duration(text):\n return int(text[:-1]) * 60\n", """
import pytest
from solution import parse_duration
def test_minutes(): assert parse_duration("90m") == 5400
def test_seconds(): assert parse_duration("45s") == 45
def test_mixed(): assert parse_duration("1h30m15s") == 5415
def test_days(): assert parse_duration("2d") == 172800
def test_spaces(): assert parse_duration("1h 5m") == 3900
def test_bad(): pytest.raises(ValueError, parse_duration, "10x")""")
task("merge_intervals", "hard", "Bug report: merge_intervals misses some overlaps.",
"def merge_intervals(xs):\n out = []\n for a, b in xs:\n if out and a < out[-1][1]:\n out[-1][1] = b\n else:\n out.append([a, b])\n return out\n", """
from solution import merge_intervals
def test_overlap(): assert merge_intervals([[1, 3], [2, 6]]) == [[1, 6]]
def test_touching(): assert merge_intervals([[1, 2], [2, 3]]) == [[1, 3]]
def test_unsorted(): assert merge_intervals([[8, 10], [1, 3], [2, 4]]) == [[1, 4], [8, 10]]
def test_inside(): assert merge_intervals([[1, 10], [2, 3]]) == [[1, 10]]
def test_empty(): assert merge_intervals([]) == []
def test_tuples(): assert merge_intervals([(5, 6), (1, 2)]) == [[1, 2], [5, 6]]""")
task("camel_to_snake", "hard", "Bug report: camel_to_snake('ParseJson') returns '_parse_json'.",
"def camel_to_snake(name):\n return ''.join('_' + ch.lower() if ch.isupper() else ch for ch in name)\n", """
from solution import camel_to_snake
def test_simple(): assert camel_to_snake("parseJson") == "parse_json"
def test_pascal(): assert camel_to_snake("ParseJson") == "parse_json"
def test_acronym(): assert camel_to_snake("parseHTTPResponse") == "parse_http_response"
def test_acronym_end(): assert camel_to_snake("getID") == "get_id"
def test_digits(): assert camel_to_snake("ep17Lab2") == "ep17_lab2"
def test_snake(): assert camel_to_snake("already_snake") == "already_snake\"""")
task("format_price", "hard", "Feature request: format_price should show amounts like 1,234.50 THB.",
"def format_price(x):\n return f'{x} THB'\n", """
from solution import format_price
def test_int(): assert format_price(1234) == "1,234.00 THB"
def test_cents(): assert format_price(1234.5) == "1,234.50 THB"
def test_negative(): assert format_price(-50) == "-50.00 THB"
def test_million(): assert format_price(1_000_000) == "1,000,000.00 THB"
def test_round_half_up(): assert format_price(0.125) == "0.13 THB"
def test_zero(): assert format_price(-0.001) == "0.00 THB\"""")
print(len(TASKS), "tasks ·", sum(t["tests"].count("def test_") for t in TASKS), "tests ·",
sum(t["public"].count("def test_") for t in TASKS), "visible")12 tasks · 49 tests · 24 visible
# ✏️ TODO 1 (▶ วิดีโอ 2:02): ไฟล์ test ใน sandbox ต้องมีแค่ชุดที่เห็น
dataset = [Sample(id=t["name"],
input=f"{t['text']}\n\nThe file solution.py is:\n```python\n{t['code']}```",
target=t["tests"],
metadata={"level": t["level"]},
files={"solution.py": t["code"], "test_solution.py": ___})
for t in TASKS]dataset = [Sample(id=t["name"],
input=f"{t['text']}\n\nThe file solution.py is:\n```python\n{t['code']}```",
target=t["tests"],
metadata={"level": t["level"]},
files={"solution.py": t["code"], "test_solution.py": t["public"]})
for t in TASKS]# ✏️ TODO 2 (▶ วิดีโอ 2:26): เขียนโค้ดใหม่ลง solution.py ใน sandbox
PYTEST = [sys.executable, "-m", "pytest", "test_solution.py", "-q", "--tb=short", "--color=no", "-p", "no:cacheprovider"]
@tool
def edit_file():
async def execute(code: str):
"""Replace the whole of solution.py, then run the visible tests.
Args:
code: the complete new contents of solution.py
"""
await sandbox().___
result = await sandbox().exec(PYTEST, timeout=30)
return (result.stdout + result.stderr)[-1500:]
return execute
@tool
def view_file():
async def execute():
"""Show the current solution.py."""
return await sandbox().read_file("solution.py")
return executePYTEST = [sys.executable, "-m", "pytest", "test_solution.py", "-q", "--tb=short", "--color=no", "-p", "no:cacheprovider"]
@tool
def edit_file():
async def execute(code: str):
"""Replace the whole of solution.py, then run the visible tests.
Args:
code: the complete new contents of solution.py
"""
await sandbox().write_file("solution.py", code)
result = await sandbox().exec(PYTEST, timeout=30)
return (result.stdout + result.stderr)[-1500:]
return execute
@tool
def view_file():
async def execute():
"""Show the current solution.py."""
return await sandbox().read_file("solution.py")
return execute@scorer(metrics=[accuracy(), stderr(), grouped(accuracy(), "level")])
def hidden_tests():
async def score(state, target):
code = await sandbox().read_file("solution.py")
with tempfile.TemporaryDirectory(prefix="judge_") as d:
with open(os.path.join(d, "solution.py"), "w") as f:
f.write(code)
with open(os.path.join(d, "test_solution.py"), "w") as f:
f.write(target.text)
# ✏️ TODO 3 (▶ วิดีโอ 3:24): ผ่านเมื่อรันครบทุกข้อ และผ่านครบทุกข้อ
subprocess.run([sys.executable, "-m", "pytest", "test_solution.py", "-q", "-p", "no:cacheprovider",
"--junitxml=report.xml"], cwd=d, capture_output=True, timeout=30)
try:
suite = ET.parse(os.path.join(d, "report.xml")).getroot().find("testsuite")
except (FileNotFoundError, ET.ParseError):
return Score(value=INCORRECT, explanation="no test report")
expected = target.text.count("def test_")
passed = int(suite.get("tests", 0)) - sum(int(suite.get(k, 0)) for k in ("failures", "errors", "skipped"))
ok = ___
return Score(value=CORRECT if ok else INCORRECT, explanation=f"{passed}/{expected} hidden tests passed")
return score@scorer(metrics=[accuracy(), stderr(), grouped(accuracy(), "level")])
def hidden_tests():
async def score(state, target):
code = await sandbox().read_file("solution.py")
with tempfile.TemporaryDirectory(prefix="judge_") as d:
with open(os.path.join(d, "solution.py"), "w") as f:
f.write(code)
with open(os.path.join(d, "test_solution.py"), "w") as f:
f.write(target.text)
subprocess.run([sys.executable, "-m", "pytest", "test_solution.py", "-q", "-p", "no:cacheprovider",
"--junitxml=report.xml"], cwd=d, capture_output=True, timeout=30)
try:
suite = ET.parse(os.path.join(d, "report.xml")).getroot().find("testsuite")
except (FileNotFoundError, ET.ParseError):
return Score(value=INCORRECT, explanation="no test report")
expected = target.text.count("def test_")
passed = int(suite.get("tests", 0)) - sum(int(suite.get(k, 0)) for k in ("failures", "errors", "skipped"))
ok = int(suite.get("tests", 0)) == expected and passed == expected
return Score(value=CORRECT if ok else INCORRECT, explanation=f"{passed}/{expected} hidden tests passed")
return score# ✏️ TODO 4 (▶ วิดีโอ 3:41): ให้แต่ละ sample ทำงานใน sandbox ของตัวเองบนเครื่องนี้
fix_bugs = Task(name="fix_bugs", dataset=dataset,
solver=react(tools=[edit_file(), view_file()]),
scorer=hidden_tests(),
sandbox=___,
message_limit=14)
log = eval(fix_bugs, model=GEMMA, epochs=3, log_dir="logs", display="none", log_level="error")[0]
for name, metric in log.results.scores[0].metrics.items():
print(f"{name:9s} {metric.value:.3f}")fix_bugs = Task(name="fix_bugs", dataset=dataset,
solver=react(tools=[edit_file(), view_file()]),
scorer=hidden_tests(),
sandbox="local",
message_limit=14)
log = eval(fix_bugs, model=GEMMA, epochs=3, log_dir="logs", display="none", log_level="error")[0]
for name, metric in log.results.scores[0].metrics.items():
print(f"{name:9s} {metric.value:.3f}")accuracy 0.583
stderr 0.149
easy 1.000
hard 0.167
all 0.583
acc, se = log.results.scores[0].metrics["accuracy"].value, log.results.scores[0].metrics["stderr"].value
print(f"{len(log.samples)} sample records · accuracy {acc:.0%} · 95% CI [{max(0, acc - 1.96 * se):.0%}, {min(1, acc + 1.96 * se):.0%}]")36 sample records · accuracy 58% · 95% CI [29%, 87%]
log = read_eval_log(log.location)
s = next(s for s in log.samples if s.metadata["level"] == "hard" and s.scores["hidden_tests"].value == INCORRECT)
print(s.id, "·", s.scores["hidden_tests"].explanation)
for m in s.messages:
for call in getattr(m, "tool_calls", None) or []:
print(" tool call:", call.function, str(call.arguments)[:70].replace("\n", " "))camel_to_snake · 4/6 hidden tests passed
tool call: edit_file {'code': "def camel_to_snake(name):\n return ''.join('_' + ch.lower
tool call: edit_file {'code': "def camel_to_snake(name):\n res = ''.join('_' + ch.lower(
tool call: edit_file {'code': 'def camel_to_snake(name):\n if not name:\n return
2. Panel กรรมการของ Lab 3 ด้วย model_graded_qa
ใช้คำตอบ 30 ข้อที่มีป้ายของ Lab 3 (เตรียมไว้แล้ว) · solver replay ส่งคำตอบที่เก็บไว้แทนการให้ model ตอบใหม่ model_graded_qa(model=[...]) ใช้ template ของ Inspect + คำสั่งของเรา · กรรมการหลายตัว = เสียงข้างมาก (reducer="majority")
ITEMS = [
{"q": "What does ReAct do, and where was it evaluated?",
"notes": "ReAct (Yao et al., 2022) prompts a language model to interleave reasoning traces with actions, such as searching a Wikipedia API. "
"It was evaluated on question answering (HotpotQA), fact verification (FEVER) and two interactive decision-making benchmarks (ALFWorld and WebShop).",
"good": "ReAct has the model alternate between reasoning steps and actions, such as Wikipedia searches. It was tested on HotpotQA, FEVER, ALFWorld and WebShop.",
"para": "In ReAct the model mixes thinking and acting: it reasons, takes an action like a Wikipedia search, and reasons again. The authors evaluated it on HotpotQA and FEVER, plus ALFWorld and WebShop.",
"bad": "ReAct has the model alternate between reasoning steps and actions, such as Wikipedia searches. It was tested only on math word-problem benchmarks.",
"subtle": "ReAct has the model alternate between reasoning steps and actions, such as Wikipedia searches. It was tested on HotpotQA, FEVER, ALFWorld and WebShop, and beat every other method on all four.",
"partial": "ReAct has the model alternate between reasoning steps and actions."},
{"q": "How does Reflexion help an agent improve?",
"notes": "Reflexion (Shinn et al., 2023) has an agent write a short verbal reflection after a failed attempt and keep it in an episodic memory buffer. "
"The reflection is added to the prompt of the next attempt. The model's weights are not updated.",
"good": "After a failed attempt, the agent writes a short reflection in words and stores it in memory; the next attempt reads it in its prompt. The model's weights stay the same.",
"para": "Reflexion keeps the model unchanged. When an attempt fails, the agent writes a brief reflection in natural language, saves it in episodic memory, and includes it in the prompt for its next try.",
"bad": "After a failed attempt, the agent writes a short reflection and then fine-tunes its own weights on it, so the next attempt uses an updated model.",
"subtle": "After a failed attempt, the agent writes a short reflection in words and stores it in memory; the next attempt reads it in its prompt. Only the last reflection is ever kept.",
"partial": "The agent writes a reflection after a failure."},
{"q": "What does the RAG model of Lewis et al. combine?",
"notes": "RAG (Lewis et al., 2020) combines a pre-trained sequence-to-sequence model (parametric memory) with a dense vector index of Wikipedia (non-parametric memory), "
"accessed through a neural retriever.",
"good": "RAG pairs a pre-trained sequence-to-sequence generator, its parametric memory, with a dense vector index of Wikipedia, its non-parametric memory, reached through a neural retriever.",
"para": "It combines two memories: the parameters of a pre-trained seq2seq model, and a dense vector index of Wikipedia that a neural retriever searches.",
"bad": "RAG pairs a pre-trained sequence-to-sequence generator with live results from a commercial web search engine, which it queries at answer time.",
"subtle": "RAG pairs a pre-trained sequence-to-sequence generator with a dense vector index of Wikipedia, reached through a neural retriever that is kept frozen and never trained.",
"partial": "RAG combines a sequence-to-sequence model with retrieval."},
{"q": "What is the Model Context Protocol (MCP)?",
"notes": "MCP is an open protocol introduced by Anthropic in November 2024. It standardizes how applications provide tools, resources and prompts to LLMs, "
"with a client-server design.",
"good": "MCP is an open protocol from Anthropic, introduced in November 2024, that standardizes how applications expose tools, resources and prompts to LLMs through clients and servers.",
"para": "The Model Context Protocol is an open, client-server protocol that Anthropic introduced in November 2024 to standardize how applications give LLMs tools, resources and prompts.",
"bad": "MCP is an open protocol introduced by OpenAI in 2023 that standardizes how applications expose tools, resources and prompts to LLMs through clients and servers.",
"subtle": "MCP is an open protocol from Anthropic, introduced in November 2024, that standardizes how applications expose tools, resources and prompts to LLMs through a peer-to-peer design.",
"partial": "MCP is an open protocol for giving LLMs tools."},
{"q": "When does chain-of-thought prompting help?",
"notes": "Chain-of-thought prompting (Wei et al., 2022) gives few-shot examples that include intermediate reasoning steps. "
"The paper reports that the gains appear mainly in large models, around 100B parameters, and are small or negative for small models.",
"good": "Chain-of-thought prompting shows few-shot examples with the reasoning steps written out. The gains appear mainly in large models, around 100B parameters; small models gain little or even lose.",
"para": "It helps mostly with large models: few-shot examples that spell out intermediate reasoning steps improve models around 100B parameters, while small models see little or negative change.",
"bad": "Chain-of-thought prompting shows few-shot examples with the reasoning steps written out. It works best with small models, which gain the most from it.",
"subtle": "Chain-of-thought prompting shows few-shot examples with the reasoning steps written out. The gains appear mainly in models around 10B parameters.",
"partial": "Chain-of-thought prompting shows examples with reasoning steps."},
{"q": "How does Constitutional AI train a harmless assistant?",
"notes": "Constitutional AI (Bai et al., 2022) uses a short list of written principles. In a supervised phase the model critiques and revises its own answers; "
"then a reinforcement-learning phase uses AI feedback (RLAIF) instead of human harmlessness labels.",
"good": "It starts from a short list of written principles. First the model critiques and revises its own answers in a supervised phase, then reinforcement learning uses AI feedback instead of human harmlessness labels.",
"para": "Bai et al. give the model a short written list of principles. The model first critiques and revises its own answers (supervised), then is trained with reinforcement learning from AI feedback rather than human harmlessness labels.",
"bad": "It starts from a short list of written principles, and as a result it removes the need for any human oversight; every chat model released since then has been trained this way.",
"subtle": "It starts from a short list of written principles. First the model critiques and revises its own answers in a supervised phase, then reinforcement learning uses feedback from human raters.",
"partial": "It uses a list of written principles to train the model."},
]
for it in ITEMS: # longer, same content: the good answer, said again, plus a bullet summary
it["restate"] = (it["good"] + " To put it another way: " + it["para"] + " Key points: "
+ " ".join("- " + s.strip().rstrip(".") + "." for s in it["good"].split(". ") if s.strip()))
LABEL = {"good": 1, "para": 1, "restate": 1, "bad": 0, "subtle": 0}
print(len(ITEMS), "questions ×", len(LABEL), "answers =", len(ITEMS) * len(LABEL), "labelled answers")6 questions × 5 answers = 30 labelled answers
# ✏️ TODO 5 (▶ วิดีโอ 6:02): ใส่คำตอบที่เก็บไว้ใน metadata เป็น output
cfg = GenerateConfig(temperature=0)
MISTRAL = get_model("openrouter/mistralai/mistral-small-3.2-24b-instruct", provider={"order": ["deepinfra"], "allow_fallbacks": False}, config=cfg)
LLAMA = get_model("openrouter/meta-llama/llama-3.3-70b-instruct", provider={"order": ["deepinfra"], "allow_fallbacks": False}, config=cfg)
@solver
def replay():
async def solve(state, generate):
state.output = ModelOutput.from_content(model="replay", content=___)
state.messages.append(state.output.message)
return state
return solve
judge = Task(name="judge_panel",
dataset=[Sample(input=f"Question: {it['q']}\n\nSource notes: {it['notes']}", target=it["notes"],
metadata={"kind": k, "label": LABEL[k], "answer": it[k]})
for it in ITEMS for k in LABEL],
solver=replay(),
scorer=model_graded_qa(model=[GEMMA, MISTRAL, LLAMA],
instructions="Grade the answer against the source notes in the criterion. Grade C if every claim is supported "
"by the notes and the question is answered; otherwise grade I. Explain briefly, then end with GRADE: C or GRADE: I."))
jlog = eval(judge, model=GEMMA, log_dir="logs", display="none", log_level="error")[0]
agree = 0
for s in jlog.samples:
sc = s.scores["model_graded_qa"]
agree += (sc.value == "C") == bool(s.metadata["label"])
if sc.metadata["panel"]["votes"].count("C") not in (0, 3):
print("split:", s.metadata["kind"], sc.metadata["panel"]["votes"], "→", sc.value, "| label", s.metadata["label"], "|", s.input.splitlines()[0][10:])
print(f"panel agrees with the labels on {agree}/{len(jlog.samples)}")cfg = GenerateConfig(temperature=0)
MISTRAL = get_model("openrouter/mistralai/mistral-small-3.2-24b-instruct", provider={"order": ["deepinfra"], "allow_fallbacks": False}, config=cfg)
LLAMA = get_model("openrouter/meta-llama/llama-3.3-70b-instruct", provider={"order": ["deepinfra"], "allow_fallbacks": False}, config=cfg)
@solver
def replay():
async def solve(state, generate):
state.output = ModelOutput.from_content(model="replay", content=state.metadata["answer"])
state.messages.append(state.output.message)
return state
return solve
judge = Task(name="judge_panel",
dataset=[Sample(input=f"Question: {it['q']}\n\nSource notes: {it['notes']}", target=it["notes"],
metadata={"kind": k, "label": LABEL[k], "answer": it[k]})
for it in ITEMS for k in LABEL],
solver=replay(),
scorer=model_graded_qa(model=[GEMMA, MISTRAL, LLAMA],
instructions="Grade the answer against the source notes in the criterion. Grade C if every claim is supported "
"by the notes and the question is answered; otherwise grade I. Explain briefly, then end with GRADE: C or GRADE: I."))
jlog = eval(judge, model=GEMMA, log_dir="logs", display="none", log_level="error")[0]
agree = 0
for s in jlog.samples:
sc = s.scores["model_graded_qa"]
agree += (sc.value == "C") == bool(s.metadata["label"])
if sc.metadata["panel"]["votes"].count("C") not in (0, 3):
print("split:", s.metadata["kind"], sc.metadata["panel"]["votes"], "→", sc.value, "| label", s.metadata["label"], "|", s.input.splitlines()[0][10:])
print(f"panel agrees with the labels on {agree}/{len(jlog.samples)}")split: subtle ['I', 'C', 'I'] → I | label 0 | How does Reflexion help an agent improve?
split: subtle ['C', 'C', 'I'] → C | label 0 | What does the RAG model of Lewis et al. combine?
panel agrees with the labels on 29/30
สรุป
| สิ่งที่ Inspect ให้ | แทนโค้ดที่เราเขียนเองใน |
|---|---|
Sample + files + sandbox |
Lab 1 reset · Lab 2 EvalEnv |
@tool จาก docstring |
Lab 1 ACTION schema |
react() |
Lab 1 policy + run_episode |
eval(..., epochs=k) ขนานเอง |
Lab 2 run_suite + ThreadPoolExecutor |
accuracy · stderr · grouped |
Lab 2 metrics · tsr_ci · report |
log file + inspect view |
Lab 2 บันทึก action ที่จดเอง |
model_graded_qa(model=[...]) |
Lab 3 panel |
สิ่งที่ framework ไม่ได้ ทำแทนเรา: ออกแบบงานที่แยกคนเก่งออกได้ · ซ่อน test · ทำ scorer ให้โกงไม่ได้ · ตรวจกรรมการกับป้าย — ยังเป็นงานของเรา
แบบฝึกหัด
- เพิ่ม
TASKSอีก 6 ข้อจากแบบฝึกหัดของ Lab 2 แล้วดูว่าstderrลดลงเท่าไร - ส่ง
instructionsที่เป็น rubric 1–5 ของ Lab 3 ให้model_graded_qa(ใช้partial_credit=True) แล้วเทียบกับผลเดิม - รัน
inspect viewในโฟลเดอร์ของ notebook แล้วเปิดดูบทสนทนาของงานยากที่ไม่ผ่าน
ถัดไป — Recap: สรุปทั้ง EP17