Lab 2 — skill หลายตัว กับ router หนึ่งตัว
Lab walkthrough · EP14 Agent Skills: Packaging Know-How for Agents
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP14 Agent Skills: Packaging Know-How for Agents
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
Lab 1 จบที่ skill หนึ่งตัวเพิ่ม token ขาเข้า ทุกครั้ง ที่เรียก model — ถ้ามีหลายตัวล่ะ Lab นี้มีคลัง skill หกตัว แล้วเทียบสองแบบจากคลิปทฤษฎี
สิ่งที่จะได้ทำ
- คลัง skill หกตัว และการ ค้นพบ (discovery): อ่านแค่ส่วนหัวของทุก skill
- static loading: ใส่ทุก skill ตลอดเวลา แล้วนับ token
- skill router: ให้ model เลือก skill จากชื่อและคำอธิบาย (dynamic discovery)
- วงจรชีวิตครบ: เลือก → เปิดใช้ → ทำงาน → ปิดใช้
- คำอธิบายที่คลุมเครือ ทำให้ router พลาด — แล้วแก้
- สิทธิ์: ผู้ใช้คนละบทบาท เห็น skill ไม่เท่ากัน
ข้อมูล paper เป็นข้อมูลจำลองเพื่อการสอน (เลข arXiv ชื่อ ผู้เขียน และปีเป็นของจริง) ส่วน output ของ model มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §22.2.1–22.2.2, §22.3.4, §22.4, §22.5 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | ตั้งค่าแบบเดียวกับ Lab 1 (lab นี้ใช้ไม่ถึง 0.1 เซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv, pyyaml (ติดตั้งใน cell ถัดไป) |
วิธีใส่ key และเหตุผลที่เลือก model อยู่ใน Lab 1 — Colab: 🔑 Secrets → OPENROUTER_API_KEY · เครื่องตัวเอง: ไฟล์ .env
%pip install -q "openai>=1.50" python-dotenv pyyamlimport json, os, re
from pathlib import Path
import yaml
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"]
MODEL = "google/gemma-4-26b-a4b-it" # why this model and provider: Lab 1
EXTRA = {"reasoning": {"enabled": False},
"provider": {"order": ["makora"], "allow_fallbacks": False}}
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5)
COST = {"chat": 0.0}PAPERS = { # teaching data: real arXiv ids, titles, authors and years; one-line summaries written for this lab
"2310.08560": {"title": "MemGPT: Towards LLMs as Operating Systems", "authors": "Packer et al.", "year": 2023,
"summary": "the LLM pages facts between a small main context and a large external store, like an operating system's virtual memory"},
"2304.03442": {"title": "Generative Agents: Interactive Simulacra of Human Behavior", "authors": "Park et al.", "year": 2023,
"summary": "agents keep a memory stream of observations, score memories by recency, importance and relevance, and write reflections"},
"2303.11366": {"title": "Reflexion: Language Agents with Verbal Reinforcement Learning", "authors": "Shinn et al.", "year": 2023,
"summary": "after a failed try the agent writes a short lesson to its memory and uses it on the next try"},
"2504.19413": {"title": "Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory", "authors": "Chhikara et al.", "year": 2025,
"summary": "an LLM extracts facts from each conversation and decides to add, update or delete them in a long-term store"},
"2502.12110": {"title": "A-MEM: Agentic Memory for LLM Agents", "authors": "Xu et al.", "year": 2025,
"summary": "each memory is a linked note with keywords and tags, and new notes update links to old ones"},
"2305.16291": {"title": "Voyager: An Open-Ended Embodied Agent with Large Language Models", "authors": "Wang et al.", "year": 2023,
"summary": "a Minecraft agent that stores verified code as a growing skill library and reuses it"},
"2210.03629": {"title": "ReAct: Synergizing Reasoning and Acting in Language Models", "authors": "Yao et al.", "year": 2023,
"summary": "the model alternates reasoning steps and tool actions in one loop"},
"2302.04761": {"title": "Toolformer: Language Models Can Teach Themselves to Use Tools", "authors": "Schick et al.", "year": 2023,
"summary": "a model learns by itself where to insert API calls in text"},
}
def search_papers(query: str, max_results: int = 5) -> str:
words = [w for w in re.findall(r"[a-z]+", query.lower()) if len(w) > 2]
hits = sorted(((sum(w in (p["title"] + " " + p["summary"]).lower() for w in words), pid)
for pid, p in PAPERS.items()), reverse=True)
return json.dumps([{"id": pid, "title": PAPERS[pid]["title"]} for score, pid in hits[:max_results] if score])
def get_paper(paper_id: str) -> str:
if paper_id not in PAPERS:
return json.dumps({"error": f"unknown id {paper_id}; call search_papers first"})
return json.dumps({"id": paper_id, **PAPERS[paper_id]})
FUNCS = {"search_papers": search_papers, "get_paper": get_paper}
SPECS = {
"search_papers": {"type": "function", "function": {"name": "search_papers",
"description": "Search the paper library by keywords in the title or summary. Returns ids and titles.",
"parameters": {"type": "object", "properties": {"query": {"type": "string"},
"max_results": {"type": "integer"}}, "required": ["query"]}}},
"get_paper": {"type": "function", "function": {"name": "get_paper",
"description": "Get one paper's full record (title, authors, year, summary) by its arXiv id.",
"parameters": {"type": "object", "properties": {"paper_id": {"type": "string"}}, "required": ["paper_id"]}}},
}
def run_agent(system, task, tools, max_steps=8):
"""The simple loop from Lab 1; info["input_tokens"] now adds up the input tokens of every call."""
msgs = [{"role": "system", "content": system}, {"role": "user", "content": task}]
info = {"input_tokens": 0, "calls": 0}
for _ in range(max_steps):
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, messages=msgs,
tools=[SPECS[t] for t in tools] or None)
COST["chat"] += r.usage.cost
info["input_tokens"] += r.usage.prompt_tokens
info["calls"] += 1
msg = r.choices[0].message
if not msg.tool_calls:
return msg.content, info
msgs.append(msg.model_dump(exclude_none=True))
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
print(f" 🔧 {call.function.name}({args})")
msgs.append({"role": "tool", "tool_call_id": call.id, "content": FUNCS[call.function.name](**args)})
return None, info
BASE = "You are a research assistant for university students."1. คลัง skill และการค้นพบ (discovery)
| skill | ทำอะไร | tool |
|---|---|---|
paper-summary |
สรุป paper อ้างอิงทุกประโยค (จาก Lab 1) | search, get |
paper-quiz |
ออกข้อสอบหนึ่งข้อต่อ paper | search, get |
formatter |
⚠️ เขียนคำอธิบายไว้ไม่ดี — กลับมาดูในส่วนที่ 5 | search, get |
code-review |
ตรวจโค้ด Python | — |
meeting-notes |
สรุปการประชุมเป็นงานที่ต้องทำ | — |
grade-submission |
ให้คะแนนตาม rubric — อาจารย์เท่านั้น | — |
Discovery (§22.4 ขั้นที่ 1): อ่าน แค่ส่วนหัว ของทุก SKILL.md — ยังไม่โหลดเนื้อหา
LIBRARY = {
"paper-summary": """---
name: paper-summary
description: Summarize research papers from the library for students, with a citation on every sentence.
version: 1.0.0
tools: [search_papers, get_paper]
knowledge: [example.md]
---
# Paper summary
Write for first-year students: plain words, no jargon without a short explanation.
## Workflow
1. Call search_papers with the topic.
2. Call get_paper for each paper you will use. Use only what get_paper returns.
3. Compare the papers: what does each one add?
4. Write the answer.
## Guardrails
- Answer with JSON only, no other text: {"papers": ["<id>", ...], "sentences": [{"text": "...", "cite": "<id>"}, ...]}
- Every sentence cites exactly one paper id that you fetched with get_paper.
- At most 120 words in all sentences together.
- Add no claim, number or adjective that the paper record does not contain.
""",
"paper-quiz": """---
name: paper-quiz
description: Write multiple-choice quiz questions about papers in the library, one question per paper.
version: 1.0.0
tools: [search_papers, get_paper]
---
# Paper quiz
Write quiz questions that check a student understood the main idea of a paper.
## Workflow
1. Find the paper (search_papers) and read its record (get_paper).
2. Write one question about the paper's main idea, from its summary only.
3. Write four choices: one correct, three plausible but wrong.
## Guardrails
- JSON only: {"questions": [{"paper": "<id>", "q": "...", "choices": ["...", "...", "...", "..."], "answer": 1}]}
- The correct answer must follow from the summary; no trick questions.
""",
"formatter": """---
name: formatter
description: Formats text.
version: 1.0.0
tools: [search_papers, get_paper]
---
# Citation format (APA)
## Workflow
1. Find the paper's arXiv id (search_papers) if you only have its title.
2. Call get_paper with the arXiv id.
3. Write: Authors (Year). Title. arXiv:<id>.
## Guardrails
- Use only the authors, year and title from get_paper; never guess missing parts.
- One line per paper, nothing else.
""",
"code-review": """---
name: code-review
description: Review Python code for bugs, unclear names and missing error handling.
version: 1.0.0
tools: []
---
# Code review
## Workflow
1. Read the code line by line.
2. List bugs first, then readability, then style.
## Guardrails
- Quote the line you comment on.
- Suggest a fix for every bug.
- Never rewrite the whole program.
""",
"meeting-notes": """---
name: meeting-notes
description: Turn a meeting transcript into decisions and action items with owners and dates.
version: 1.0.0
tools: []
---
# Meeting notes
## Workflow
1. Read the transcript.
2. List decisions, then action items (owner, task, due date).
## Guardrails
- Only items said in the transcript; mark a missing owner or date as "?".
""",
"grade-submission": """---
name: grade-submission
description: Grade a student's answer against the course rubric and explain the score.
version: 1.0.0
tools: []
allowed_roles: [teacher]
---
# Grade submission
## Workflow
1. Read the rubric and the answer.
2. Score each rubric line, then add them up.
## Guardrails
- Explain every point taken off.
- Never reveal other students' answers.
""",
}
EXAMPLE = """# Example of a good answer (topic: tool use)
{"papers": ["2210.03629", "2302.04761"],
"sentences": [
{"text": "ReAct lets a model think and then act with a tool, again and again in one loop.", "cite": "2210.03629"},
{"text": "Toolformer goes further: the model learns by itself where an API call helps.", "cite": "2302.04761"}]}
"""
for name, text in LIBRARY.items():
Path(f"skills/{name}").mkdir(parents=True, exist_ok=True)
Path(f"skills/{name}/SKILL.md").write_text(text)
Path("skills/paper-summary/example.md").write_text(EXAMPLE)
print(sorted(p.parent.name for p in Path("skills").glob("*/SKILL.md")))['code-review', 'formatter', 'grade-submission', 'meeting-notes', 'paper-quiz', 'paper-summary']
def read_header(path):
_, header, body = Path(path).read_text().split("---", 2)
return yaml.safe_load(header), body.strip()
# ✏️ TODO 1 (▶ วิดีโอ 1:58): หาไฟล์ SKILL.md ของทุก skill ในโฟลเดอร์
def discover(root="skills"):
registry = {}
for path in ___:
meta, _ = read_header(path)
registry[meta["name"]] = {**meta, "path": path}
return registry
REGISTRY = discover()
for name, s in REGISTRY.items():
print(f"{name:17} {s['description']}")def read_header(path):
_, header, body = Path(path).read_text().split("---", 2)
return yaml.safe_load(header), body.strip()
def discover(root="skills"):
registry = {}
for path in sorted(Path(root).glob("*/SKILL.md")):
meta, _ = read_header(path)
registry[meta["name"]] = {**meta, "path": path}
return registry
REGISTRY = discover()
for name, s in REGISTRY.items():
print(f"{name:17} {s['description']}")code-review Review Python code for bugs, unclear names and missing error handling.
formatter Formats text.
grade-submission Grade a student's answer against the course rubric and explain the score.
meeting-notes Turn a meeting transcript into decisions and action items with owners and dates.
paper-quiz Write multiple-choice quiz questions about papers in the library, one question per paper.
paper-summary Summarize research papers from the library for students, with a citation on every sentence.
2. Static loading: ใส่ทุก skill ตลอดเวลา (§22.2.1)
activate รับ skill หลายตัว: ต่อเนื้อหาทุกตัวเข้า system prompt และรวม tool ของทุกตัว
def load_skill(name):
meta, body = read_header(REGISTRY[name]["path"])
knowledge = "\n\n".join((REGISTRY[name]["path"].parent / f).read_text() for f in meta.get("knowledge", []))
return {**meta, "instructions": body, "knowledge_text": knowledge}
# ✏️ TODO 2 (▶ วิดีโอ 2:39): รวม tool ของทุก skill โดยไม่ซ้ำกัน
def activate(skills, base=BASE):
parts = [base] + [f"# Skill: {s['name']}\n{s['instructions']}\n{s['knowledge_text']}" for s in skills]
tools = ___
return "\n\n".join(parts), toolsdef load_skill(name):
meta, body = read_header(REGISTRY[name]["path"])
knowledge = "\n\n".join((REGISTRY[name]["path"].parent / f).read_text() for f in meta.get("knowledge", []))
return {**meta, "instructions": body, "knowledge_text": knowledge}
def activate(skills, base=BASE):
parts = [base] + [f"# Skill: {s['name']}\n{s['instructions']}\n{s['knowledge_text']}" for s in skills]
tools = sorted({t for s in skills for t in s["tools"]})
return "\n\n".join(parts), toolsTASK = "Summarize 3 papers on agent memory for first-year students."
system, tools = activate([load_skill(n) for n in REGISTRY])
answer, static = run_agent(system, TASK, tools)
print(f"\nstatic: {static['calls']} calls · {static['input_tokens']} input tokens · "
f"{static['input_tokens'] // static['calls']} per call") 🔧 search_papers({'query': 'agent memory'})
🔧 get_paper({'paper_id': '2504.19413'})
🔧 get_paper({'paper_id': '2304.03422'})
🔧 get_paper({'paper_id': '2310.08560'})
🔧 get_paper({'paper_id': '2304.03442'})
static: 4 calls · 4841 input tokens · 1210 per call
3. Skill router: ให้ model เลือก skill (§22.2.2)
router เห็นแค่ ชื่อ + คำอธิบาย และตอบด้วย JSON schema ที่ enum เป็นชื่อ skill (หรือ "none") — ตอบชื่อที่ไม่มีอยู่จริงไม่ได้
# ✏️ TODO 3 (▶ วิดีโอ 3:32): จำกัดคำตอบให้เป็นชื่อ skill ที่มีอยู่จริง หรือ "none"
def route(request, names, k=2):
menu = "\n".join(f"- {n}: {REGISTRY[n]['description']}" for n in names)
schema = {"type": "object", "additionalProperties": False, "required": ["skills"],
"properties": {"skills": {"type": "array", "minItems": 1, "maxItems": k,
"items": {"type": "string", "enum": ___}}}}
r = client.chat.completions.create(
model=MODEL, temperature=0, extra_body=EXTRA,
response_format={"type": "json_schema", "json_schema": {"name": "route", "strict": True, "schema": schema}},
messages=[{"role": "system", "content": f"Pick the skills needed for the user's request, at most {k}. "
f"Pick 'none' if no skill fits.\n\nSkills:\n{menu}"},
{"role": "user", "content": request}])
COST["chat"] += r.usage.cost
return json.loads(r.choices[0].message.content)["skills"], r.usage.prompt_tokensdef route(request, names, k=2):
menu = "\n".join(f"- {n}: {REGISTRY[n]['description']}" for n in names)
schema = {"type": "object", "additionalProperties": False, "required": ["skills"],
"properties": {"skills": {"type": "array", "minItems": 1, "maxItems": k,
"items": {"type": "string", "enum": names + ["none"]}}}}
r = client.chat.completions.create(
model=MODEL, temperature=0, extra_body=EXTRA,
response_format={"type": "json_schema", "json_schema": {"name": "route", "strict": True, "schema": schema}},
messages=[{"role": "system", "content": f"Pick the skills needed for the user's request, at most {k}. "
f"Pick 'none' if no skill fits.\n\nSkills:\n{menu}"},
{"role": "user", "content": request}])
COST["chat"] += r.usage.cost
return json.loads(r.choices[0].message.content)["skills"], r.usage.prompt_tokensfor request in ["Summarize 3 papers on agent memory for first-year students.",
"Write a quiz question about the MemGPT paper.",
"Is there a bug in: def avg(xs): return sum(xs) / len(xs)",
"What's the capital of France?"]:
chosen, tokens = route(request, list(REGISTRY))
print(f"{str(chosen):22} {tokens:>4} tokens ← {request}")['paper-summary'] 175 tokens ← Summarize 3 papers on agent memory for first-year students.
['paper-quiz'] 171 tokens ← Write a quiz question about the MemGPT paper.
['code-review'] 182 tokens ← Is there a bug in: def avg(xs): return sum(xs) / len(xs)
['none'] 169 tokens ← What's the capital of France?
4. วงจรชีวิตครบ (§22.4)
handle = discovery (registry) → selection (router) → activation → execution → deactivation (คำขอถัดไปเริ่มจาก BASE ใหม่ — context ของ skill ไม่ติดไป)
def handle(request, names=None):
names = names or list(REGISTRY)
chosen, router_tokens = route(request, names)
print(f"🧭 selection: {chosen} ({router_tokens} tokens)")
if chosen == ["none"]:
return run_agent(BASE, request, [])
# ✏️ TODO 4 (▶ วิดีโอ 4:52): โหลดเนื้อหาเต็ม เฉพาะ skill ที่ router เลือก
skills = ___
system, tools = activate(skills)
print(f"🔌 activation: {[s['name'] for s in skills]} · tools {tools}")
answer, info = run_agent(system, request, tools)
info["input_tokens"] += router_tokens
print(f"🧹 deactivation: {chosen} removed — the next request starts from BASE")
return answer, infodef handle(request, names=None):
names = names or list(REGISTRY)
chosen, router_tokens = route(request, names)
print(f"🧭 selection: {chosen} ({router_tokens} tokens)")
if chosen == ["none"]:
return run_agent(BASE, request, [])
skills = [load_skill(n) for n in chosen]
system, tools = activate(skills)
print(f"🔌 activation: {[s['name'] for s in skills]} · tools {tools}")
answer, info = run_agent(system, request, tools)
info["input_tokens"] += router_tokens
print(f"🧹 deactivation: {chosen} removed — the next request starts from BASE")
return answer, infoanswer, dynamic = handle(TASK)
print(f"\n{'':10}{'calls':>6}{'input tokens':>14}")
print(f"{'static':10}{static['calls']:>6}{static['input_tokens']:>14}")
print(f"{'dynamic':10}{dynamic['calls'] + 1:>6}{dynamic['input_tokens']:>14} (router call included)")🧭 selection: ['paper-summary'] (175 tokens)
🔌 activation: ['paper-summary'] · tools ['get_paper', 'search_papers']
🔧 search_papers({'query': 'agent memory architecture long-term short-term'})
🔧 get_paper({'paper_id': '2504.19413'})
🔧 get_paper({'paper_id': '2310.08560'})
🔧 get_paper({'paper_id': '2304.03442'})
🧹 deactivation: ['paper-summary'] removed — the next request starts from BASE
calls input tokens
static 4 4841
dynamic 4 2322 (router call included)
5. เมื่อ router พลาด: คำอธิบายที่คลุมเครือ
ตำรา: “Routing errors can miss relevant skills” และ “invest in tool quality” (§22.2.2, §22.3.4)
CITE = "How do I cite the MemGPT paper in my report?"
print(route(CITE, list(REGISTRY)))(['none'], 173)
path = REGISTRY["formatter"]["path"]
path.write_text(path.read_text().replace(
"description: Formats text.",
"description: Format a reference (citation) for a paper in the library in APA style, from its arXiv id or title."))
REGISTRY = discover()
answer, _ = handle(CITE)
print("\n" + answer)🧭 selection: ['formatter'] (192 tokens)
🔌 activation: ['formatter'] · tools ['get_paper', 'search_papers']
🔧 search_papers({'query': 'MemGPT'})
🔧 get_paper({'paper_id': '2310.08560'})
🧹 deactivation: ['formatter'] removed — the next request starts from BASE
Packer et al. (2023). MemGPT: Towards LLMs as Operating Systems. arXiv:2310.08560.
6. สิทธิ์: ไม่ใช่ทุกคนควรได้ทุก skill (§22.5)
allowed_roles ในส่วนหัว → กรองก่อนส่งให้ router: router ของนักศึกษา ไม่เห็น grade-submission เลย
# ✏️ TODO 5 (▶ วิดีโอ 6:56): เก็บ skill ที่บทบาทนี้อยู่ใน allowed_roles (ไม่มีบรรทัดนี้ = ทุกคน)
def visible(role):
return [n for n, s in REGISTRY.items() if ___]
GRADE = "Grade this answer with the rubric: 'MemGPT stores facts in a database.'"
for role in ["student", "teacher"]:
print(f"{role:8} sees {len(visible(role))} skills → router: {route(GRADE, visible(role))[0]}")def visible(role):
return [n for n, s in REGISTRY.items() if role in s.get("allowed_roles", [role])]
GRADE = "Grade this answer with the rubric: 'MemGPT stores facts in a database.'"
for role in ["student", "teacher"]:
print(f"{role:8} sees {len(visible(role))} skills → router: {route(GRADE, visible(role))[0]}")student sees 5 skills → router: ['none']
teacher sees 6 skills → router: ['grade-submission']
print(f"cost: ${COST['chat']:.5f}")cost: $0.00103
สรุป
| static (ทุก skill) | dynamic (router) | |
|---|---|---|
| context | เนื้อหาทั้งหกตัว ทุกครั้งที่เรียก model | ชื่อ + คำอธิบาย ตอนเลือก + เนื้อหาเฉพาะตัวที่เลือก |
| การเรียก model | งานอย่างเดียว | + router หนึ่งครั้ง |
| ความเสี่ยง | เปลือง context ขยายถึงหลักร้อยไม่ได้ | เลือกพลาด ถ้าคำอธิบายไม่ดี |
- คำอธิบาย skill คือ สิ่งเดียว ที่ router เห็น —
Formats text.พลาด, คำอธิบายที่ชัดเจนเลือกถูก - สิทธิ์กรอง ก่อน router: นักศึกษาไม่เห็น
grade-submissionเลย
แบบฝึกหัด
- เพิ่ม skill ที่เจ็ด
paper-compareที่เทียบ paper สองเรื่อง — ไม่ต้องแก้โค้ดเลย แค่เขียนโฟลเดอร์ แล้วdiscover()ใหม่ - ลองคำขอที่ต้องใช้สอง skill เช่น “Summarize the MemGPT paper and give its APA reference” — router เลือกกี่ตัว
- เปลี่ยน router เป็นการเทียบคำแบบง่ายๆ (นับคำที่ตรงกับคำอธิบาย) แล้วดูว่าพลาดตรงไหน
ถัดไป — Lab 3: skill ที่เรียก skill อื่นต่อกันเป็นกราฟ และคลัง skill ที่เรียนรู้เองแบบ Voyager