Skip to main content

Lab 4 — skill ชุดเดิม กับ deepagents

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–3 เราเขียนทุกชิ้นเอง Lab นี้ใช้ deepagents (LangChain) ที่มี SkillsMiddleware ในตัว — โฟลเดอร์ SKILL.md แบบเดียวกับของเรา

ที่เราเขียนเอง (Lab 1–2) ใน deepagents
discover() อ่านแค่ส่วนหัว SkillsMiddleware อ่าน frontmatter แล้วใส่ ชื่อ + คำอธิบาย + ที่อยู่ไฟล์ ใน system prompt
route() เรียก model แยกหนึ่งครั้ง ไม่มี router แยก — model ตัวที่ทำงาน อ่านรายการแล้วเลือกเอง
load_skill() + activate() model เรียก read_file เปิด SKILL.md เอง (progressive disclosure)
tools: ในส่วนหัว (tool binding) metadata.include_tools — tool โผล่ให้ model เห็น หลัง อ่าน skill แล้ว
visible(role) + allowed_roles sources คนละชุดต่อบทบาท

ข้อมูล paper เป็นข้อมูลจำลองเพื่อการสอน (เลข arXiv ชื่อ ผู้เขียน และปีเป็นของจริง) ส่วน output ของ model มาจากการรันจริง

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §22.2.2, §22.4, §22.5 — CC BY-SA 4.0

0. เตรียมเครื่องก่อนเริ่ม

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key ตั้งค่าแบบเดียวกับ Lab 1 (lab นี้ใช้ไม่ถึง 0.2 เซ็นต์ดอลลาร์)
Packages deepagents และ LangChain ตามเวอร์ชันที่ล็อกไว้ (ติดตั้งใน cell ถัดไป)

วิธีใส่ key และเหตุผลที่เลือก model อยู่ใน Lab 1 — Colab: 🔑 Secrets → OPENROUTER_API_KEY · เครื่องตัวเอง: ไฟล์ .env

%pip install -q "deepagents==0.7.35" "langchain==1.5.0" "langchain-core==1.8.0" "langchain-openai==1.7.4" "langgraph==1.2.21" "langgraph-prebuilt==1.1.1" "langchain-anthropic==1.7.10" "langchain-google-genai==4.5.0" "openai==3.50.0" python-dotenv
import json, os, re
from pathlib import Path

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"]

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"},
}

1. โฟลเดอร์ skill: รูปแบบเดียวกับ Lab 1–2

workspace/                      ← agent เห็นแค่โฟลเดอร์นี้
└── skills/
    ├── shared/                 ← ทุกคน
    │   ├── paper-summary/SKILL.md
    │   └── formatter/SKILL.md
    └── teacher/                ← อาจารย์เท่านั้น
        └── grade-submission/SKILL.md

ส่วนหัวต่างจากของเรานิดเดียว: ช่องที่ไม่ใช่ name / description ย้ายไปอยู่ใต้ metadata:

ของเรา deepagents
version: 1.0.0 metadata: version: "1.0.0"
tools: [search_papers, get_paper] metadata: include_tools: search_papers get_paper
SKILLS = {
    "shared/paper-summary": """---
name: paper-summary
description: Summarize research papers from the library for students, with a citation on every sentence.
metadata:
  version: "1.0.0"
  include_tools: search_papers get_paper
---
# 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.
""",
    "shared/formatter": """---
name: formatter
description: Format a reference (citation) for a paper in the library in APA style, from its arXiv id or title.
metadata:
  version: "1.0.0"
  include_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.
""",
    "teacher/grade-submission": """---
name: grade-submission
description: Grade a student's answer against the course rubric and explain the score.
metadata:
  version: "1.0.0"
---
# Grade submission
## Rubric — "What does MemGPT do?" (3 points)
1. Says the LLM has a small main context (1 point)
2. Says there is a large external store (1 point)
3. Says the LLM moves (pages) facts between the two (1 point)
## Guardrails
- Score each rubric line, then add them up: "Score: n/3".
- Explain every point taken off, in one line each.
""",
}
for name, text in SKILLS.items():
    Path(f"workspace/skills/{name}").mkdir(parents=True, exist_ok=True)
    Path(f"workspace/skills/{name}/SKILL.md").write_text(text)
print(sorted(str(p.parent.relative_to("workspace")) for p in Path("workspace").glob("skills/*/*/SKILL.md")))
['skills/shared/formatter', 'skills/shared/paper-summary', 'skills/teacher/grade-submission']

2. tool, model และ backend

from langchain_core.tools import tool

@tool
def search_papers(query: str, max_results: int = 5) -> str:
    """Search the paper library by keywords in the title or summary. Returns ids and titles."""
    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])

@tool
def get_paper(paper_id: str) -> str:
    """Get one paper's full record (title, authors, year, summary) by its arXiv id."""
    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]})
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="google/gemma-4-26b-a4b-it", base_url="https://openrouter.ai/api/v1",
                   api_key=load_key(), temperature=0,
                   extra_body={"reasoning": {"enabled": False},
                               "provider": {"order": ["makora"], "allow_fallbacks": False}})
# ✏️ TODO 1 (▶ วิดีโอ 2:13): ให้ agent เห็นแค่โฟลเดอร์ workspace
from deepagents.backends.filesystem import FilesystemBackend

backend = FilesystemBackend(root_dir=___, virtual_mode=True)
from deepagents.backends.filesystem import FilesystemBackend

backend = FilesystemBackend(root_dir="workspace", virtual_mode=True)

3. สร้าง agent: create_agent + middleware สองตัว

  • FilesystemMiddleware(tools=["read_file"]) — ให้ tool อ่านไฟล์ อย่างเดียว (ไม่มี write / edit / delete → agent แก้ skill ไม่ได้)
  • SkillsMiddleware(sources=…, tools=…) — รายการ skill ใน system prompt + tool ที่เปิดเมื่อ skill ถูกอ่าน

ทำไมไม่ใช้ create_deep_agent ตรงๆ: มันเพิ่ม tool อีกหลายตัว (เขียนไฟล์ · ค้นไฟล์ · task ส่งงานให้ subagent) ตอนลอง Gemma ส่งงานอ้างอิงให้ subagent โดยไม่เปิด skill เลย และใช้ token มากกว่าราวห้าเท่า

from langchain.agents import create_agent
from deepagents import FilesystemMiddleware
from deepagents.middleware.skills import SkillsMiddleware

BASE = ("You are a research assistant for university students. When a skill fits the request, read its SKILL.md "
        "with read_file first, then follow it. Act with tool calls; don't announce what you are going to do.")

# ✏️ TODO 2 (▶ วิดีโอ 3:08): ให้ agent อ่านไฟล์ได้อย่างเดียว และเปิด tool สองตัวเมื่ออ่าน skill

def make_agent(sources):
    return create_agent(model, tools=[], system_prompt=BASE, middleware=[
        FilesystemMiddleware(backend=backend, tools=___),
        SkillsMiddleware(backend=backend, sources=sources, tools=___),
    ])
from langchain.agents import create_agent
from deepagents import FilesystemMiddleware
from deepagents.middleware.skills import SkillsMiddleware

BASE = ("You are a research assistant for university students. When a skill fits the request, read its SKILL.md "
        "with read_file first, then follow it. Act with tool calls; don't announce what you are going to do.")

def make_agent(sources):
    return create_agent(model, tools=[], system_prompt=BASE, middleware=[
        FilesystemMiddleware(backend=backend, tools=["read_file"]),
        SkillsMiddleware(backend=backend, sources=sources, tools=[search_papers, get_paper]),
    ])
from langchain_core.callbacks import BaseCallbackHandler

class Show(BaseCallbackHandler):
    """Prints, live, the tools the model is offered on each call, and every tool call."""
    def on_chat_model_start(self, serialized, messages, **kw):
        names = [t["function"]["name"] for t in kw.get("invocation_params", {}).get("tools", [])]
        print(f"🧠 model call · tools offered: {names}")
    def on_tool_start(self, serialized, input_str, **kw):
        print(f"   🔧 {serialized['name']}({input_str[:90]})")

TOKENS = {"in": 0, "out": 0}

def ask(agent, question):
    result = agent.invoke({"messages": [{"role": "user", "content": question}]}, {"callbacks": [Show()]})
    used = [m.usage_metadata for m in result["messages"] if getattr(m, "usage_metadata", None)]
    tin, tout = sum(u["input_tokens"] for u in used), sum(u["output_tokens"] for u in used)
    TOKENS["in"] += tin; TOKENS["out"] += tout
    print(f"\n💬 {result['messages'][-1].content}\n\n📥 {tin} input tokens over {len(used)} model calls")

4. งานเดิมจาก Lab 1 และ Lab 2

student = make_agent(["/skills/shared/"])
ask(student, "Summarize 3 papers on agent memory for first-year students.")
🧠 model call · tools offered: ['read_file']
   🔧 read_file({'file_path': '/skills/shared/paper-summary/SKILL.md', 'limit': 1000})
🧠 model call · tools offered: ['read_file', 'get_paper', 'search_papers']
   🔧 search_papers({'query': 'agent memory'})
🧠 model call · tools offered: ['read_file', 'get_paper', 'search_papers']
   🔧 get_paper({'paper_id': '2504.19413'})
   🔧 get_paper({'paper_id': '2502.12110'})
   🔧 get_paper({'paper_id': '2304.03442'})
🧠 model call · tools offered: ['read_file', 'get_paper', 'search_papers']

💬 ```json
{
  "papers": [
    "2504.19413",
    "2502.12110",
    "2304.03442"
  ],
  "sentences": [
    {
      "text": "One method uses a large language model to pull facts from conversations and manage them in a long-term storage system (2504.19413).",
      "cite": "2504.19413"
    },
    {
      "text": "Another approach organizes memory as a series of linked notes that use keywords and tags to connect new information to old (2502.12110).",
      "cite": "2502.12110"
    },
    {
      "text": "A third system records a stream of observations and ranks them based on how recent or important they are (2304.03442).",
      "cite": "2304.03442"
    },
    {
      "text": "These agents can also write reflections to better understand their experiences (2304.03442).",
      "cite": "2304.03442"
    }
  ]
}
```

📥 5937 input tokens over 4 model calls
ask(student, "How do I cite the MemGPT paper in my report?")
🧠 model call · tools offered: ['read_file']
   🔧 read_file({'file_path': '/skills/shared/formatter/SKILL.md', 'limit': 1000})
🧠 model call · tools offered: ['read_file', 'get_paper', 'search_papers']
   🔧 search_papers({'query': 'MemGPT'})
🧠 model call · tools offered: ['read_file', 'get_paper', 'search_papers']
   🔧 get_paper({'paper_id': '2310.08560'})
🧠 model call · tools offered: ['read_file', 'get_paper', 'search_papers']

💬 Packer et al. (2023). MemGPT: Towards LLMs as Operating Systems. arXiv:2310.08560.

📥 5226 input tokens over 4 model calls

5. บทบาทต่างกัน = sources ต่างกัน (§22.5)

# ✏️ TODO 3 (▶ วิดีโอ 5:00): ให้อาจารย์เห็นทั้งโฟลเดอร์ shared และ teacher
ROLES = {"student": ["/skills/shared/"], "teacher": ___}
for role, sources in ROLES.items():
    names = sorted(p.parent.name for s in sources for p in Path("workspace" + s).glob("*/SKILL.md"))
    print(f"{role:8} sources {sources} → skills {names}")

teacher = make_agent(ROLES["teacher"])
ask(teacher, "Grade this student answer to 'What does MemGPT do?': 'MemGPT stores facts in a database.'")
ROLES = {"student": ["/skills/shared/"], "teacher": ["/skills/shared/", "/skills/teacher/"]}
for role, sources in ROLES.items():
    names = sorted(p.parent.name for s in sources for p in Path("workspace" + s).glob("*/SKILL.md"))
    print(f"{role:8} sources {sources} → skills {names}")

teacher = make_agent(ROLES["teacher"])
ask(teacher, "Grade this student answer to 'What does MemGPT do?': 'MemGPT stores facts in a database.'")
student  sources ['/skills/shared/'] → skills ['formatter', 'paper-summary']
teacher  sources ['/skills/shared/', '/skills/teacher/'] → skills ['formatter', 'grade-submission', 'paper-summary']
🧠 model call · tools offered: ['read_file']
   🔧 read_file({'file_path': '/skills/teacher/grade-submission/SKILL.md', 'limit': 1000})
🧠 model call · tools offered: ['read_file']

💬 The student's answer is: "MemGPT stores facts in a database."

**Score: 1/3**

**Explanation:**
- The answer fails to mention the limitation of the LLM's main context window.
- The answer fails to mention the mechanism of moving (paging) information between the context and the external store.

📥 2323 input tokens over 2 model calls
print(f"tokens: {TOKENS['in']} in · {TOKENS['out']} out · "
      f"≈ ${TOKENS['in'] * 0.09e-6 + TOKENS['out'] * 0.28e-6:.5f} (Makora's price)")
tokens: 13486 in · 657 out · ≈ $0.00140 (Makora's price)

สรุป

เขียนเอง (Lab 1–3) deepagents
ค้นพบ discover() SkillsMiddleware + sources
เลือก router แยก (+1 การเรียก) model ตัวที่ทำงานเลือกจากรายการ
เปิดใช้ activate() ใส่ทั้งหมดใน system prompt read_file เปิด SKILL.md เมื่อต้องใช้
tool binding tools: metadata.include_tools — tool โผล่หลังอ่าน skill
สิทธิ์ allowed_roles sources ต่อบทบาท + read_file อย่างเดียว
คลี่กราฟ · คลังที่เรียนรู้ Lab 3 ไม่มีในตัว — เขียนเพิ่มเอง
token (งานสรุปหนึ่งงาน) ราว 2,300 (Lab 2) ราว 6,000

แบบฝึกหัด

  1. ลบ metadata.include_tools ออกจาก formatter แล้วถามเรื่องการอ้างอิงอีกครั้ง — agent ยังค้น paper ได้ไหม
  2. ลองเปลี่ยนคำอธิบายของ formatter กลับเป็น Formats text. — model ตัวที่ทำงานพลาดแบบ router ใน Lab 2 ไหม
  3. ลอง create_deep_agent(model, skills=["/skills/shared/"], backend=backend) แล้วนับ tool และ token เทียบกัน

ถัดไป — Recap: สรุป EP14 ทั้งตอน จากสิ่งที่เห็นในสี่ lab