Lab 6 — Workflow Patterns ด้วย LangGraph (§19.1, §25.3.1)
Lab walkthrough · EP04 Workflow Patterns
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP04 Workflow Patterns
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
ใน Lab 1–5 เราเขียน workflow ทั้งห้า pattern เองทุกบรรทัด lab นี้จะสร้างทั้งห้า pattern ใหม่ด้วย LangGraph framework ที่มอง workflow เป็น graph — node คือขั้นตอนหนึ่งขั้น, edge คือเส้นทางจากขั้นหนึ่งไปอีกขั้น
| LangGraph | ตรงกับที่เราเขียนเอง |
|---|---|
| State — dict ที่ไหลผ่าน graph | ตัวแปรที่ส่งต่อระหว่างฟังก์ชัน |
| Node — ฟังก์ชันที่รับ state คืนส่วนที่เปลี่ยน | ฟังก์ชันแต่ละขั้น (extract_points, classify, …) |
| Edge — ไปขั้นไหนต่อ | ลำดับบรรทัดในโค้ด |
| Conditional edge — เลือกทางตาม state | if ของ gate, ROUTES[label], while ของ loop |
| Reducer — วิธีรวมค่าจากหลาย node | list(pool.map(...)) |
Send — แตกงานตามจำนวนที่รู้ตอนรัน |
ex.map(run_worker, tasks) |
ทุก prompt และข้อมูลมาจาก Lab 1–5 (แสดงไว้ ไม่ได้พิมพ์ใหม่) สิ่งใหม่ใน lab นี้มีแค่ graph ข้อมูลทั้งหมดเป็น ข้อมูลจำลองที่เขียนขึ้นเพื่อการสอน ส่วนคำตอบของ model ทั้งหมดมาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.1 (p.369–371), §25.3.1 (p.461–464) — CC BY-SA 4.0
0. เตรียมเครื่อง
ต้องมี Python 3.10+ (หรือ Colab) และ OpenRouter API key — วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1
เวอร์ชันของ LangGraph ถูกล็อกไว้ เพราะ API ของ framework เปลี่ยนเร็ว ถ้าใช้เวอร์ชันใหม่กว่านี้ บางบรรทัดอาจต้องปรับ
%pip install -q "langgraph==1.2.16" "grandalf==0.8" "openai>=1.50" python-dotenvimport os, json, time, operator, subprocess, sys
from typing import TypedDict, Annotated
from openai import OpenAI
from langgraph.graph import StateGraph, START, END
from langgraph.types import Send# ---- จาก Lab 1: ตั้งค่า client + ask_llm ----
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 text1. Prompt chaining + gate → conditional edge (Lab 1)
START → input_gate ─(ผ่าน)→ extract ─(ครบ 3 ข้อ)→ write_thai → END
└─(ไม่ผ่าน)→ END └─(ไม่ครบ)→ END
ใน Lab 1 gate คือ if not gate(...): return None ที่นี่ gate กลายเป็น conditional edge ที่พาไป END
# ---- จาก Lab 1: ข้อมูลจำลอง + prompt เดิม ----
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."""
IS_ABSTRACT = {"type": "object", "additionalProperties": False, "required": ["is_abstract", "reason"],
"properties": {"is_abstract": {"type": "boolean"}, "reason": {"type": "string"}}}
POINTS = {"type": "object", "additionalProperties": False, "required": ["points"],
"properties": {"points": {"type": "array", "minItems": 1, "items": {"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"]
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)class ChainState(TypedDict, total=False):
text: str
ok: bool
why: str
points: list
summary: strdef input_gate(s):
ok, why = gate_is_abstract(s["text"])
return {"ok": ok, "why": why}
def extract(s):
points = extract_points(s["text"])
return {"points": points, "ok": len(points) == 3, "why": f"key points: {len(points)} (need 3)"}
def summarize(s):
return {"summary": write_thai(s["points"])}
def passed(s):
return "next" if s["ok"] else "stop"g = StateGraph(ChainState)
g.add_node("input_gate", input_gate)
g.add_node("extract", extract)
g.add_node("write_thai", summarize)
g.add_edge(START, "input_gate")
# ✏️ TODO 1 (▶ วิดีโอ 3:35): หลัง input_gate ให้เลือกทางด้วย passed: next → extract, stop → END
g.add_conditional_edges("input_gate", ___, {"next": ___, "stop": ___})
g.add_conditional_edges("extract", passed, {"next": "write_thai", "stop": END})
g.add_edge("write_thai", END)
chain = g.compile()g = StateGraph(ChainState)
g.add_node("input_gate", input_gate)
g.add_node("extract", extract)
g.add_node("write_thai", summarize)
g.add_edge(START, "input_gate")
g.add_conditional_edges("input_gate", passed, {"next": "extract", "stop": END})
g.add_conditional_edges("extract", passed, {"next": "write_thai", "stop": END})
g.add_edge("write_thai", END)
chain = g.compile()print(chain.get_graph().draw_ascii()) +-----------+
| __start__ |
+-----------+
*
*
*
+------------+
| input_gate |
+------------+....
... ....
. ....
.. ....
+---------+ ...
| extract | .
+---------+ .
... .. .
. .. .
.. .. .
+------------+ .. ...
| write_thai | . ....
+------------+*** . ....
***** . ....
*** . ....
*** . ...
+---------+
| __end__ |
+---------+
def show_steps(graph, state):
for step in graph.stream(state, stream_mode="updates"):
for node, update in step.items():
print(f"▶ {node}: {update}")
show_steps(chain, {"text": ABSTRACT})▶ input_gate: {'ok': True, 'why': 'The text follows the standard structure of an abstract by summarizing the research objective, methodology, key findings, and data availability.'}
▶ extract: {'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.'], 'ok': True, 'why': 'key points: 3 (need 3)'}
▶ write_thai: {'summary': 'การศึกษานี้ตรวจสอบว่า retrieval-augmented teaching assistant ช่วยนักศึกษาปีหนึ่งในการ debug งาน Python ได้หรือไม่\nผู้วิจัยเปรียบเทียบกลุ่มที่ใช้ assistant ที่ทำ retrieval lecture notes กับกลุ่มที่ใช้ LLM เดียวกันที่ไม่มี retrieval ในคอร์สเรียน 10 สัปดาห์\nกลุ่ม retrieval สามารถ fix bugs ได้ด้วยตนเองมากกว่า 31% และถามคำถามซ้ำกับ human TAs น้อยลง 40%\nอย่างไรก็ตาม ประโยชน์ดังกล่าวหายไปสำหรับ advanced students'}
show_steps(chain, {"text": NOTICE})▶ input_gate: {'ok': False, 'why': 'The text is a logistical announcement or administrative notice intended for students rather than a summary of a research study.'}
2. Routing → conditional edge จาก classifier (Lab 2)
ใน Lab 2 คือ label = classify(item) แล้ว ROUTES[label](item) ที่นี่ชื่อ route คือ ชื่อ node ที่จะไปต่อ
# ---- จาก Lab 2: คำถามจำลอง + classifier + handler เดิม ----
QUESTIONS = [
{"q": "How is ReAct different from prompt chaining?", "expect": "concept"},
{"q": "When is the midterm exam, and in which room?", "expect": "admin"},
{"q": "Why does my average function break on an empty list?",
"code": "def average(xs):\n return sum(xs) / len(xs)\nprint(average([]))", "expect": "code_error"},
]
ROUTE_SCHEMA = {"type": "object", "additionalProperties": False, "required": ["route"],
"properties": {"route": {"type": "string", "enum": ["concept", "code_error", "admin"]}}}
COURSE_INFO = ("Midterm exam: Saturday 12 December, 09:00-12:00, room CL-301. Final exam: Saturday 6 February, room CL-301. "
"Late lab submission: -10% per day, not accepted after 3 days. Office hours: Wed 13:00-15:00.")
def classify(item):
prompt = ("Classify this student question for a university AI course into exactly one route:\n"
"- concept: asks to explain an idea or theory (no code to debug)\n"
"- code_error: the student's code fails and they attached it\n"
"- admin: course logistics such as exam dates, rooms, deadlines, grading policy\n\n"
f"Question: {item['q']}\nAttached code: {item.get('code', '(none)')}")
return ask_llm(prompt, temperature=0, schema=ROUTE_SCHEMA)["route"]
def answer_concept(item):
return ask_llm("You are a patient teaching assistant for an AI course. Explain the idea clearly, "
"with one everyday analogy. Answer in Thai, at most 3 sentences.\n\n"
f"Question: {item['q']}")
def run_snippet(code):
r = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=10,
env={**os.environ, "PYTHON_COLORS": "0"})
return r.stderr.strip().splitlines()[-1] if r.returncode else "no error"
def answer_code(item):
error = run_snippet(item["code"])
return ask_llm("You are a Python debugging tutor. Using the REAL error below, explain the cause "
"in Thai in at most 2 sentences, then give one fixed line of code.\n\n"
f"Code:\n{item['code']}\n\nError when run: {error}")
def answer_admin(item):
return ask_llm("Answer the student's question using ONLY this course info, copying dates and rooms exactly. "
"If it is not there, say to ask the instructor. "
f"Answer in Thai, 1-2 sentences.\n\nCourse info: {COURSE_INFO}\n\nQuestion: {item['q']}",
temperature=0)class RouteState(TypedDict, total=False):
item: dict
route: str
answer: str
r = StateGraph(RouteState)
r.add_node("classify", lambda s: {"route": classify(s["item"])})
r.add_node("concept", lambda s: {"answer": answer_concept(s["item"])})
r.add_node("code_error", lambda s: {"answer": answer_code(s["item"])})
r.add_node("admin", lambda s: {"answer": answer_admin(s["item"])})
# ✏️ TODO 2 (▶ วิดีโอ 5:57): หลัง classify ให้อ่านช่อง route ใน state แล้วไป node ชื่อเดียวกัน
r.add_conditional_edges("classify", lambda s: ___, ["concept", "code_error", "admin"])
for n in ["concept", "code_error", "admin"]:
r.add_edge(n, END)
router = r.compile()
print(router.get_graph().draw_ascii())class RouteState(TypedDict, total=False):
item: dict
route: str
answer: str
r = StateGraph(RouteState)
r.add_node("classify", lambda s: {"route": classify(s["item"])})
r.add_node("concept", lambda s: {"answer": answer_concept(s["item"])})
r.add_node("code_error", lambda s: {"answer": answer_code(s["item"])})
r.add_node("admin", lambda s: {"answer": answer_admin(s["item"])})
r.add_edge(START, "classify")
r.add_conditional_edges("classify", lambda s: s["route"], ["concept", "code_error", "admin"])
for n in ["concept", "code_error", "admin"]:
r.add_edge(n, END)
router = r.compile()
print(router.get_graph().draw_ascii()) +-----------+
| __start__ |
+-----------+
*
*
*
+----------+
| classify |
...+----------+...
... . ...
.... . ....
.. . ..
+-------+ +------------+ +---------+
| admin |* | code_error | | concept |
+-------+ **** +------------+ ***+---------+
*** * ***
**** * ****
** * **
+---------+
| __end__ |
+---------+
for item in QUESTIONS:
out = router.invoke({"item": item})
print(f"expect {item['expect']:<10} → route {out['route']:<10} | {out['answer'][:90]}")expect concept → route concept | ReAct คือการให้ AI คิดและลงมือทำสลับกันไปมาในขั้นตอนเดียวเพื่อแก้ปัญหาที่ซับซ้อน ในขณะที่
expect admin → route admin | การสอบ Midterm คือวัน Saturday 12 December, 09:00-12:00 ที่ห้อง room CL-301
expect code_error → route code_error | ข้อผิดพลาดนี้เกิดจากการพยายามหารด้วยศูนย์ เนื่องจากลิสต์ `xs` เป็นค่าว่าง ทำให้ `len(xs)`
3. Parallelization → fan-out + reducer (Lab 3)
ใน Lab 3 เราใช้ ThreadPoolExecutor ให้ผู้ตรวจสามด้านทำงานพร้อมกัน ที่นี่ node ที่มี edge มาจากจุดเดียวกัน รันพร้อมกันเอง และ reducer บอกว่าจะรวมผลของทั้งสามอย่างไร
# ---- จาก Lab 3: โค้ดที่จะตรวจ + ผู้ตรวจเดิม ----
CODE = '''import sqlite3
DB_PASSWORD = "cogito123"
def find_failing(db, student_names):
result = ""
for n in student_names:
q = "SELECT name, score FROM grades WHERE name = '" + n + "'"
row = db.execute(q).fetchone()
if row and row[1] < 50:
if row[0] not in result.split(","):
result = result + row[0] + ","
return result
'''
NUMBERED = "\n".join(f"{i:2} | {line}" for i, line in enumerate(CODE.splitlines(), 1))
REVIEWERS = {
"security": "security only: injection, secrets in code, unsafe input handling",
"performance": "performance only: slow loops, repeated work, wasted database calls",
"style": "style only: naming, readability, magic numbers, return types",
}
FINDING = {"type": "object", "additionalProperties": False, "required": ["line", "severity", "issue"],
"properties": {"line": {"type": "integer"},
"severity": {"type": "string", "enum": ["high", "medium", "low"]},
"issue": {"type": "string"}}}
SCHEMA = {"type": "object", "additionalProperties": False, "required": ["findings"],
"properties": {"findings": {"type": "array", "minItems": 1, "items": FINDING}}}
def review(aspect):
start = time.perf_counter()
out = ask_llm(f"You are a code reviewer. Review this Python code for {REVIEWERS[aspect]}. "
f"Ignore every other kind of problem. Give at most 3 findings, each with its line number "
f"and a one-sentence issue.\n\n{NUMBERED}", temperature=0, schema=SCHEMA)
return aspect, out["findings"], time.perf_counter() - start# ✏️ TODO 3 (▶ วิดีโอ 7:29): ให้ช่อง results ต่อ list จากทุก node แทนการเขียนทับ (reducer)
class ReviewState(TypedDict):
results: Annotated[list, ___]class ReviewState(TypedDict):
results: Annotated[list, operator.add]def reviewer(aspect):
return lambda s: {"results": [review(aspect)]}
p = StateGraph(ReviewState)
for aspect in REVIEWERS:
p.add_node(aspect, reviewer(aspect))
p.add_edge(START, aspect)
p.add_edge(aspect, END)
reviews = p.compile()
print(reviews.get_graph().draw_ascii()) +-----------+
| __start__ |
**+-----------+***
*** * ***
**** * ****
** * **
+-------------+ +----------+ +-------+
| performance | | security | | style |
+-------------+** +----------+ ****+-------+
*** * ***
**** * ****
** * **
+---------+
| __end__ |
+---------+
start = time.perf_counter()
out = reviews.invoke({"results": []})
total = time.perf_counter() - start
for aspect, findings, sec in out["results"]:
print(f" {aspect:12} {sec:5.1f}s {len(findings)} findings")
print(f"⏱ graph: {total:.1f}s | sum of calls = {sum(r[2] for r in out['results']):.1f}s") performance 2.6s 3 findings
security 1.7s 2 findings
style 2.9s 3 findings
⏱ graph: 2.9s | sum of calls = 7.2s
4. Orchestrator-workers → Send (Lab 4)
ใน Lab 3 เรารู้ล่วงหน้าว่ามีผู้ตรวจสามคน จึงวาด edge ไว้สามเส้นได้ แต่ใน Lab 4 orchestrator (LLM) เขียนแผนตอนรัน เราไม่รู้ว่าจะได้งานย่อยกี่ชิ้น Send("worker", ...) ส่งงานหนึ่งชิ้นไปที่ node worker และส่งกี่ชิ้นก็ได้
START → orchestrator ─Send×N→ worker → synthesizer → END
# ---- จาก Lab 4: paper จำลอง + planner, worker, synthesizer เดิม ----
PAPERS = {
"P1": ("TutorBot: An LLM Tutor for Introductory Programming. We deployed an LLM-based tutor in a first-year "
"Python course with 412 students for one semester. Students who used the tutor at least weekly scored "
"11% higher on the final exam than a matched control group. The tutor gave hints instead of full solutions."),
"P2": ("Grading at Scale: Automatic Feedback on Code Assignments. We built a pipeline that runs unit tests and "
"asks an LLM to explain failures to students. On 3,800 submissions, teaching assistants agreed with the "
"LLM's feedback in 87% of cases, and grading time per assignment dropped from 9 to 2 minutes."),
"P3": ("The Hint Trap: Over-reliance on AI Assistants. In a controlled study with 96 students, those given "
"unlimited AI hints solved 30% more practice problems but scored 14% lower on a closed-book test two "
"weeks later than students with no AI access. Limiting hints to three per problem removed the gap."),
}
FACTS_ONLY = ("Copy every number exactly, with the same meaning as in the source. "
"Add no claim, cause, advice or adjective that is not in the source.")
WORKERS = {
"summarize": "You summarize one research abstract for students in 2-3 sentences. Keep the key numbers.",
"extract": "You extract facts. Return a short bullet list of only what the task asks for. No commentary.",
"compare": "You compare papers. In 3-4 sentences, say where they agree and where they conflict. Name papers by id.",
}
SUBTASK = {"type": "object", "additionalProperties": False,
"required": ["id", "worker", "paper_ids", "instruction"],
"properties": {"id": {"type": "string"},
"worker": {"type": "string", "enum": list(WORKERS)},
"paper_ids": {"type": "array", "minItems": 1, "items": {"type": "string", "enum": list(PAPERS)}},
"instruction": {"type": "string"}}}
PLAN_SCHEMA = {"type": "object", "additionalProperties": False, "required": ["subtasks"],
"properties": {"subtasks": {"type": "array", "items": SUBTASK, "minItems": 1}}}
def plan(goal):
papers = "\n".join(f"{pid}: {text}" for pid, text in PAPERS.items())
prompt = f"""You are the orchestrator of a teaching assistant. Break the GOAL into subtasks for workers.
GOAL: {goal}
AVAILABLE PAPERS:
{papers}
WORKER TYPES:
- summarize: overview of ONE paper
- extract: pull the specific facts a question needs from ONE paper
- compare: contrast 2+ papers
RULES:
- Return 1 to 6 subtasks. Use only the subtasks this goal really needs.
- Only use papers that are relevant to the goal.
- Each subtask uses one worker type and lists the paper ids the worker may read.
- summarize and extract read exactly ONE paper: make a separate subtask for each paper.
- Do NOT add a final merge/report subtask; a synthesizer merges the results afterwards.
- ids are T1, T2, ..."""
return ask_llm(prompt, temperature=0, schema=PLAN_SCHEMA)["subtasks"]
def run_worker(task):
papers = "\n\n".join(f"[{pid}] {PAPERS[pid]}" for pid in task["paper_ids"])
prompt = f"{WORKERS[task['worker']]} {FACTS_ONLY}\n\nTASK: {task['instruction']}\n\nPAPERS:\n{papers}"
return ask_llm(prompt, temperature=0.3)
def synthesize(goal, tasks, results):
parts = "\n\n".join(f"[{t['worker']} result, source papers: {', '.join(t['paper_ids'])}]\n{r}"
for t, r in zip(tasks, results))
prompt = (f"GOAL: {goal}\n\nWORKER RESULTS:\n{parts}\n\n"
"Merge these results into ONE coherent answer for students, in Thai, keeping technical terms "
"in English, at most 150 words. Use only facts from the results and cite papers as [P1], [P2], [P3]. "
+ FACTS_ONLY)
return ask_llm(prompt, temperature=0.3)class OrchState(TypedDict, total=False):
goal: str
tasks: list
done: Annotated[list, operator.add]
answer: str
# ✏️ TODO 4 (▶ วิดีโอ 9:55): แตกงาน: ส่ง Send ไปที่ node worker หนึ่งตัวต่องานย่อยหนึ่งชิ้นใน tasks
def assign(s):
return [Send(___, {"task": t}) for t in ___]
o = StateGraph(OrchState)
o.add_node("orchestrator", lambda s: {"tasks": plan(s["goal"])})
o.add_node("worker", lambda s: {"done": [(s["task"], run_worker(s["task"]))]})
o.add_node("synthesizer", lambda s: {"answer": synthesize(
s["goal"], [t for t, _ in s["done"]], [r for _, r in s["done"]])})
o.add_edge(START, "orchestrator")
o.add_conditional_edges("orchestrator", assign, ["worker"])
o.add_edge("worker", "synthesizer")
o.add_edge("synthesizer", END)
orchestrate = o.compile()
print(orchestrate.get_graph().draw_ascii())class OrchState(TypedDict, total=False):
goal: str
tasks: list
done: Annotated[list, operator.add]
answer: str
def assign(s):
return [Send("worker", {"task": t}) for t in s["tasks"]]
o = StateGraph(OrchState)
o.add_node("orchestrator", lambda s: {"tasks": plan(s["goal"])})
o.add_node("worker", lambda s: {"done": [(s["task"], run_worker(s["task"]))]})
o.add_node("synthesizer", lambda s: {"answer": synthesize(
s["goal"], [t for t, _ in s["done"]], [r for _, r in s["done"]])})
o.add_edge(START, "orchestrator")
o.add_conditional_edges("orchestrator", assign, ["worker"])
o.add_edge("worker", "synthesizer")
o.add_edge("synthesizer", END)
orchestrate = o.compile()
print(orchestrate.get_graph().draw_ascii()) +-----------+
| __start__ |
+-----------+
*
*
*
+--------------+
| orchestrator |
+--------------+
.
.
.
+--------+
| worker |
+--------+
*
*
*
+-------------+
| synthesizer |
+-------------+
*
*
*
+---------+
| __end__ |
+---------+
def run_goal(goal):
out = orchestrate.invoke({"goal": goal})
print(f"🧭 PLAN: {len(out['tasks'])} subtasks → 👷 {len(out['done'])} worker runs")
for t in out["tasks"]:
print(f" {t['id']} {t['worker']:<9} {','.join(t['paper_ids'])}")
print("\n📝", out["answer"])
run_goal("Summarize these 3 papers into one overview for students.")🧭 PLAN: 4 subtasks → 👷 4 worker runs
T1 summarize P1
T2 summarize P2
T3 summarize P3
T4 compare P1,P2,P3
📝 การใช้ LLM ในการเรียนการสอนมีผลลัพธ์ที่หลากหลาย: ในวิชา Python สำหรับนักศึกษา 412 คน พบว่าผู้ที่ใช้ tutor อย่างน้อยสัปดาห์ละครั้งทำคะแนน final exam ได้สูงกว่ากลุ่ม control group 11% โดย tutor ให้เป็น hints แทนการให้ full solutions [P1] ขณะที่การใช้ AI hints แบบไม่จำกัดช่วยให้แก้ practice problems ได้มากขึ้น 30% แต่คะแนน closed-book test ในอีก 2 สัปดาห์ต่อมาต่ำกว่ากลุ่มที่ไม่มี AI 14% อย่างไรก็ตาม การจำกัด hints ไว้ที่ 3 ครั้งต่อปัญหาช่วยลบช่องว่างดังกล่าวได้ [P3] นอกจากนี้ การสร้าง pipeline เพื่อให้ LLM อธิบาย failure จาก unit tests พบว่า teaching assistants เห็นด้วยกับ feedback 87% และช่วยลด grading time จาก 9 นาที เหลือ 2 นาทีต่อ assignment [P2]
run_goal("A student asks: should I use AI hints while doing practice problems? Answer with evidence.")🧭 PLAN: 3 subtasks → 👷 3 worker runs
T1 extract P1
T2 extract P3
T3 compare P1,P3
📝 การใช้ AI hints มีผลลัพธ์ที่แตกต่างกันตามรูปแบบการใช้งาน: นักเรียนที่ใช้ tutor อย่างน้อย weekly มีคะแนน final exam สูงกว่า matched control group 11% [P1] อย่างไรก็ตาม การใช้ unlimited AI hints ทำให้นักเรียนแก้ practice problems ได้มากกว่า 30% แต่กลับมีคะแนนใน closed-book test หลังจากผ่านไป two weeks ต่ำกว่านักเรียนที่ไม่มี AI access อยู่ 14% [P3] ทั้งนี้ การจำกัด hints เป็น three per problem สามารถ remove the gap ดังกล่าวได้ [P3]
5. Evaluator-optimizer → วงวน (cycle) (Lab 5)
ใน Lab 5 คือ for rnd in range(1, budget + 1) กับ if score >= threshold: return ที่นี่คือ edge ที่วนกลับ ไปที่ generate และ conditional edge ที่ตัดสินว่าจะวนต่อหรือหยุด
# ---- จาก Lab 5: abstract + evaluator เดิม ----
ABSTRACT5 = (
"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{ABSTRACT5}")
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]
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."""
EVAL_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"
"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=EVAL_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 reviewclass LoopState(TypedDict, total=False):
context: str
draft: str
review: dict
round: int
def generate(s):
return {"draft": ask_llm(s["context"], temperature=0.7), "round": s.get("round", 0) + 1}
def check(s):
r = evaluate(ABSTRACT5, s["draft"])
print(f"--- round {s['round']}: score {r['score']}/10 · bad terms: {r['bad_terms'] or 'none'}")
return {"review": r,
"context": s["context"] + (f"\n\nYour previous draft:\n{s['draft']}\n\n"
f"Editor's critique (score {r['score']}/10):\n{r['critique']}\n\n"
"Write an improved full translation. Reply with the translation only.")}
# ✏️ TODO 5 (▶ วิดีโอ 12:53): หยุดเมื่อคะแนนถึง threshold หรือใช้ครบ budget แล้ว
def good_enough(s, threshold=9, budget=3):
if ___ or ___:
return "done"
return "retry"class LoopState(TypedDict, total=False):
context: str
draft: str
review: dict
round: int
def generate(s):
return {"draft": ask_llm(s["context"], temperature=0.7), "round": s.get("round", 0) + 1}
def check(s):
r = evaluate(ABSTRACT5, s["draft"])
print(f"--- round {s['round']}: score {r['score']}/10 · bad terms: {r['bad_terms'] or 'none'}")
return {"review": r,
"context": s["context"] + (f"\n\nYour previous draft:\n{s['draft']}\n\n"
f"Editor's critique (score {r['score']}/10):\n{r['critique']}\n\n"
"Write an improved full translation. Reply with the translation only.")}
def good_enough(s, threshold=9, budget=3):
if s["review"]["score"] >= threshold or s["round"] >= budget:
return "done"
return "retry"e = StateGraph(LoopState)
e.add_node("generate", generate)
e.add_node("evaluate", check)
e.add_edge(START, "generate")
e.add_edge("generate", "evaluate")
e.add_conditional_edges("evaluate", good_enough, {"retry": "generate", "done": END})
loop = e.compile()
for edge in loop.get_graph().edges:
print(f"{edge.source:>9} → {edge.target:<9} {'(conditional)' if edge.conditional else ''}")__start__ → generate
evaluate → __end__ (conditional)
evaluate → generate (conditional)
generate → evaluate
out = loop.invoke({"context": TASK})
print(f"\n✅ stopped after round {out['round']} with {out['review']['score']}/10")
print(out["draft"])--- round 1: score 6/10 · bad terms: ['hallucination', 'small language model', 'retrieval-augmented generation', 'fine-tuning', 'benchmark', 'latency']
--- round 2: score 10/10 · bad terms: none
✅ stopped after round 2 with 10/10
บทคัดย่อ:
เราทำการศึกษา hallucination ใน small language model ที่ใช้สำหรับตอบคำถามนิสิตนักศึกษาเกี่ยวกับเนื้อหาในบทเรียน โดยเราได้ใช้วิธีการรวม retrieval-augmented generation เข้ากับการทำ lightweight fine-tuning จากชุดข้อมูลคำถามและคำตอบจำนวน 4,200 คู่ จากรายวิชาในมหาวิทยาลัย 3 วิชา จากการทดสอบกับ benchmark ใหม่ซึ่งประกอบด้วยคำถาม 600 ข้อ พบว่าวิธีการของเราสามารถลด hallucination ลงได้ถึง 31% ในขณะที่ยังคงรักษา latency ในการตอบคำถามให้ต่ำกว่าสองวินาที ทั้งนี้เราได้เปิดเผย benchmark และซอร์สโค้ดเพื่อให้ผู้อื่นสามารถนำไปต่อยอดในการศึกษาต่อไปได้
สรุป
| Pattern | เขียนเอง (Lab 1–5) | LangGraph (Lab 6) |
|---|---|---|
| Prompt chaining + gate | if not gate(...): return None |
conditional edge → END |
| Routing | ROUTES[label](item) |
conditional edge จากชื่อ route ไป node ชื่อเดียวกัน |
| Parallelization | ThreadPoolExecutor + pool.map |
หลาย edge จาก START + reducer operator.add |
| Orchestrator-workers | ex.map(run_worker, tasks) |
Send("worker", ...) หนึ่งตัวต่องานย่อย |
| Evaluator-optimizer | for + if score >= threshold |
edge วนกลับ + conditional edge good_enough |
| — | print เองทุกขั้น |
draw_ascii() + stream() เห็นทุกขั้น |
เขียนเองเมื่อไร / ใช้ framework เมื่อไร — เขียนเองเพื่อเข้าใจกลไก และเมื่อ workflow ยังสั้น ใช้ framework เมื่อ workflow มีหลายทางแยก มีงานพร้อมกัน หรือต้องให้ทีมอ่านโครงสร้างร่วมกันได้
ลองทำต่อ: ใส่ gate ที่สอง (ไม่เกิน 5 บรรทัด) ต่อจาก write_thai ใน chain ของส่วนที่ 1 หรือตั้ง budget=1 ใน good_enough แล้วดูว่า loop หยุดที่รอบไหน