Skip to main content

Lab 1 — Prompt Chaining + Validation Gates (§19.1.1)

Lab walkthrough · EP04 Workflow Patterns

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

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

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

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

ผู้ช่วยอาจารย์ของ Cogito Learn จะสรุป abstract ของ paper เป็นภาษาไทยให้นักศึกษาปีหนึ่ง ด้วย chain ของ LLM call ที่ลำดับตายตัว และมี gate ตรวจคุณภาพระหว่างขั้น

text → 🚦 input gate (LLM): เป็น abstract ไหม?
     → ① ดึงประเด็นหลัก → 🚦 gate 1 (code): ครบ 3 ประเด็นไหม?
     → ② เขียนสรุปภาษาไทย → 🚦 gate 2 (code): ไม่เกิน 5 บรรทัดไหม?

สิ่งที่จะได้เรียน

  1. เรียก LLM ผ่าน API และขอคำตอบเป็น JSON (structured output)
  2. เขียน gate ทั้งแบบโค้ดธรรมดาและแบบใช้ LLM
  3. ต่อขั้นเป็น chain ที่หยุดทันทีเมื่อ gate ไม่ผ่าน และเปิดดูผลระหว่างทางได้ทุกขั้น

ข้อมูลใน lab นี้ (abstract และประกาศ) เป็น ข้อมูลจำลองที่เขียนขึ้นเพื่อการสอน ส่วนคำตอบของ model ทั้งหมดมาจากการรันจริง

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.1.1 (p.369) — CC BY-SA 4.0

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key สมัครที่ openrouter.ai → Keys → Create Key
Packages openai, python-dotenv (ติดตั้งใน cell ถัดไป)

ใส่ API key

  • Colab: ไอคอน 🔑 Secrets → ชื่อ OPENROUTER_API_KEY → เปิด Notebook access
  • เครื่องตัวเอง: สร้างไฟล์ .env ในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัด OPENROUTER_API_KEY=sk-or-...

⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env

%pip install -q "openai>=1.50" python-dotenv

1. เรียก LLM ผ่าน OpenRouter

เราใช้ Gemma 4 26B (open weights) ผ่าน OpenRouter ซึ่งใช้ API แบบ OpenAI-compatible ทุกขั้นของ chain จะเรียก LLM ผ่านฟังก์ชันเดียวคือ ask_llm()

ล็อก provider ไว้เจ้าเดียว (deepinfra/fp8) เพราะ model ชื่อเดียวกันให้ผลต่างกันในแต่ละเจ้า · ทุก lab ของ EP04 ใช้เจ้านี้ · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-15: 6 ใน 6 ครั้งได้ 429 “rate-limited upstream”)

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
print(ask_llm("Explain prompt chaining in one sentence.", temperature=0))
Prompt chaining is the process of breaking a complex task into a sequence of smaller, interconnected steps where the output of one prompt serves as the input for the next.

2. ข้อมูลทดสอบ (จำลอง)

  • ABSTRACT — abstract ของ paper สมมติ เรื่องผู้ช่วยสอนแบบ retrieval-augmented
  • NOTICE — ประกาศของรายวิชา ซึ่ง ไม่ใช่ abstract (ไว้ทดสอบว่า gate หยุด chain ได้)
ABSTRACT = """We study whether a retrieval-augmented teaching assistant helps first-year students debug
Python assignments. In a 10-week course with 240 students, half used an assistant that first retrieves
the course's lecture notes, and half used the same LLM without retrieval. The retrieval group fixed 31%
more bugs on their own and asked human TAs 40% fewer repeated questions, but the benefit disappeared
for advanced students. We release anonymised interaction logs for further research."""

NOTICE = """Reminder for CS101 students: the midterm exam has moved from Room 402 to the main hall.
Please bring your student ID card and arrive 15 minutes early. Office hours this week are cancelled."""

3. Validation gates

ตำรา: gate ระหว่างขั้น จับข้อผิดพลาดตั้งแต่เนิ่นๆ ก่อนจะไหลไปขั้นถัดไป และเป็นได้ทั้ง programmatic (โค้ด) หรือ LLM-based

ทุก gate คืนค่าแบบเดียวกัน: (ok, why) — ผ่านไหม และเพราะอะไร

# ✏️ TODO 1 (▶ วิดีโอ 5:49): gate แบบโค้ด: ผ่านเมื่อได้ประเด็นหลักครบ 3 ข้อพอดี
def gate_points(points):
    return ___, f"key points: {len(points)} (need 3)"

# ✏️ TODO 2 (▶ วิดีโอ 6:01): gate แบบโค้ด: นับจำนวนบรรทัดของสรุป แล้วผ่านเมื่อไม่เกิน max_lines

def gate_lines(text, max_lines=5):
    n = ___
    return ___, f"lines: {n} (limit {max_lines})"
def gate_points(points):
    return len(points) == 3, f"key points: {len(points)} (need 3)"

def gate_lines(text, max_lines=5):
    n = len(text.strip().splitlines())
    return n <= max_lines, f"lines: {n} (limit {max_lines})"
print(gate_points(["problem", "method", "finding"]))
print(gate_points(["only one point"]))
print(gate_lines("1\n2\n3\n4\n5\n6"))
(True, 'key points: 3 (need 3)')
(False, 'key points: 1 (need 3)')
(False, 'lines: 6 (limit 5)')
IS_ABSTRACT = {"type": "object", "additionalProperties": False, "required": ["is_abstract", "reason"],
               "properties": {"is_abstract": {"type": "boolean"}, "reason": {"type": "string"}}}

# ✏️ TODO 3 (▶ วิดีโอ 6:54): gate แบบ LLM: ถามด้วย temperature 0 พร้อม schema แล้วคืน (ok, why) จาก dict ที่ได้

def gate_is_abstract(text):
    check = ask_llm("Is the following text the abstract of a research paper? Give a one-sentence reason.\n\n"
                    + text, temperature=___, schema=___)
    return ___, ___
IS_ABSTRACT = {"type": "object", "additionalProperties": False, "required": ["is_abstract", "reason"],
               "properties": {"is_abstract": {"type": "boolean"}, "reason": {"type": "string"}}}

def gate_is_abstract(text):
    check = ask_llm("Is the following text the abstract of a research paper? Give a one-sentence reason.\n\n"
                    + text, temperature=0, schema=IS_ABSTRACT)
    return check["is_abstract"], check["reason"]

4. ขั้นของ chain — แต่ละขั้นเป็น LLM call แยก

ขั้น งาน temperature ทำไม
gate เป็น abstract ไหม 0 ตัดสินให้นิ่ง
① ดึง 3 ประเด็น (JSON) 0.2 ซื่อตรงต่อต้นฉบับ
② เขียนสรุปภาษาไทย 0.7 ภาษาเป็นธรรมชาติ
POINTS = {"type": "object", "additionalProperties": False, "required": ["points"],
          "properties": {"points": {"type": "array", "minItems": 1, "items": {"type": "string"}}}}

def extract_points(abstract):
    prompt = ("Extract exactly 3 key points from this research abstract: the problem, the method "
              "and the main finding. One short English sentence each. Use only facts stated in the text: "
              "no new adjectives, judgements or claims.\n\n" + abstract)
    return ask_llm(prompt, temperature=0.2, schema=POINTS)["points"]

# ✏️ TODO 4 (▶ วิดีโอ 8:01): นำผลของขั้นที่หนึ่ง (list ของประเด็น) มาต่อเป็นข้อความทีละบรรทัด ขึ้นต้นด้วย "- "

def write_thai(points):
    bullets = ___
    prompt = ("Write a Thai summary for first-year university students using only these key points. "
              "Do not add any fact, adjective or claim that is not in the points. "
              "At most 5 lines, one sentence per line, no blank lines, keep technical terms in English. "
              "Return only the summary.\n\n" + bullets)
    return ask_llm(prompt, temperature=0.7)
POINTS = {"type": "object", "additionalProperties": False, "required": ["points"],
          "properties": {"points": {"type": "array", "minItems": 1, "items": {"type": "string"}}}}

def extract_points(abstract):
    prompt = ("Extract exactly 3 key points from this research abstract: the problem, the method "
              "and the main finding. One short English sentence each. Use only facts stated in the text: "
              "no new adjectives, judgements or claims.\n\n" + abstract)
    return ask_llm(prompt, temperature=0.2, schema=POINTS)["points"]

def write_thai(points):
    bullets = "\n".join(f"- {p}" for p in points)
    prompt = ("Write a Thai summary for first-year university students using only these key points. "
              "Do not add any fact, adjective or claim that is not in the points. "
              "At most 5 lines, one sentence per line, no blank lines, keep technical terms in English. "
              "Return only the summary.\n\n" + bullets)
    return ask_llm(prompt, temperature=0.7)

5. ต่อเป็น chain

ระบบ (ไม่ใช่ model) เป็นคนกำหนดลำดับ: gate → ① → gate → ② → gate — gate ไหนไม่ผ่าน chain หยุดทันที

def gate(name, result):
    ok, why = result
    print(f"🚦 {name}: {'✅ pass' if ok else '🛑 STOP'} — {why}")
    return ok
# ✏️ TODO 5 (▶ วิดีโอ 8:52): ถ้า gate แรก (LLM) ไม่ผ่าน ให้หยุด chain ทันทีโดยคืน None
def summarize_chain(text, max_lines=5):
    if not gate("input gate · research abstract? (LLM)", ___):
        ___

    # ✏️ TODO 6 (▶ วิดีโอ 9:08): ขั้นที่หนึ่ง: ดึงประเด็น แล้วให้ gate_points ตรวจ ถ้าไม่ผ่านให้หยุด chain

    points = ___
    print("① key points:", *points, sep="\n   • ")
    if not gate("gate 1 · exactly 3 points? (code)", ___):
        return None

    summary = write_thai(points)
    print("② Thai summary:\n" + summary)
    if not gate(f"gate 2 · at most {max_lines} lines? (code)", gate_lines(summary, max_lines)):
        return None
    return summary
def summarize_chain(text, max_lines=5):
    if not gate("input gate · research abstract? (LLM)", gate_is_abstract(text)):
        return None

    points = extract_points(text)
    print("① key points:", *points, sep="\n   • ")
    if not gate("gate 1 · exactly 3 points? (code)", gate_points(points)):
        return None

    summary = write_thai(points)
    print("② Thai summary:\n" + summary)
    if not gate(f"gate 2 · at most {max_lines} lines? (code)", gate_lines(summary, max_lines)):
        return None
    return summary
result = summarize_chain(ABSTRACT)
🚦 input gate · research abstract? (LLM): ✅ pass — The text follows the standard structure of an abstract by stating the research objective, describing the methodology, summarizing the key findings, and mentioning the data availability.
① key points:
   • The study examines whether a retrieval-augmented teaching assistant helps first-year students debug Python assignments.
   • Half of 240 students used an assistant that retrieves lecture notes while the other half used the same LLM without retrieval.
   • The retrieval group fixed 31% more bugs on their own and asked human TAs 40% fewer repeated questions, but the benefit disappeared for advanced students.
🚦 gate 1 · exactly 3 points? (code): ✅ pass — key points: 3 (need 3)
② Thai summary:
การศึกษานี้ตรวจสอบว่า retrieval-augmented teaching assistant ช่วยนักศึกษาปีหนึ่งในการ debug Python assignments หรือไม่
นักศึกษา 240 คนแบ่งเป็นสองกลุ่มโดยครึ่งหนึ่งใช้ assistant ที่มี retrieval ส่วนอีกครึ่งใช้ LLM เดียวกันที่ไม่มี retrieval
กลุ่ม retrieval สามารถ fix bugs ได้ด้วยตนเองมากขึ้น 31% และถามคำถามเดิมกับ human TAs น้อยลง 40%
อย่างไรก็ตาม ประโยชน์ดังกล่าวหายไปเมื่อใช้กับนักศึกษาที่มีความสามารถระดับ advanced
🚦 gate 2 · at most 5 lines? (code): ✅ pass — lines: 4 (limit 5)
result = summarize_chain(NOTICE)
print("result:", result)
🚦 input gate · research abstract? (LLM): 🛑 STOP — The text is a logistical announcement or administrative notice intended for students rather than a summary of research findings and methodology.
result: None
result = summarize_chain(ABSTRACT, max_lines=2)
print("result:", result)
🚦 input gate · research abstract? (LLM): ✅ pass — The text summarizes the study's objective, methodology, key quantitative results, and data availability, which are the standard components of a research abstract.
① key points:
   • The study examines whether a retrieval-augmented teaching assistant helps first-year students debug Python assignments.
   • Researchers compared a group using an assistant that retrieves lecture notes against a group using the same LLM without retrieval in a 10-week course.
   • The retrieval group fixed 31% more bugs on their own and asked human TAs 40% fewer repeated questions, though the benefit disappeared for advanced students.
🚦 gate 1 · exactly 3 points? (code): ✅ pass — key points: 3 (need 3)
② Thai summary:
การศึกษานี้ตรวจสอบว่า retrieval-augmented teaching assistant ช่วยนักศึกษาปีหนึ่งในการ debug Python assignments หรือไม่
ผู้วิจัยเปรียบเทียบกลุ่มที่ใช้ assistant ที่ทำ retrieval lecture notes กับกลุ่มที่ใช้ LLM เดียวกันโดยไม่มี retrieval ในหลักสูตร 10 สัปดาห์
กลุ่ม retrieval แก้ไข bugs ได้ด้วยตนเองมากกว่า 31% และถามคำถามซ้ำกับ human TAs น้อยลง 40%
อย่างไรก็ตาม ประโยชน์ดังกล่าวหายไปสำหรับนักศึกษาที่มีความสามารถระดับ advanced
🚦 gate 2 · at most 2 lines? (code): 🛑 STOP — lines: 4 (limit 2)
result: None

สรุป

สิ่งที่ตำราบอก (§19.1.1) ในโค้ด
ลำดับ LLM call ที่ตายตัว summarize_chain() — gate → ① → gate → ② → gate
ส่งผลขั้นก่อนเป็น context ขั้นถัดไป write_thai(points) เห็นแค่ประเด็นจากขั้นที่หนึ่ง
gate จับข้อผิดพลาดตั้งแต่เนิ่นๆ NOTICE หยุดที่ input gate → ไม่เรียกขั้น ① ② · max_lines=2 หยุดที่ gate 2
gate เป็น LLM หรือโค้ดก็ได้ gate_is_abstract() (LLM) · gate_points(), gate_lines() (โค้ด)
แต่ละขั้นใช้ temperature ต่างกัน 0 · 0.2 · 0.7
ผลระหว่างทางเปิดดูได้ print() ทุกขั้น

ลองทำต่อ: เพิ่มขั้นที่ ③ ให้ LLM ตั้งชื่อเรื่องภาษาไทยไม่เกิน 10 คำ พร้อม gate ตรวจจำนวนคำ