Lab 2 — Structured output
Lab walkthrough · EP02 Prompt, Structured Output และ Hallucination
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP02 Prompt, Structured Output และ Hallucination
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
ใน Lab 1 ผู้ช่วยอาจารย์ตอบได้แค่ป้ายเดียว คราวนี้เราอยากได้ แบบฟอร์ม 4 ช่อง จากอีเมลแต่ละฉบับ: เจตนา (intent), ความด่วน (urgency), รหัสวิชา (course) และสรุปหนึ่งประโยค (summary) — ให้โปรแกรมเอาไปใช้ต่อได้ทันที
สิ่งที่จะได้เรียน (บันไดสามขั้นจากคลิปทฤษฎี)
- ขอ JSON ใน prompt — แล้วดูว่า
json.loadsผ่านกี่ฉบับ - เขียน schema เป็น class ด้วย Pydantic แล้ว validate ทุกช่อง
- ส่ง schema ให้ API ผ่าน
response_format— รูปแบบถูกแน่นอน แต่ ถูกรูปแบบ ≠ ถูกต้อง - ออกแบบ schema ให้ดีขึ้น: คำอธิบายช่อง, enum เป็นรหัสสั้นๆ, validator ของเราเอง และถามใหม่เมื่อไม่ผ่าน
อีเมลใน lab นี้เป็น ข้อมูลจำลองที่เขียนขึ้นเพื่อการสอน ส่วนคำตอบของ model ทั้งหมดมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §1.12.11, §1.13.5, §19.3 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
เหมือน Lab 1: Python 3.10+ หรือ Colab และ OPENROUTER_API_KEY ใน Colab Secrets หรือไฟล์ .env (วิธีตั้งค่า key และเหตุผลที่เลือก model กับ provider อยู่ใน Lab 1)
%pip install -q "openai>=1.50" python-dotenv "pydantic>=2.7"import os, json, re
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())
MODEL = "google/gemma-4-26b-a4b-it"
PROVIDER = {"order": ["parasail/bf16"], "allow_fallbacks": False}
EXTRA = {"reasoning": {"enabled": False}, "provider": PROVIDER}
def ask(messages, **kw):
resp = client.chat.completions.create(model=MODEL, messages=messages, extra_body=EXTRA, **kw)
return resp.choices[0].message.content, resp.usage.completion_tokensEMAILS = [
"เรียนอาจารย์ค่ะ หนูป่วยเป็นไข้หวัดใหญ่ ขอส่งการบ้านครั้งที่ 2 วิชา AI301 ช้าไป 3 วันได้ไหมคะ แนบใบรับรองแพทย์มาด้วยค่ะ",
"อาจารย์ครับ สอบกลางภาคออกถึงบทไหนครับ",
"ระบบ LMS ล่มตอนผมกดส่งงาน CS214 แล้วโดนหักคะแนนส่งช้า ผมว่าไม่ยุติธรรมครับ",
"ขอเลื่อนส่งรายงานกลุ่มเป็นวันจันทร์ได้ไหมครับ สมาชิกในกลุ่มติดสอบวิชาอื่น",
"Lab 3 ของวิชา AI301 ต้องใช้ API key ของตัวเองหรือเปล่าคะ",
"ผมส่งการบ้านไปสองรอบแล้วแต่คะแนนยังขึ้นศูนย์ ช่วยตรวจสอบด้วยครับ",
]1. ขั้นที่หนึ่ง: ขอ JSON ใน prompt
วาง schema ไว้ ก่อน ข้อมูล (schema-first) และสั่งว่า “ตอบเป็น JSON เท่านั้น” — แบบตัวอย่างอีเมลลูกค้าในตำรา
PROMPT_JSON = """อ่านอีเมลนักศึกษาแล้วตอบเป็น JSON เท่านั้น
Schema:
{"intent": "คำถาม|ขอเลื่อนส่ง|ร้องเรียน", "urgency": "low|medium|high", "course": "string or null", "summary": "one sentence summary"}
อีเมล: """
answers = [ask([{"role": "user", "content": PROMPT_JSON + email}], max_tokens=300)[0] for email in EMAILS]
print(answers[0])```json
{
"intent": "คำถาม",
"urgency": "medium",
"course": "AI301",
"summary": "The student is requesting a three-day ขอเลื่อนส่ง for homework 2 due to illness and has provided a medical certificate."
}
```
# ✏️ TODO 1 (▶ วิดีโอ 1:54): แปลงคำตอบ text เป็น dict ด้วย json
ok = 0
for text in answers:
try:
___
ok += 1
except json.JSONDecodeError as err:
print("✗", err, "| เริ่มด้วย", repr(text[:8]))
print(f"json.loads ผ่าน {ok}/{len(answers)}")ok = 0
for text in answers:
try:
json.loads(text)
ok += 1
except json.JSONDecodeError as err:
print("✗", err, "| เริ่มด้วย", repr(text[:8]))
print(f"json.loads ผ่าน {ok}/{len(answers)}")✗ Expecting value: line 1 column 1 (char 0) | เริ่มด้วย '```json\n'
✗ Expecting value: line 1 column 1 (char 0) | เริ่มด้วย '```json\n'
✗ Expecting value: line 1 column 1 (char 0) | เริ่มด้วย '```json\n'
✗ Expecting value: line 1 column 1 (char 0) | เริ่มด้วย '```json\n'
✗ Expecting value: line 1 column 1 (char 0) | เริ่มด้วย '```json\n'
✗ Expecting value: line 1 column 1 (char 0) | เริ่มด้วย '```json\n'
json.loads ผ่าน 0/6
def strip_fences(text):
m = re.search(r"\{.*\}", text, re.DOTALL)
return m.group(0) if m else text
data = [json.loads(strip_fences(t)) for t in answers]
print(data[0]){'intent': 'คำถาม', 'urgency': 'medium', 'course': 'AI301', 'summary': 'The student is requesting a three-day ขอเลื่อนส่ง for homework 2 due to illness and has provided a medical certificate.'}
2. เขียน schema เป็น class ด้วย Pydantic
Literal[...] = enum (เลือกได้แค่ค่าในรายการ) · str | None = ข้อความหรือ null · extra="forbid" = ห้ามมีช่องเกิน
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validatorclass EmailInfo(BaseModel):
model_config = ConfigDict(extra="forbid")
# ✏️ TODO 2 (▶ วิดีโอ 3:21): ประกาศช่อง urgency ให้เลือกได้แค่ low / medium / high
intent: Literal["คำถาม", "ขอเลื่อนส่ง", "ร้องเรียน"]
urgency: ___
course: str | None
summary: strclass EmailInfo(BaseModel):
model_config = ConfigDict(extra="forbid")
intent: Literal["คำถาม", "ขอเลื่อนส่ง", "ร้องเรียน"]
urgency: Literal["low", "medium", "high"]
course: str | None
summary: strfor d in data:
info = EmailInfo.model_validate(d)
print(info.intent, info.urgency, repr(info.course))คำถาม medium 'AI301'
คำถาม medium None
ร้องเรียน medium 'CS214'
ขอเลื่อนส่ง medium None
คำถาม medium 'AI301'
ร้องเรียน medium None
try:
EmailInfo.model_validate({"intent": "ขอเลื่อนส่ง", "urgency": "ด่วนมากกก"})
except ValidationError as err:
print(err)3 validation errors for EmailInfo
urgency
Input should be 'low', 'medium' or 'high' [type=literal_error, input_value='ด่วนมากกก', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/literal_error
course
Field required [type=missing, input_value={'intent': 'ขอเลื่อนส่ง', '...ncy': 'ด่วนมากกก'}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.14/v/missing
summary
Field required [type=missing, input_value={'intent': 'ขอเลื่อนส่ง', '...ncy': 'ด่วนมากกก'}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.14/v/missing
3. ขั้นที่สอง: ส่ง schema ให้ API
response_format แบบ json_schema + strict: True ให้ฝั่งผู้ให้บริการบังคับรูปแบบตอน generate (constrained decoding) → ไม่มี backtick ไม่มีคำนำหน้า และ class เดียวกันใช้ได้ทั้งสองทาง
# ✏️ TODO 3 (▶ วิดีโอ 4:28): แปลง class model เป็น JSON schema ด้วย Pydantic
def schema_of(model):
return {"type": "json_schema",
"json_schema": {"name": model.__name__, "strict": True, "schema": ___}}
print(json.dumps(EmailInfo.model_json_schema()["properties"]["urgency"], ensure_ascii=False))def schema_of(model):
return {"type": "json_schema",
"json_schema": {"name": model.__name__, "strict": True, "schema": model.model_json_schema()}}
print(json.dumps(EmailInfo.model_json_schema()["properties"]["urgency"], ensure_ascii=False)){"enum": ["low", "medium", "high"], "title": "Urgency", "type": "string"}
# ✏️ TODO 4 (▶ วิดีโอ 4:52): ส่ง schema ของ EmailInfo ให้ API ผ่าน response_format
results = []
for email in EMAILS:
text, _ = ask([{"role": "user", "content": "อ่านอีเมลนักศึกษาแล้วสรุปข้อมูล\nอีเมล: " + email}],
max_tokens=300, response_format=___)
info = EmailInfo.model_validate_json(text)
results.append(info)
print(info.intent, info.urgency, repr(info.course))results = []
for email in EMAILS:
text, _ = ask([{"role": "user", "content": "อ่านอีเมลนักศึกษาแล้วสรุปข้อมูล\nอีเมล: " + email}],
max_tokens=300, response_format=schema_of(EmailInfo))
info = EmailInfo.model_validate_json(text)
results.append(info)
print(info.intent, info.urgency, repr(info.course))ขอเลื่อนส่ง medium 'AI301'
คำถาม low None
ร้องเรียน medium 'CS214'
ขอเลื่อนส่ง medium 'not specified'
คำถาม low 'AI301'
ขอเลื่อนส่ง medium 'not specified'
4. ออกแบบ schema ให้ดีขึ้น
Field(description=...)— บอก model ว่าแต่ละช่องหมายถึงอะไร (ไปอยู่ใน JSON schema ด้วย)- enum เป็น รหัสภาษาอังกฤษสั้นๆ + คำอธิบายภาษาไทย — ตอนทดสอบ ป้ายภาษาไทยใน schema ทำให้อีเมลฉบับที่หก (คะแนนขึ้นศูนย์) ถูกจัดเป็น “ขอเลื่อนส่ง” ทั้ง 4 รอบ ส่วนรหัสอังกฤษถูกทุกฉบับ 24/24
field_validator— ตรวจสิ่งที่ schema บอกไม่ได้ เช่น รหัสวิชาต้องเป็นตัวอักษร 2–3 ตัวตามด้วยตัวเลข 3 ตัว
class StudentEmail(BaseModel):
model_config = ConfigDict(extra="forbid")
intent: Literal["question", "extension", "complaint"] = Field(
description="question = ถามข้อมูล · extension = ขอส่งงานช้ากว่ากำหนด · complaint = แจ้งปัญหาหรือไม่พอใจ")
urgency: Literal["low", "medium", "high"] = Field(description="high = มีกำหนดส่งหรือคะแนนเสีย")
course: str | None = Field(description="รหัสวิชาที่เขียนในอีเมล เช่น AI301 ถ้าไม่มีให้เป็น null")
summary: str = Field(description="สรุปหนึ่งประโยค")
# ✏️ TODO 5 (▶ วิดีโอ 6:01): ถ้า course ไม่ใช่ None และไม่ตรงรูปแบบ ตัวอักษร 2–3 ตัว + ตัวเลข 3 ตัว ให้โยน ValueError
@field_validator("course")
@classmethod
def must_be_code(cls, v):
if v is not None and not re.fullmatch(___, v):
raise ValueError(f"ไม่ใช่รหัสวิชา: {v!r}")
return vclass StudentEmail(BaseModel):
model_config = ConfigDict(extra="forbid")
intent: Literal["question", "extension", "complaint"] = Field(
description="question = ถามข้อมูล · extension = ขอส่งงานช้ากว่ากำหนด · complaint = แจ้งปัญหาหรือไม่พอใจ")
urgency: Literal["low", "medium", "high"] = Field(description="high = มีกำหนดส่งหรือคะแนนเสีย")
course: str | None = Field(description="รหัสวิชาที่เขียนในอีเมล เช่น AI301 ถ้าไม่มีให้เป็น null")
summary: str = Field(description="สรุปหนึ่งประโยค")
@field_validator("course")
@classmethod
def must_be_code(cls, v):
if v is not None and not re.fullmatch(r"[A-Z]{2,3}\d{3}", v):
raise ValueError(f"ไม่ใช่รหัสวิชา: {v!r}")
return vtry:
StudentEmail.model_validate({"intent": "question", "urgency": "low", "course": "ไม่ระบุ", "summary": "ถามขอบเขตสอบ"})
except ValidationError as err:
print(err.errors()[0]["msg"])Value error, ไม่ใช่รหัสวิชา: 'not specified'
SYSTEM = "คุณคือผู้ช่วยอาจารย์ อ่านอีเมลนักศึกษาใน <email> แล้วกรอกข้อมูลตาม schema ใช้เฉพาะข้อมูลที่อยู่ในอีเมล"
def extract(email, tries=3):
msgs = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"<email>\n{email}\n</email>"}]
for attempt in range(1, tries + 1):
text, _ = ask(msgs, max_tokens=300, response_format=schema_of(StudentEmail))
try:
return StudentEmail.model_validate_json(text)
# ✏️ TODO 6 (▶ วิดีโอ 6:57): ดัก ValidationError แล้วพิมพ์ว่ารอบไหนไม่ผ่านเพราะอะไร จากนั้นวนถามใหม่
except ___ as err:
print(f" รอบ {attempt} ไม่ผ่าน:", err.errors()[0]["msg"])
return NoneSYSTEM = "คุณคือผู้ช่วยอาจารย์ อ่านอีเมลนักศึกษาใน <email> แล้วกรอกข้อมูลตาม schema ใช้เฉพาะข้อมูลที่อยู่ในอีเมล"
def extract(email, tries=3):
msgs = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"<email>\n{email}\n</email>"}]
for attempt in range(1, tries + 1):
text, _ = ask(msgs, max_tokens=300, response_format=schema_of(StudentEmail))
try:
return StudentEmail.model_validate_json(text)
except ValidationError as err:
print(f" รอบ {attempt} ไม่ผ่าน:", err.errors()[0]["msg"])
return NoneTHAI = {"question": "คำถาม", "extension": "ขอเลื่อนส่ง", "complaint": "ร้องเรียน"}
for email in EMAILS:
info = extract(email)
if info:
print(THAI[info.intent], info.urgency, repr(info.course), "|", info.summary)Extension medium 'AI301' | The student is requesting a three-day ขอเลื่อนส่ง for homework 2 due to the flu and has provided a medical certificate as proof.
Question medium None | The student is asking which chapters will be included in the midterm exam.
Complaint medium 'CS214' | The student is complaining about losing marks for late submission because the LMS crashed during their work submission.
Extension medium None | The student is requesting to move the group report deadline to Monday because group members have an exam in another course.
Question medium 'AI301' | The student is asking if they need their own API key for Lab 3.
Question medium None | The student is reporting that their score shows zero despite submitting their homework twice and is requesting a manual check.
สรุป
| ขั้น | ผลใน lab นี้ |
|---|---|
| ขอ JSON ใน prompt | json.loads ผ่าน 0/6 — ครอบด้วย ```json ทุกฉบับ |
| ตัดส่วนเกินด้วย regex + Pydantic | ผ่าน 6/6 (แต่เป็นการปะผุ) |
response_format + schema เปล่าๆ |
ถูกรูปแบบทุกฉบับ แต่ course = “ไม่ระบุ” แทน null |
| คำอธิบายช่อง + รหัสอังกฤษ + validator + ถามใหม่ | ถูกทุกช่อง · course = รหัสวิชาหรือ None |
แบบฝึกหัด: เพิ่มช่อง deadline: str | None (วันที่ที่นักศึกษาขอ) พร้อม validator ที่ยอมรับเฉพาะรูปแบบ YYYY-MM-DD แล้วทดสอบกับอีเมลที่มีวันที่และไม่มีวันที่
▶ ถัดไป: Lab 3 — Hallucination จับ model ตอนแต่งเรื่อง ด้วยการถามซ้ำ ความน่าจะเป็นของ token และ grounding