Lab 1 — เขียน skill ตัวแรก
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 ที่คุณรันเองจึงอาจต่างจากหน้านี้
คลิปทฤษฎีบอกว่า tool ให้ agent ทำได้ ส่วน skill ให้ agent รู้ว่าควรทำอย่างไร Lab นี้เราจะเขียน skill paper-summary เป็นโฟลเดอร์ แล้วเทียบงานเดิม แบบไม่มี skill กับมี skill
สิ่งที่จะได้ทำ
- agent ลูปง่ายๆ กับ tool ค้น paper (ลูปจาก §22.3.4)
- สั่งงาน โดยไม่มี skill แล้วดูผล
- เขียน skill เป็นโฟลเดอร์:
SKILL.md(คำสั่ง · ขั้นตอน · กฎ) +example.md(ความรู้) - โหลด และ เปิดใช้ skill (activation): เติม prompt และเลือก tool ที่ skill ต้องใช้
- ตรวจกฎด้วยโค้ด และให้ลองใหม่เมื่อผิด (recovery)
- เทียบผล และนับว่า skill เพิ่ม token เท่าไร
ข้อมูล paper เป็นข้อมูลจำลองเพื่อการสอน (เลข arXiv ชื่อ ผู้เขียน และปีเป็นของจริง บทสรุปบรรทัดเดียวเขียนขึ้นสำหรับ lab) ส่วน output ของ model มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §22.1, §22.3.4, §22.4 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึง 0.1 เซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv, pyyaml (ติดตั้งใน 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 pyyamlimport json, os, re
from pathlib import Path
import yaml
from openai import OpenAIdef 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"]1. คลัง paper, tool และลูปของ agent
คลัง paper จำลองแปดเรื่อง (เรื่องความจำของ agent และการใช้ tool) และ tool สามตัว:
| tool | ทำอะไร |
|---|---|
search_papers(query) |
ค้นจากคำในชื่อและบทสรุป คืนเลขและชื่อ |
get_paper(paper_id) |
คืนข้อมูลเต็มของ paper หนึ่งเรื่อง |
word_count(text) |
นับคำ |
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]})
def word_count(text: str) -> str:
return json.dumps({"words": len(text.split())})
FUNCS = {"search_papers": search_papers, "get_paper": get_paper, "word_count": word_count}
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"]}}},
"word_count": {"type": "function", "function": {"name": "word_count",
"description": "Count the words in a text.",
"parameters": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}},
}Model: google/gemma-4-26b-a4b-it — model เดียวกับทุก EP ล็อก provider เป็น Makora · lab นี้ต้องการ tool calling ซึ่ง Gemma 4 ทำได้ · ราคา 0.09 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.28 ต่อล้าน token ขาออก — งานสรุปหนึ่งรอบราว 0.03 เซ็นต์ · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-26: 4 ใน 4 ครั้งได้ 429 “rate-limited”)
MODEL = "google/gemma-4-26b-a4b-it"
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}def run_agent(system, task, tools, max_steps=8):
msgs = [{"role": "system", "content": system}, {"role": "user", "content": task}]
info = {"prompt_tokens": None, "fetched": set()}
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])
COST["chat"] += r.usage.cost
info["prompt_tokens"] = info["prompt_tokens"] or r.usage.prompt_tokens
msg = r.choices[0].message
if not msg.tool_calls:
return msg.content, info
# ✏️ TODO 1 (▶ วิดีโอ 2:51): รัน tool ที่ model เลือก แล้วส่งผลกลับเข้าไปในข้อความ
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})")
if call.function.name == "get_paper":
info["fetched"].add(args["paper_id"])
msgs.append({"role": "tool", "tool_call_id": call.id,
"content": ___})
return None, infodef run_agent(system, task, tools, max_steps=8):
msgs = [{"role": "system", "content": system}, {"role": "user", "content": task}]
info = {"prompt_tokens": None, "fetched": set()}
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])
COST["chat"] += r.usage.cost
info["prompt_tokens"] = info["prompt_tokens"] or r.usage.prompt_tokens
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})")
if call.function.name == "get_paper":
info["fetched"].add(args["paper_id"])
msgs.append({"role": "tool", "tool_call_id": call.id,
"content": FUNCS[call.function.name](**args)})
return None, info2. สั่งงานโดยไม่มี skill
system prompt มีแค่บรรทัดเดียว และ agent ได้ tool ทั้งสามตัว
BASE = "You are a research assistant for university students."
TASK = "Summarize 3 papers on agent memory for first-year students."
plain, plain_info = run_agent(BASE, TASK, ["search_papers", "get_paper", "word_count"])
print(f"\n{len(plain.split())} words · papers opened: {sorted(plain_info['fetched'])}\n")
print(plain[:700], "…") 🔧 search_papers({'query': 'LLM agent memory architecture survey'})
🔧 get_paper({'paper_id': '2310.08560'})
🔧 get_paper({'paper_id': '2304.03442'})
🔧 get_paper({'paper_id': '2303.11366'})
621 words · papers opened: ['2303.11366', '2304.03442', '2310.08560']
To help you understand how AI "agents" (AI programs that can act on their own) remember things, I have selected three foundational papers. I have summarized them using analogies that are easy to grasp for a first-year student.
In the world of AI, "memory" isn't just a database; it's how an agent uses past experiences to make better decisions in the future.
---
### 1. MemGPT: The "Computer Hard Drive" Approach
**Paper:** *MemGPT: Towards LLMs as Operating Systems* (Packer et al., 2023)
**The Problem:**
Large Language Models (like ChatGPT) have a "context window," which is like a human's short-term working memory. Once a conversation gets too long, the AI starts "forgetting" the beginning …
3. เขียน skill เป็นโฟลเดอร์
skills/paper-summary/
├── SKILL.md ← ส่วนหัว (name, description, version, tools) + คำสั่ง ขั้นตอน และกฎ
└── example.md ← ความรู้: ตัวอย่างคำตอบที่ดี
| ส่วนของ skill (§22.1) | อยู่ตรงไหน |
|---|---|
| prompt: คำสั่ง ข้อจำกัด บทบาท | เนื้อหาของ SKILL.md |
| tool ที่ต้องใช้ | tools: ในส่วนหัว |
| ความรู้ | example.md |
| ขั้นตอน | ## Workflow |
| กฎ | ## Guardrails |
ส่วนหัวระหว่าง --- เป็น YAML (เรียกว่า frontmatter) — รูปแบบ SKILL.md นี้หลายเครื่องมือใช้กัน ตำราบอกว่ายังไม่มี schema มาตรฐานของวงการ (§22.5)
Path("skills/paper-summary").mkdir(parents=True, exist_ok=True)%%writefile skills/paper-summary/SKILL.md
---
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.Writing skills/paper-summary/SKILL.md
%%writefile skills/paper-summary/example.md
# 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"}]}Writing skills/paper-summary/example.md
4. โหลด และเปิดใช้ skill
วงจรชีวิตของ skill (§22.4) ขั้นที่ 3 activation: ใส่คำสั่ง tool และความรู้ของ skill เข้าไปใน context
# ✏️ TODO 2 (▶ วิดีโอ 5:31): แปลงส่วนหัว YAML เป็น dictionary
def load_skill(folder):
folder = Path(folder)
_, header, body = (folder / "SKILL.md").read_text().split("---", 2)
skill = ___
skill["instructions"] = body.strip()
skill["knowledge_text"] = "\n\n".join((folder / f).read_text() for f in skill.get("knowledge", []))
return skill
skill = load_skill("skills/paper-summary")
print({k: skill[k] for k in ["name", "version", "tools", "knowledge"]})
print(skill["description"])def load_skill(folder):
folder = Path(folder)
_, header, body = (folder / "SKILL.md").read_text().split("---", 2)
skill = yaml.safe_load(header)
skill["instructions"] = body.strip()
skill["knowledge_text"] = "\n\n".join((folder / f).read_text() for f in skill.get("knowledge", []))
return skill
skill = load_skill("skills/paper-summary")
print({k: skill[k] for k in ["name", "version", "tools", "knowledge"]})
print(skill["description"]){'name': 'paper-summary', 'version': '1.0.0', 'tools': ['search_papers', 'get_paper'], 'knowledge': ['example.md']}
Summarize research papers from the library for students, with a citation on every sentence.
# ✏️ TODO 3 (▶ วิดีโอ 6:02): คืนรายชื่อ tool ที่ skill ต้องใช้ (ไม่ใช่ทุก tool)
def activate(skill, base=BASE):
system = f"{base}\n\n{skill['instructions']}\n\n## Knowledge\n{skill['knowledge_text']}"
return system, ___def activate(skill, base=BASE):
system = f"{base}\n\n{skill['instructions']}\n\n## Knowledge\n{skill['knowledge_text']}"
return system, skill["tools"]5. ตรวจกฎด้วยโค้ด และลองใหม่เมื่อผิด
กฎที่ตรวจด้วยโค้ดได้ ไม่ต้องให้ model ตรวจตัวเอง (EP04: model ตรวจกฎแบบนับพลาดบ่อย) ถ้าผิด ส่งรายการปัญหากลับไปให้ลองใหม่หนึ่งครั้ง — build in recovery (§22.3.4)
def check(answer, fetched, max_words=120):
text = (answer or "").strip().removeprefix("```json").removesuffix("```").strip()
try:
sentences = json.loads(text)["sentences"]
except (json.JSONDecodeError, KeyError, TypeError):
return ["not JSON with a 'sentences' list"]
# ✏️ TODO 4 (▶ วิดีโอ 6:44): หาประโยคที่อ้าง paper ที่ไม่ได้เปิดอ่าน
problems = [f"sentence {i} cites {s.get('cite')!r}, which was not fetched with get_paper"
for i, s in enumerate(sentences, 1) if ___]
words = sum(len(s.get("text", "").split()) for s in sentences)
if words > max_words:
problems.append(f"{words} words, more than {max_words}")
return problemsdef check(answer, fetched, max_words=120):
text = (answer or "").strip().removeprefix("```json").removesuffix("```").strip()
try:
sentences = json.loads(text)["sentences"]
except (json.JSONDecodeError, KeyError, TypeError):
return ["not JSON with a 'sentences' list"]
problems = [f"sentence {i} cites {s.get('cite')!r}, which was not fetched with get_paper"
for i, s in enumerate(sentences, 1) if s.get("cite") not in fetched]
words = sum(len(s.get("text", "").split()) for s in sentences)
if words > max_words:
problems.append(f"{words} words, more than {max_words}")
return problemsdef run_skill(skill, task):
system, tools = activate(skill)
answer, info = run_agent(system, task, tools)
problems = check(answer, info["fetched"])
# ✏️ TODO 5 (▶ วิดีโอ 7:12): ถ้ามีปัญหา ให้ลองใหม่หนึ่งครั้งพร้อมรายการปัญหา
if ___:
print(" ⚠️ retry:", problems)
answer, info2 = run_agent(system, f"{task}\n\nYour last answer broke these rules: {problems}. Answer again.", tools)
info["fetched"] |= info2["fetched"]
problems = check(answer, info["fetched"])
return answer, info, problemsdef run_skill(skill, task):
system, tools = activate(skill)
answer, info = run_agent(system, task, tools)
problems = check(answer, info["fetched"])
if problems:
print(" ⚠️ retry:", problems)
answer, info2 = run_agent(system, f"{task}\n\nYour last answer broke these rules: {problems}. Answer again.", tools)
info["fetched"] |= info2["fetched"]
problems = check(answer, info["fetched"])
return answer, info, problems6. งานเดิม แต่มี skill
answer, info, problems = run_skill(skill, TASK)
print(f"\nchecks: {problems or 'all passed'}\n")
for s in json.loads(answer.strip().removeprefix("```json").removesuffix("```"))["sentences"]:
print(f"[{s['cite']}] {s['text']}") 🔧 search_papers({'query': 'LLM agent memory architecture'})
🔧 get_paper({'paper_id': '2504.19413'})
🔧 get_paper({'paper_id': '2310.08560'})
🔧 get_paper({'paper_id': '2304.03442'})
checks: all passed
[2504.19413] Mem0 allows an AI to extract facts from conversations to add, update, or delete them in a long-term storage system.
[2310.08560] MemGPT works like a computer's operating system by moving facts between a small immediate space and a large external storage.
[2304.03442] Generative Agents use a memory stream to record observations and then score them based on how recent or important they are.
print(f"{'':16}{'without skill':>15}{'with skill':>12}")
print(f"{'checks passed':16}{str(not check(plain, plain_info['fetched'])):>15}{str(not problems):>12}")
print(f"{'input tokens':16}{plain_info['prompt_tokens']:>15}{info['prompt_tokens']:>12}")
print(f"\nthe skill adds {info['prompt_tokens'] - plain_info['prompt_tokens']} tokens to every call · cost so far: ${COST['chat']:.5f}") without skill with skill
checks passed False True
input tokens 212 463
the skill adds 251 tokens to every call · cost so far: $0.00067
สรุป
| ไม่มี skill | มี skill paper-summary |
|
|---|---|---|
| ขั้นตอน | agent เดาเอง (บางรอบไม่เปิด paper เลย) | ค้น → เปิดทุกเรื่อง → เทียบ → เขียน |
| tool | ทั้งสามตัว | เฉพาะ search_papers, get_paper (tool binding) |
| รูปแบบ | markdown หลายร้อยคำ ไม่มีการอ้างอิง | JSON ทุกประโยคอ้าง paper ที่เปิดอ่าน |
| ต้นทุน | — | token ขาเข้าเพิ่มทุกครั้งที่เรียก model |
skill คือ ข้อความในไฟล์ — แก้ไฟล์ ได้พฤติกรรมใหม่ทันที ไม่ต้องฝึก model ใหม่ (§22.6)
แบบฝึกหัด
- เปลี่ยนกฎเป็น
At most 40 wordsแต่ให้checkยังใช้max_words=120— แล้วลองสลับกัน: กฎใน skill 120 แต่ตรวจที่ 40 ดูว่า recovery ทำงานไหม - เพิ่มขั้นในส่วน Workflow ให้ agent ใช้
word_countก่อนตอบ — ต้องแก้ส่วนหัวตรงไหนด้วย - เขียน skill ที่สอง
paper-quizที่ออกข้อสอบหนึ่งข้อต่อ paper หนึ่งเรื่อง โดยใช้load_skillกับrun_skillเดิม
ถัดไป — Lab 2: skill หลายตัวในคลังเดียว ให้ model เลือกเองจากคำอธิบาย และนับว่าประหยัด context ได้เท่าไร