Lab 4 — Orchestrator-Workers: ให้ LLM เป็นคนแบ่งงาน (§19.1.4)
Lab walkthrough · EP04 Workflow Patterns
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP04 Workflow Patterns
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
ผู้ช่วยอาจารย์ของ Cogito Learn ได้รับ paper 3 ฉบับ และโจทย์ที่ต่างกันไปในแต่ละวัน
goal ──▶ 🧭 orchestrator (LLM เขียนแผนงานย่อย)
├──▶ 👷 worker T1 ─┐
├──▶ 👷 worker T2 ─┼──▶ 📝 synthesizer ──▶ คำตอบเดียว
└──▶ 👷 worker … ─┘
ต่างจาก parallelization (Lab 3): การแบ่งงานมาจาก model ไม่ได้เขียนตายตัวในโค้ด
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §19.1.4 (p.370) — CC BY-SA 4.0 abstract ทั้ง 3 ฉบับเป็นข้อมูลจำลองเพื่อการสอน ส่วนผลลัพธ์ของ model ทุกอันมาจากการรันจริง
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 text1. Input และ worker
paper จำลอง 3 ฉบับ (P1–P3) และ worker 3 แบบที่ใช้ prompt ต่างกัน
PAPERS = { # ข้อมูลจำลองเพื่อการสอน (fictional abstracts)
"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.",
}2. Orchestrator: LLM เขียนแผนงานย่อย
ผลลัพธ์เป็น JSON (structured output): {"subtasks": [{"id", "worker", "paper_ids", "instruction"}, …]}
SUBTASK = {"type": "object", "additionalProperties": False,
"required": ["id", "worker", "paper_ids", "instruction"],
"properties": {"id": {"type": "string"},
# ✏️ TODO 1 (▶ วิดีโอ 3:01): จำกัดให้ worker เป็นได้แค่ชื่อ worker ที่มีจริง และ paper_ids เป็นได้แค่ id ของ paper ที่มีจริง
"worker": {"type": "string", "enum": ___},
"paper_ids": {"type": "array", "minItems": 1, "items": {"type": "string", "enum": ___}},
"instruction": {"type": "string"}}}
PLAN_SCHEMA = {"type": "object", "additionalProperties": False, "required": ["subtasks"],
"properties": {"subtasks": {"type": "array", "items": SUBTASK, "minItems": 1}}}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, ..."""
# ✏️ TODO 2 (▶ วิดีโอ 4:14): เรียก LLM หนึ่งครั้ง ที่ temperature 0 พร้อม PLAN_SCHEMA แล้วคืน list ของงานย่อย
return ___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 show_plan(tasks):
for t in tasks:
print(f" {t['id']} {t['worker']:<9} {','.join(t['paper_ids']):<8} {t['instruction'][:70]}")GOAL1 = "Summarize these 3 papers into one overview for students."
tasks1 = plan(GOAL1)
print(f"🧭 PLAN: {len(tasks1)} subtasks")
show_plan(tasks1)🧭 PLAN: 4 subtasks
T1 summarize P1 Summarize the key findings and methodology of the TutorBot study.
T2 summarize P2 Summarize the key findings and methodology of the automatic code feedb
T3 summarize P3 Summarize the key findings and methodology of the 'Hint Trap' study re
T4 compare P1,P2,P3 Compare and contrast the effectiveness, implementation methods, and po
3. Workers: ทำงานย่อยทุกชิ้น
worker แต่ละตัวเห็น เฉพาะ paper ที่ orchestrator ระบุ · งานย่อยไม่ขึ้นต่อกัน → รันพร้อมกันได้เหมือน Lab 3
# ✏️ TODO 3 (▶ วิดีโอ 5:16): ให้ worker อ่านเฉพาะ paper ใน task แล้วสร้าง prompt จาก prompt ของ worker แบบนั้น + instruction ที่ orchestrator เขียน
def run_worker(task):
papers = "\n\n".join(f"[{pid}] {PAPERS[pid]}" for pid in ___)
prompt = f"{___} {FACTS_ONLY}\n\nTASK: {___}\n\nPAPERS:\n{papers}"
return ask_llm(prompt, temperature=0.3)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)# ✏️ TODO 4 (▶ วิดีโอ 5:37): ส่งงานย่อยทุกชิ้นใน tasks1 ให้ run_worker ทำพร้อมกัน แล้วเก็บผลเป็น list
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as ex:
results1 = ___
for t, r in zip(tasks1, results1):
print(f"👷 {t['id']} {t['worker']} {t['paper_ids']}\n{r.strip()[:300]}\n")from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as ex:
results1 = list(ex.map(run_worker, tasks1))
for t, r in zip(tasks1, results1):
print(f"👷 {t['id']} {t['worker']} {t['paper_ids']}\n{r.strip()[:300]}\n")👷 T1 summarize ['P1']
An LLM-based tutor was deployed in a first-year Python course with 412 students for one semester. The tutor gave hints instead of full solutions, and students who used the tutor at least weekly scored 11% higher on the final exam than a matched control group.
👷 T2 summarize ['P2']
A pipeline was built 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.
👷 T3 summarize ['P3']
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.
👷 T4 compare ['P1', 'P2', 'P3']
[P1] and [P2] implement LLMs to provide hints or explanations for code, while [P3] studies the effects of unlimited AI hints. [P1] reports students who used the tutor at least weekly scored 11% higher on the final exam, whereas [P3] found students given unlimited AI hints scored 14% lower on a close
4. Synthesizer: รวมผลเป็นคำตอบเดียว
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)print(synthesize(GOAL1, tasks1, results1))การใช้ LLM ในการเรียนการสอน Programming มีผลลัพธ์ที่หลากหลาย: การใช้ LLM-based tutor ให้คำใบ้แทนการเฉลยในวิชา Python พบว่านักเรียนที่ใช้งานอย่างน้อย weekly มีคะแนน final exam สูงกว่ากลุ่มควบคุม 11% [P1] ขณะที่การใช้ pipeline เพื่อให้ LLM อธิบายผลของ unit tests พบว่า Teaching Assistants เห็นด้วยกับ feedback ถึง 87% จาก 3,800 submissions และช่วยลด grading time จาก 9 เหลือ 2 minutes [P2] อย่างไรก็ตาม การให้ unlimited AI hints ส่งผลให้นักเรียนแก้ practice problems ได้มากขึ้น 30% แต่คะแนน closed-book test ในอีกสองสัปดาห์ต่อมาต่ำกว่ากลุ่มที่ไม่มี AI access ถึง 14% [P3] ทั้งนี้ การจำกัด hints เป็น 3 ครั้งต่อ problem สามารถลบช่องว่างของคะแนนดังกล่าวได้ [P3]
5. Goal ใหม่ → แผนใหม่ (โค้ดเดิม)
รวมทั้งสามขั้นเป็นฟังก์ชันเดียว แล้วลองกับคำถามของนักศึกษา
# ✏️ TODO 5 (▶ วิดีโอ 7:40): ขั้นที่ 1: ให้ orchestrator เขียนแผนงานย่อยจาก goal
def orchestrate(goal):
tasks = ___
print(f"🧭 PLAN: {len(tasks)} subtasks"); show_plan(tasks)
# ✏️ TODO 6 (▶ วิดีโอ 7:47): ขั้นที่ 2–3: ให้ worker ทำทุกงานพร้อมกัน แล้วให้ synthesizer รวมผล
with ThreadPoolExecutor() as ex:
results = ___
return tasks, ___def orchestrate(goal):
tasks = plan(goal)
print(f"🧭 PLAN: {len(tasks)} subtasks"); show_plan(tasks)
with ThreadPoolExecutor() as ex:
results = list(ex.map(run_worker, tasks))
return tasks, synthesize(goal, tasks, results)GOAL2 = "A student asks: should I use AI hints while doing practice problems? Answer with evidence."
tasks2, answer2 = orchestrate(GOAL2)
print("\n📝", answer2)🧭 PLAN: 3 subtasks
T1 extract P1 Extract evidence regarding the impact of using an LLM tutor that provi
T2 extract P3 Extract evidence regarding the impact of unlimited AI hints versus lim
T3 compare P1,P3 Compare the findings of P1 and P3 to determine the nuance between usin
📝 การใช้ 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 สามารถช่วยลบช่องว่าง (removed the gap) ของคะแนนดังกล่าวได้ [P3]
from collections import Counter
for name, ts in [("GOAL1", tasks1), ("GOAL2", tasks2)]:
kinds = Counter(t["worker"] for t in ts)
used = sorted({pid for t in ts for pid in t["paper_ids"]})
print(f"{name}: {len(ts)} subtasks {dict(kinds)} papers={used}")GOAL1: 4 subtasks {'summarize': 3, 'compare': 1} papers=['P1', 'P2', 'P3']
GOAL2: 3 subtasks {'extract': 2, 'compare': 1} papers=['P1', 'P3']
สรุป
| ส่วน | ในโค้ด |
|---|---|
| Orchestrator | plan() — LLM เรียกครั้งเดียว เขียนแผนเป็น JSON ตาม PLAN_SCHEMA |
| Workers | run_worker() — prompt ต่างกันตาม WORKERS อ่านเฉพาะ paper ที่ได้รับ · รันพร้อมกัน |
| Synthesizer | synthesize() — รวมผลเป็นคำตอบเดียว อ้าง [P1]–[P3] |
| ยังเป็น workflow | ลำดับ plan → workers → synthesize ตายตัวในโค้ด ไม่วน ไม่แก้แผน |
ลองทำต่อ: เพิ่ม worker แบบที่ 4 "quiz" (เขียนคำถามทบทวน 1 ข้อจาก paper) ใน WORKERS แล้วลอง orchestrate("Make 3 review questions for students from these papers.") — orchestrator เลือกใช้ worker ใหม่เองไหม