Skip to main content

Lab 5 — Evaluator-Optimizer: แปล abstract จนผ่านเกณฑ์ (§19.1.5)

Lab walkthrough · EP04 Workflow Patterns

หมายเหตุวิธีใช้หน้านี้

หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด

▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP04 Workflow Patterns

model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้

ผู้ช่วยอาจารย์ของ Cogito Learn ต้องแปล abstract ภาษาอังกฤษเป็นภาษาไทยให้นักศึกษา โดย ความหมายต้องครบ และ ศัพท์เทคนิคต้องคงเป็นภาษาอังกฤษ

Evaluator-optimizer คือ feedback loop ของสอง model:

ต่างจาก Reflexion (EP05): ที่นี่ evaluator แยกตัว ตรวจตามเกณฑ์ที่กำหนดไว้ใน loop ที่มีจำนวนรอบตายตัว ส่วน Reflexion จะเก็บ บทเรียน ไว้ใน memory ข้ามความพยายามหลายครั้ง

ข้อมูลในแล็บนี้ (abstract) เป็นข้อมูลสมมติ แต่ผลลัพธ์ของ model ทั้งหมดมาจากการรันจริง

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.1.5 (p.370) — 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, json
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": {"enabled": False}}

def ask_llm(prompt, temperature=0.7, schema=None):
    kw = {"response_format": {"type": "json_schema", "json_schema": {"name": "out", "strict": True, "schema": schema}}} if schema else {}
    resp = client.chat.completions.create(model=MODEL, extra_body=EXTRA, temperature=temperature,
                                          messages=[{"role": "user", "content": prompt}], **kw)
    text = resp.choices[0].message.content
    return json.loads(text) if schema else text

1. โจทย์: abstract + glossary

ABSTRACT = (
    "We study hallucination in small language models that answer students' questions about "
    "course material. We combine retrieval-augmented generation with lightweight fine-tuning on "
    "4,200 question-answer pairs from three university courses. On a new benchmark of 600 "
    "questions, our method reduces hallucination by 31% while keeping answer latency under "
    "two seconds. We release the benchmark and code for future work."
)

GLOSSARY = ["hallucination", "small language model", "retrieval-augmented generation",
            "fine-tuning", "benchmark", "latency"]

TASK = ("Translate this research abstract into Thai for Thai university students. "
        f"Reply with the translation only.\n\nAbstract:\n{ABSTRACT}")

2. Evaluator — ให้คะแนนตามเกณฑ์ที่เขียนไว้ชัดเจน

เกณฑ์ คะแนน ใครตรวจ
meaning — ทุกข้อความ คำขยาย และตัวเลขครบและถูก 0–4 LLM
terms — ศัพท์ใน glossary เป็นภาษาอังกฤษ ไม่มีคำแปลไทย 0–4 โค้ด
fluency — อ่านเป็นภาษาไทยวิชาการที่เป็นธรรมชาติ 0–2 LLM
def term_problems(draft):
    text = draft.lower()
    return [t for t in GLOSSARY
            if t not in text or f"({t}" in text or f"{t})" in text]

print(term_problems("ลด การสร้างข้อมูลเท็จ (hallucination) ด้วย fine-tuning"))
['hallucination', 'small language model', 'retrieval-augmented generation', 'benchmark', 'latency']
CRITERIA = """1. meaning (0-4): every claim, qualifier (e.g. small, lightweight) and number of the
   source is present and correct in the Thai draft.
2. fluency (0-2): reads like natural Thai academic writing.
English technical terms inside the Thai text are expected and correct; do not penalize them."""
SCHEMA = {"type": "object", "additionalProperties": False,
          "required": ["meaning", "fluency", "critique"],
          "properties": {"meaning": {"type": "integer"}, "fluency": {"type": "integer"},
                         "critique": {"type": "string"}}}
def evaluate(source, draft):
    review = ask_llm(
        "You are a strict editor of English-to-Thai translations.\n"
        f"Score the Thai draft against these criteria:\n{CRITERIA}\n\n"
        f"Source (English):\n{source}\n\nThai draft:\n{draft}\n\n"
        # ✏️ TODO 1 (▶ วิดีโอ 3:48): เรียก evaluator ด้วย temperature 0 และบังคับคำตอบตาม SCHEMA
        "In critique, list at most 3 concrete problems and how to fix each, one short line each "
        "(in English). If nothing is wrong, say so.",
        temperature=___, schema=___)
    # ✏️ TODO 2 (▶ วิดีโอ 4:08): ตรวจศัพท์ด้วยโค้ด ถ้ามีคำที่ผิด ให้ต่อรายการคำเหล่านั้นเข้าไปใน critique
    bad = ___
    if bad:
        review["critique"] += ___
    # ✏️ TODO 3 (▶ วิดีโอ 4:21): คิดคะแนน terms (4 หักคำละ 2 ไม่ต่ำกว่า 0) แล้วรวมสามเกณฑ์เป็น score เต็ม 10
    review["bad_terms"] = bad
    review["terms"] = ___
    review["score"] = ___
    return review
def evaluate(source, draft):
    review = ask_llm(
        "You are a strict editor of English-to-Thai translations.\n"
        f"Score the Thai draft against these criteria:\n{CRITERIA}\n\n"
        f"Source (English):\n{source}\n\nThai draft:\n{draft}\n\n"
        "In critique, list at most 3 concrete problems and how to fix each, one short line each "
        "(in English). If nothing is wrong, say so.",
        temperature=0, schema=SCHEMA)
    bad = term_problems(draft)
    if bad:
        review["critique"] += ("\nGlossary check: write these terms in English only, with no Thai "
                               f"translation and no parentheses: {', '.join(bad)}")
    review["bad_terms"] = bad
    review["terms"] = max(0, 4 - 2 * len(bad))
    review["score"] = review["meaning"] + review["terms"] + review["fluency"]
    return review

3. Evaluator-optimizer loop

generate → evaluate → (ผ่าน threshold? หยุด) → ต่อ critique เข้า context → generate ใหม่ สูงสุด budget รอบ

def evaluator_optimizer(source, threshold=9, budget=3):
    context = TASK
    for rnd in range(1, budget + 1):
        # ✏️ TODO 4 (▶ วิดีโอ 5:06): แต่ละรอบ ให้ generator สร้างร่างจาก context แล้วส่งร่างให้ evaluator ตรวจ
        draft = ___
        review = ___
        print(f"\n--- round {rnd}: score {review['score']}/10 "
              f"(meaning {review['meaning']}, terms {review['terms']}, fluency {review['fluency']})")
        print(draft)
        print("❌ bad terms:", review["bad_terms"] or "none")
        print("🧐 critique:", review["critique"])
        # ✏️ TODO 5 (▶ วิดีโอ 5:33): ถ้าคะแนนถึง threshold ให้หยุดแล้วคืนร่างนี้
        if ___:
            print(f"✅ passed in round {rnd}")
            return draft
        # ✏️ TODO 6 (▶ วิดีโอ 5:39): ต่อร่างเดิม + critique ของ evaluator เข้าไปใน context ของ generator
        context += ___
    print(f"⛔ retry budget of {budget} rounds used up, returning the last draft")
    return draft
def evaluator_optimizer(source, threshold=9, budget=3):
    context = TASK
    for rnd in range(1, budget + 1):
        draft = ask_llm(context, temperature=0.7)
        review = evaluate(source, draft)
        print(f"\n--- round {rnd}: score {review['score']}/10 "
              f"(meaning {review['meaning']}, terms {review['terms']}, fluency {review['fluency']})")
        print(draft)
        print("❌ bad terms:", review["bad_terms"] or "none")
        print("🧐 critique:", review["critique"])
        if review["score"] >= threshold:
            print(f"✅ passed in round {rnd}")
            return draft
        context += (f"\n\nYour previous draft:\n{draft}\n\n"
                    f"Editor's critique (score {review['score']}/10):\n{review['critique']}\n\n"
                    "Write an improved full translation. Reply with the translation only.")
    print(f"⛔ retry budget of {budget} rounds used up, returning the last draft")
    return draft
final = evaluator_optimizer(ABSTRACT)

--- round 1: score 6/10 (meaning 4, terms 0, fluency 2)
บทคัดย่อ:

งานวิจัยนี้ทำการศึกษาปัญหาการสร้างข้อมูลที่ไม่เป็นความจริง (hallucination) ในโมเดลภาษาขนาดเล็ก (small language models) ที่ใช้ตอบคำถามนิสิตนักศึกษาเกี่ยวกับเนื้อหาในบทเรียน โดยเราได้ใช้วิธีการผสมผสานระหว่างการสร้างคำตอบด้วยการสืบค้นข้อมูลประกอบ (retrieval-augmented generation) และการปรับจูนโมเดลแบบน้ำหนักเบา (lightweight fine-tuning) จากชุดข้อมูลคู่คำถาม-คำตอบจำนวน 4,200 คู่ จากรายวิชาในมหาวิทยาลัย 3 วิชา จากการทดสอบกับชุดข้อมูลมาตรฐาน (benchmark) ใหม่จำนวน 600 คำถาม พบว่าวิธีการของเราสามารถลดการสร้างข้อมูลที่ไม่เป็นความจริงลงได้ถึง 31% ในขณะที่ยังคงรักษาความเร็วในการตอบคำถามให้ต่ำกว่าสองวินาที ทั้งนี้เราได้เปิดเผยชุดข้อมูลมาตรฐานและซอร์สโค้ดเพื่อให้สามารถนำไปต่อยอดในงานวิจัยอื่น ๆ ได้ต่อไป
❌ bad terms: ['hallucination', 'small language model', 'retrieval-augmented generation', 'fine-tuning', 'benchmark', 'latency']
🧐 critique: Nothing is wrong.
Glossary check: write these terms in English only, with no Thai translation and no parentheses: hallucination, small language model, retrieval-augmented generation, fine-tuning, benchmark, latency

--- round 2: score 10/10 (meaning 4, terms 4, fluency 2)
บทคัดย่อ:

งานวิจัยนี้ทำการศึกษา hallucination ใน small language model ที่ใช้ตอบคำถามนิสิตนักศึกษาเกี่ยวกับเนื้อหาในบทเรียน โดยเราได้ใช้วิธีการผสมผสานระหว่าง retrieval-augmented generation และ fine-tuning แบบน้ำหนักเบาจากชุดข้อมูลคู่คำถาม-คำตอบจำนวน 4,200 คู่ จากรายวิชาในมหาวิทยาลัย 3 วิชา จากการทดสอบกับ benchmark ใหม่จำนวน 600 คำถาม พบว่าวิธีการของเราสามารถลด hallucination ลงได้ถึง 31% ในขณะที่ยังคงรักษา latency ในการตอบคำถามให้ต่ำกว่าสองวินาที ทั้งนี้เราได้เปิดเผย benchmark และซอร์สโค้ดเพื่อให้สามารถนำไปต่อยอดในงานวิจัยอื่น ๆ ได้ต่อไป
❌ bad terms: none
🧐 critique: Nothing is wrong.
✅ passed in round 2

สรุป

องค์ประกอบ (§19.1.5) ในโค้ด
Generator ask_llm(context, temperature=0.7)
Evaluator แยกตัว + เกณฑ์ชัดเจน evaluate() + CRITERIA + SCHEMA, temperature 0 + term_problems() (ตรวจศัพท์ด้วยโค้ด)
Threshold threshold=9
Critique ต่อเข้า context context += ...
Retry budget budget=3

Evaluator-optimizer vs Reflexion (EP05): ที่นี่ evaluator แยกตัว ตรวจตามเกณฑ์ที่ชัดเจนใน loop ที่มีจำนวนรอบตายตัว ส่วน Reflexion เก็บบทเรียนไว้ใน memory ข้ามความพยายามหลายครั้ง

ลองทำต่อ: ตั้ง threshold=10, budget=1 แล้วดูว่า guard ทำงานอย่างไร หรือเพิ่มคำใหม่ใน GLOSSARY (เช่น “question-answer pairs”) แล้วดูว่า critique เปลี่ยนไปอย่างไร