Skip to main content

Lab 3 — LLM-as-judge: อคติ · G-Eval · panel และ Cohen’s κ

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–2 ให้คะแนนด้วย test ที่รันได้ แต่งานของ research agent คือ รายงาน ไม่มี test ให้รัน ทางที่ตำราเสนอคือ LLM-as-judge (§14.7): ให้ model อีกตัวเป็นกรรมการ — แต่กรรมการก็มีอคติ เราต้องตรวจกรรมการก่อนใช้

สิ่งที่จะได้ทำ

  1. ข้อมูล: คำถามวิจัย 6 ข้อ · บันทึกแหล่งข้อมูล · คำตอบ 5 แบบต่อข้อ ที่เรารู้อยู่แล้วว่าดีหรือไม่ดี
  2. pointwise judge สามตัวจากสามตระกูล model แล้ววัดว่าตรงกับป้ายแค่ไหน ด้วย Cohen’s κ
  3. pairwise judge กับ swap augmentation: เจอ position bias ไหม
  4. ทดสอบ verbosity bias
  5. G-Eval: เฉลี่ยคะแนนด้วยความน่าจะเป็นจาก logprobs
  6. panel: เสียงข้างมากของสามกรรมการ

บันทึกแหล่งข้อมูลและคำตอบเขียนขึ้นสำหรับ lab นี้ (สรุปจาก paper จริง) — ป้ายดี/ไม่ดีมาจากการที่เราเขียนจุดผิดเอง ไม่ใช่ป้ายจากคน คำตัดสินของกรรมการทุกตัวมาจากการรันจริง

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

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

เหมือน Lab 1: Python 3.10 ขึ้นไป (หรือ Colab) และ OpenRouter API key — วิธีตั้งค่า key อยู่ใน Lab 1 lab นี้เรียก model ราวสองร้อยครั้ง ใช้ราวหนึ่งเซ็นต์ดอลลาร์

%pip install -q "openai>=1.50" python-dotenv
import json, math, os
from concurrent.futures import ThreadPoolExecutor
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(), max_retries=5, timeout=60)
COST = {"chat": 0.0}
pool = ThreadPoolExecutor(max_workers=12)

กรรมการสามตัว จากสามตระกูล model — ตำราแนะนำ panel ที่ไม่ได้มาจาก model ตระกูลเดียวกัน เพราะอคติของตระกูลเดียวกันมักไปทางเดียวกัน (§14.7.4)

กรรมการ model provider (ล็อกไว้)
gemma google/gemma-4-26b-a4b-it Makora — ให้ logprobs ด้วย (ใช้กับ G-Eval)
mistral mistralai/mistral-small-3.2-24b-instruct DeepInfra
llama meta-llama/llama-3.3-70b-instruct DeepInfra

ทั้งสามรองรับ structured output · DeepInfra ไม่คืน logprobs ของสอง model หลัง G-Eval จึงใช้แค่ Gemma

JUDGES = {"gemma":   ("google/gemma-4-26b-a4b-it", "makora"),
          "mistral": ("mistralai/mistral-small-3.2-24b-instruct", "deepinfra"),
          "llama":   ("meta-llama/llama-3.3-70b-instruct", "deepinfra")}

def ask(judge, prompt, **kw):
    model, provider = JUDGES[judge]
    extra = {"provider": {"order": [provider], "allow_fallbacks": False}}
    if judge == "gemma":
        extra["reasoning"] = {"enabled": False}
    r = client.chat.completions.create(model=model, temperature=0, extra_body=extra,
                                       messages=[{"role": "user", "content": prompt}], **kw)
    COST["chat"] += r.usage.cost or 0
    return r

1. ข้อมูล: คำตอบที่เรารู้อยู่แล้วว่าดีหรือไม่ดี

คำถามแต่ละข้อมี บันทึกแหล่งข้อมูล (สิ่งที่ research agent ค้นมา) และคำตอบ 5 แบบ:

แบบ คืออะไร ป้าย
good ตอบครบ ทุกข้อความมีในบันทึก ดี
para เนื้อหาเดียวกับ good เขียนคนละแบบ ดี
restate good + พูดซ้ำอีกรอบ + bullet สรุป (ยาวกว่า เนื้อหาเท่าเดิม) ดี
bad มีข้อความที่ขัดกับบันทึกชัดๆ ไม่ดี
subtle ผิดเล็กน้อย: ตัวเลขผิด หรือข้อความที่บันทึกไม่ได้บอก ไม่ดี

ตำราบอกให้ตรวจกรรมการกับ ป้ายจากคน — ใน lab นี้เรารู้ป้ายเพราะเราเขียนจุดผิดเอง ซึ่งแทนป้ายจากคนได้ในการทดลองนี้ แต่ไม่ใช่ป้ายจากคนจริง

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

2. Pointwise judge: ให้คะแนนทีละคำตอบ

rubric 1–5 ที่ยึด บันทึกแหล่งข้อมูล เป็นความจริง · กรรมการเขียนเหตุผลหนึ่งประโยค ก่อน ให้คะแนน (§14.7.1) คะแนน ≥ 4 นับว่า “ดี”

# ✏️ TODO 1 (▶ วิดีโอ 3:14): ให้คะแนนเลือกได้แค่ 1 ถึง 5
def schema(name, props):
    return {"type": "json_schema", "json_schema": {"name": name, "strict": True, "schema": {
        "type": "object", "additionalProperties": False, "required": list(props), "properties": props}}}

SCORE = schema("score", {"reason": {"type": "string"}, "score": {"type": "integer", "enum": ___}})

def ask_json(judge, prompt, fmt, tries=3):
    for attempt in range(tries):
        try:
            return json.loads(ask(judge, prompt, response_format=fmt).choices[0].message.content)
        except json.JSONDecodeError:
            if attempt == tries - 1:
                raise

RUBRIC = """You grade a research assistant's answer. Use only the source notes as the truth.
5 = answers the question and every claim is supported by the notes
3 = answers the question but leaves out an important point
1 = contains a claim that the notes contradict or do not support"""

def pointwise(judge, it, answer):
    prompt = (f"{RUBRIC}\n\nQuestion: {it['q']}\nSource notes: {it['notes']}\nAnswer: {answer}\n\n"
              "Give a one-sentence reason, then a score from 1 to 5.")
    return ask_json(judge, prompt, SCORE)["score"]
def schema(name, props):
    return {"type": "json_schema", "json_schema": {"name": name, "strict": True, "schema": {
        "type": "object", "additionalProperties": False, "required": list(props), "properties": props}}}

SCORE = schema("score", {"reason": {"type": "string"}, "score": {"type": "integer", "enum": [1, 2, 3, 4, 5]}})

def ask_json(judge, prompt, fmt, tries=3):
    for attempt in range(tries):
        try:
            return json.loads(ask(judge, prompt, response_format=fmt).choices[0].message.content)
        except json.JSONDecodeError:
            if attempt == tries - 1:
                raise

RUBRIC = """You grade a research assistant's answer. Use only the source notes as the truth.
5 = answers the question and every claim is supported by the notes
3 = answers the question but leaves out an important point
1 = contains a claim that the notes contradict or do not support"""

def pointwise(judge, it, answer):
    prompt = (f"{RUBRIC}\n\nQuestion: {it['q']}\nSource notes: {it['notes']}\nAnswer: {answer}\n\n"
              "Give a one-sentence reason, then a score from 1 to 5.")
    return ask_json(judge, prompt, SCORE)["score"]
jobs = [(j, i, kind) for j in JUDGES for i in range(len(ITEMS)) for kind in LABEL]
scores = list(pool.map(lambda x: pointwise(x[0], ITEMS[x[1]], ITEMS[x[1]][x[2]]), jobs))
POINT = {}
for (j, i, kind), s in zip(jobs, scores):
    POINT.setdefault(j, []).append((kind, s))

for j, rows in POINT.items():
    print(f"{j:8s}", "  ".join(f"{k}:{''.join(str(s) for kk, s in rows if kk == k)}" for k in LABEL))
gemma    good:555555  para:555555  restate:555555  bad:111111  subtle:111111
mistral  good:555555  para:555555  restate:555555  bad:111111  subtle:333111
llama    good:555555  para:355555  restate:555555  bad:111111  subtle:111111

3. ตรงกับป้ายแค่ไหน: agreement กับ Cohen’s κ

agreement = สัดส่วนที่ตัดสินตรงกับป้าย · Cohen’s κ = (p_o − p_e) / (1 − p_e) หักส่วนที่ตรงกันโดยบังเอิญ p_e ออก ตำราถือว่ากรรมการเชื่อถือได้เมื่อ κ > 0.6 และตรงกันเกิน 80% (§14.7.4)

# ✏️ TODO 2 (▶ วิดีโอ 4:52): ส่วนที่ตรงกันโดยบังเอิญ = ทั้งคู่ว่าดี + ทั้งคู่ว่าไม่ดี
def cohen_kappa(a, b):
    n = len(a)
    p_o = sum(x == y for x, y in zip(a, b)) / n
    pa, pb = sum(a) / n, sum(b) / n
    p_e = ___
    return 1.0 if p_e == 1 else (p_o - p_e) / (1 - p_e)

labels = [LABEL[k] for k, s in POINT["gemma"]]
def check(name, verdicts):
    agree = sum(v == l for v, l in zip(verdicts, labels)) / len(labels)
    print(f"{name:12s} agreement {agree:4.0%}   kappa {cohen_kappa(verdicts, labels):5.2f}")

for j, rows in POINT.items():
    check(j, [int(s >= 4) for k, s in rows])
check("always good", [1] * len(labels))
def cohen_kappa(a, b):
    n = len(a)
    p_o = sum(x == y for x, y in zip(a, b)) / n
    pa, pb = sum(a) / n, sum(b) / n
    p_e = pa * pb + (1 - pa) * (1 - pb)
    return 1.0 if p_e == 1 else (p_o - p_e) / (1 - p_e)

labels = [LABEL[k] for k, s in POINT["gemma"]]
def check(name, verdicts):
    agree = sum(v == l for v, l in zip(verdicts, labels)) / len(labels)
    print(f"{name:12s} agreement {agree:4.0%}   kappa {cohen_kappa(verdicts, labels):5.2f}")

for j, rows in POINT.items():
    check(j, [int(s >= 4) for k, s in rows])
check("always good", [1] * len(labels))
gemma        agreement 100%   kappa  1.00
mistral      agreement 100%   kappa  1.00
llama        agreement  97%   kappa  0.93
always good  agreement  60%   kappa  0.00

4. Pairwise judge กับ swap augmentation: position bias

ให้กรรมการดูสองคำตอบแล้วเลือก A · B · tie — แล้ว สลับลำดับ ถามอีกรอบ (§14.7.2)

  • เลือกคำตอบเดิมทั้งสองลำดับ → ผลนั้น
  • เลือก ตำแหน่งเดิม ทั้งสองลำดับ (A กับ A หรือ B กับ B) → ตัดสินตามตำแหน่ง → นับเป็น tie

สองการทดลอง: good vs subtle (คุณภาพต่างกันชัด) · good vs para (เนื้อหาเท่ากัน คำตอบที่ถูกคือ tie)

VERDICT = schema("verdict", {"reason": {"type": "string"}, "winner": {"type": "string", "enum": ["A", "B", "tie"]}})

def pairwise(judge, it, a, b):
    prompt = (f"Two research assistants answered the same question. Use only the source notes as the truth.\n\n"
              f"Question: {it['q']}\nSource notes: {it['notes']}\n\nAnswer A: {a}\n\nAnswer B: {b}\n\n"
              "Which answer is better? Give a one-sentence reason, then A, B or tie.")
    return ask_json(judge, prompt, VERDICT)["winner"]

# ✏️ TODO 3 (▶ วิดีโอ 6:29): แปลงผลรอบสอง (สลับลำดับแล้ว) กลับเป็นมุมมองของรอบแรก

def swap_test(judge, it, x, y):
    first = pairwise(judge, it, it[x], it[y])      # x in slot A
    second = pairwise(judge, it, it[y], it[x])     # x in slot B
    second_as_first = {"A": ___, "B": ___, "tie": "tie"}[second]
    final = first if first == second_as_first else "tie"
    return first + second, final

def run_pairs(x, y):
    jobs = [(j, it) for j in JUDGES for it in ITEMS]
    out = list(pool.map(lambda job: swap_test(job[0], job[1], x, y), jobs))
    for j in JUDGES:
        rows = [o for (jj, it), o in zip(jobs, out) if jj == j]
        slot = sum(raw in ("AA", "BB") for raw, final in rows)
        print(f"{j:8s} raw {' '.join(raw for raw, f in rows):26s} same slot {slot}/6   final {[f for r, f in rows]}")
VERDICT = schema("verdict", {"reason": {"type": "string"}, "winner": {"type": "string", "enum": ["A", "B", "tie"]}})

def pairwise(judge, it, a, b):
    prompt = (f"Two research assistants answered the same question. Use only the source notes as the truth.\n\n"
              f"Question: {it['q']}\nSource notes: {it['notes']}\n\nAnswer A: {a}\n\nAnswer B: {b}\n\n"
              "Which answer is better? Give a one-sentence reason, then A, B or tie.")
    return ask_json(judge, prompt, VERDICT)["winner"]

def swap_test(judge, it, x, y):
    first = pairwise(judge, it, it[x], it[y])      # x in slot A
    second = pairwise(judge, it, it[y], it[x])     # x in slot B
    second_as_first = {"A": "B", "B": "A", "tie": "tie"}[second]
    final = first if first == second_as_first else "tie"
    return first + second, final

def run_pairs(x, y):
    jobs = [(j, it) for j in JUDGES for it in ITEMS]
    out = list(pool.map(lambda job: swap_test(job[0], job[1], x, y), jobs))
    for j in JUDGES:
        rows = [o for (jj, it), o in zip(jobs, out) if jj == j]
        slot = sum(raw in ("AA", "BB") for raw, final in rows)
        print(f"{j:8s} raw {' '.join(raw for raw, f in rows):26s} same slot {slot}/6   final {[f for r, f in rows]}")
run_pairs("good", "subtle")
gemma    raw AB AB AB AB AB AB          same slot 0/6   final ['A', 'A', 'A', 'A', 'A', 'A']
mistral  raw AB AB AB AB AB AB          same slot 0/6   final ['A', 'A', 'A', 'A', 'A', 'A']
llama    raw AB AB AB AB AB AB          same slot 0/6   final ['A', 'A', 'A', 'A', 'A', 'A']
run_pairs("good", "para")
gemma    raw AB BA AB Btie BB BA        same slot 1/6   final ['A', 'B', 'A', 'tie', 'tie', 'B']
mistral  raw BB BB AA BA BB BA          same slot 4/6   final ['tie', 'tie', 'tie', 'B', 'tie', 'B']
llama    raw AB BA AB BA BA AA          same slot 1/6   final ['A', 'B', 'A', 'B', 'B', 'tie']

5. Verbosity bias: คำตอบยาวชนะไหม

good vs restate — เนื้อหาเท่ากัน แต่ restate ยาวกว่าราวสามเท่า (พูดซ้ำ + bullet) · ตำราบอกว่ากรรมการมักชอบคำตอบยาว (§14.7.2)

run_pairs("good", "restate")
gemma    raw AB AB AB AB AB AB          same slot 0/6   final ['A', 'A', 'A', 'A', 'A', 'A']
mistral  raw BB BB BB BB BA BA          same slot 4/6   final ['tie', 'tie', 'tie', 'tie', 'B', 'B']
llama    raw AB Btie AB AB Atie AB      same slot 0/6   final ['A', 'tie', 'A', 'A', 'tie', 'A']

6. G-Eval: เฉลี่ยคะแนนด้วยความน่าจะเป็น

G-Eval (§14.7.5): แทนที่จะอ่านคะแนนตัวเดียว ให้อ่านความน่าจะเป็นของทุกคะแนน แล้วคิด Σ s·P(s) ใน lab นี้เราใส่ขั้นการประเมินไว้ใน rubric แทนที่จะให้ model เขียนเอง และใช้คำตอบ partial (ถูกแต่ไม่ครบ) ซึ่งควรได้คะแนนกลางๆ

# ✏️ TODO 4 (▶ วิดีโอ 9:22): G-Eval = Σ s·P(s) (หารด้วย z ให้ความน่าจะเป็นรวมเป็นหนึ่ง)
COMPLETE = """You grade how complete a research assistant's answer is, compared with the source notes.
Score from 1 (misses almost everything in the notes) to 5 (covers everything in the notes that the question asks about)."""

def g_eval(it, answer):
    prompt = f"{COMPLETE}\n\nQuestion: {it['q']}\nSource notes: {it['notes']}\nAnswer: {answer}\n\nReply with only the score digit."
    r = ask("gemma", prompt, logprobs=True, top_logprobs=10, max_tokens=1)
    top = r.choices[0].logprobs.content[0].top_logprobs
    p = {int(t.token): math.exp(t.logprob) for t in top if t.token.strip() in ("1", "2", "3", "4", "5")}
    z = sum(p.values())
    return r.choices[0].message.content.strip(), ___, {s: round(q / z, 3) for s, q in sorted(p.items())}

for it, (said, g, probs) in zip(ITEMS, pool.map(lambda it: g_eval(it, it["partial"]), ITEMS)):
    print(f"said {said}   G-Eval {g:.2f}   {probs}")
COMPLETE = """You grade how complete a research assistant's answer is, compared with the source notes.
Score from 1 (misses almost everything in the notes) to 5 (covers everything in the notes that the question asks about)."""

def g_eval(it, answer):
    prompt = f"{COMPLETE}\n\nQuestion: {it['q']}\nSource notes: {it['notes']}\nAnswer: {answer}\n\nReply with only the score digit."
    r = ask("gemma", prompt, logprobs=True, top_logprobs=10, max_tokens=1)
    top = r.choices[0].logprobs.content[0].top_logprobs
    p = {int(t.token): math.exp(t.logprob) for t in top if t.token.strip() in ("1", "2", "3", "4", "5")}
    z = sum(p.values())
    return r.choices[0].message.content.strip(), sum(s * q for s, q in p.items()) / z, {s: round(q / z, 3) for s, q in sorted(p.items())}

for it, (said, g, probs) in zip(ITEMS, pool.map(lambda it: g_eval(it, it["partial"]), ITEMS)):
    print(f"said {said}   G-Eval {g:.2f}   {probs}")
said 2   G-Eval 2.02   {1: 0.0, 2: 0.982, 3: 0.018, 4: 0.0}
said 2   G-Eval 2.02   {1: 0.0, 2: 0.98, 3: 0.02, 4: 0.0}
said 3   G-Eval 3.13   {2: 0.0, 3: 0.867, 4: 0.133, 5: 0.0}
said 3   G-Eval 3.00   {2: 0.001, 3: 0.999, 4: 0.0}
said 2   G-Eval 2.05   {1: 0.0, 2: 0.947, 3: 0.053, 4: 0.0}
said 2   G-Eval 2.01   {1: 0.0, 2: 0.986, 3: 0.014, 4: 0.0}

7. Panel: เสียงข้างมากของสามกรรมการ

ตำรา: ตรงกันทั้งสาม = มั่นใจสูง · สองต่อหนึ่ง = มั่นใจปานกลาง (§14.7.4)

# ✏️ TODO 5 (▶ วิดีโอ 10:38): เสียงข้างมาก: ดีเมื่อได้อย่างน้อยสองเสียง
votes = list(zip(*[[int(s >= 4) for k, s in POINT[j]] for j in JUDGES]))
panel = [___ for v in votes]
split = sum(0 < sum(v) < 3 for v in votes)
check("panel", panel)
print(f"split votes (2 to 1): {split}/{len(votes)}   cost: USD {COST['chat']:.4f}")
votes = list(zip(*[[int(s >= 4) for k, s in POINT[j]] for j in JUDGES]))
panel = [int(sum(v) >= 2) for v in votes]
split = sum(0 < sum(v) < 3 for v in votes)
check("panel", panel)
print(f"split votes (2 to 1): {split}/{len(votes)}   cost: USD {COST['chat']:.4f}")
panel        agreement 100%   kappa  1.00
split votes (2 to 1): 1/30   cost: USD 0.0062

สรุป

ชิ้นส่วน ในโค้ด สิ่งที่เห็น ตำรา
pointwise + rubric pointwise · เหตุผลก่อนคะแนน กรรมการทั้งสามจับจุดผิดได้เมื่อมีบันทึกให้เทียบ §14.7.1
agreement · Cohen’s κ cohen_kappa · check “ดีทุกครั้ง” ตรง 60% แต่ κ = 0 §14.7.4
position bias · swap swap_test คู่ที่เท่ากัน: เลือกตามตำแหน่ง → tie §14.7.2
verbosity bias run_pairs("good", "restate") เล็กมากในข้อมูลชุดนี้ → ต้องทดสอบเอง §14.7.2
G-Eval g_eval · logprobs ส่วนใหญ่ ≈ คะแนนตรงๆ · ข้อที่ก้ำกึ่งได้ค่าระหว่างกลาง §14.7.5
panel เสียงข้างมาก · นับเสียงแตก ข้อที่แตกเสียง → ส่งให้คน §14.7.4

แบบฝึกหัด

  1. เขียนคำตอบ restate แบบใหม่ ที่ยาวขึ้นด้วยรายละเอียดที่ฟังดูมีสาระ (แต่ไม่ได้อยู่ในบันทึก) กรรมการยังจับได้ไหม
  2. ตัด Source notes ออกจาก prompt ของ pointwise — κ เปลี่ยนไปเท่าไร คำตอบ subtle แบบไหนรอดจากกรรมการ
  3. ติดป้ายคำตอบ 10 ข้อด้วยตัวเอง (ดี/ไม่ดี) แล้วคิด κ ระหว่างตัวคุณกับ panel

ถัดไป — Lab 4: Inspect AI: ทำ harness · scorer · judge ของ Lab 2–3 ด้วย framework จริง