Lab 3 — skill ที่ใช้ 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 ที่คุณรันเองจึงอาจต่างจากหน้านี้
สองเรื่องจากคลิปทฤษฎีที่ Lab 1–2 ยังไม่ได้ทำ
ส่วน A — Hierarchical composition (§22.2.3)
- skill ประกาศ
requiresพร้อมเวอร์ชัน (citation-format@1) - เขียนตัว คลี่กราฟ (resolver): ลำดับการโหลด · skill ที่หายไป · เวอร์ชันไม่ตรง
- ดูว่า skill ย่อยตัวเดียว ใช้ร่วมกัน ได้หลายตัว แล้วรัน skill ที่ประกอบขึ้นจริง
ส่วน B — คลังที่เรียนรู้เอง แบบ Voyager (§22.4 ขั้นที่ 6)
- ไม่มี skill ที่เหมาะ → agent เขียน skill ใหม่เป็นโค้ด พร้อม test
- ตรวจ ด้วยการรัน test → ผ่านแล้วเก็บเข้าคลัง
- คำถามถัดไป → ใช้ skill ที่เก็บไว้ซ้ำ ไม่ต้องเขียนใหม่
ข้อมูล paper เป็นข้อมูลจำลองเพื่อการสอน (เลข arXiv ชื่อ ผู้เขียน และปีเป็นของจริง) ส่วน output และโค้ดที่ model เขียน มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §22.2.3, §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."""
msgs = [{"role": "system", "content": system}, {"role": "user", "content": task}]
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
msg = r.choices[0].message
if not msg.tool_calls:
return msg.content
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
def ask_json(system, user, schema, name):
"""One model call with strict structured output (EP02); returns the parsed JSON.
max_tokens: strict JSON can loop on whitespace until the limit (EP02) — a cut-off answer raises JSONDecodeError."""
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, max_tokens=2000, messages=[
{"role": "system", "content": system}, {"role": "user", "content": user}],
response_format={"type": "json_schema", "json_schema": {"name": name, "strict": True, "schema": schema}})
COST["chat"] += r.usage.cost
return json.loads(r.choices[0].message.content)
BASE = "You are a research assistant for university students."A1. skill ที่ประกาศว่าต้องใช้ skill อื่น
literature-review 1.2.0 ──▶ paper-summary 1.0.0
└────▶ citation-format 1.1.0 ◀── reading-list
weekly-report ──▶ literature-review, meeting-notes (❓ ไม่มีในคลัง)
thesis-chapter ──▶ literature-review, citation-format@2 (❓ คลังมี 1.1.0)
requires: ["citation-format@1"] = ต้องใช้ citation-format เวอร์ชันหลัก 1 (1.0, 1.1, … ได้หมด แต่ 2.0 ไม่ได้)
def skill(name, version, requires=(), tools=(), instructions=""):
return {"name": name, "version": version, "requires": list(requires), "tools": list(tools),
"instructions": instructions}
REGISTRY = {s["name"]: s for s in [
skill("paper-summary", "1.0.0", tools=["search_papers", "get_paper"], instructions=
"Write for first-year students. Call search_papers, then get_paper for every paper you use; use only what "
"get_paper returns. Each sentence cites one fetched paper id in square brackets, e.g. [2310.08560]."),
skill("citation-format", "1.1.0", tools=["get_paper"], instructions=
"Format each reference as: Authors (Year). Title. arXiv:<id>. Use only fields from get_paper."),
skill("literature-review", "1.2.0", requires=["paper-summary@1", "citation-format@1"], instructions=
"1. Use the paper-summary skill to write one short paragraph per paper (at most 2 sentences each).\n"
"2. Add one sentence that compares the papers.\n"
"3. End with a 'References' list, using the citation-format skill, one line per paper cited."),
skill("reading-list", "1.0.0", requires=["citation-format@1"], instructions="List papers on a topic as APA references."),
skill("weekly-report", "1.0.0", requires=["literature-review@1", "meeting-notes@1"]),
skill("thesis-chapter", "1.0.0", requires=["literature-review@1", "citation-format@2"]),
]}A2. ตัวคลี่กราฟ (resolver)
ก่อนทำงาน ตัวคุมงานต้องคลี่กราฟให้ครบ (§22.2.3): skill ย่อยมาก่อน skill ที่ใช้มัน (ลำดับแบบ topological) และหยุดทันทีถ้า skill หาย เวอร์ชันไม่ตรง หรือกราฟวนกลับ (ไม่ใช่ DAG)
def resolve(name, order=None, path=()):
order = [] if order is None else order
if name in order:
return order
if name in path:
raise ValueError(f"cycle: {' → '.join(path + (name,))}")
# ✏️ TODO 1 (▶ วิดีโอ 2:23): หยุดเมื่อเวอร์ชันหลักในคลังไม่ตรงกับที่ขอ
for dep in REGISTRY[name]["requires"]:
dep_name, major = dep.split("@")
if dep_name not in REGISTRY:
raise LookupError(f"{name} needs {dep_name}, which is not in the library")
have = REGISTRY[dep_name]["version"]
if ___:
raise LookupError(f"{name} needs {dep_name} {major}.x, the library has {have}")
# ✏️ TODO 2 (▶ วิดีโอ 2:40): คลี่ skill ย่อยก่อน แล้วจึงใส่ skill นี้ต่อท้าย
resolve(dep_name, order, path + (name,))
___
return orderdef resolve(name, order=None, path=()):
order = [] if order is None else order
if name in order:
return order
if name in path:
raise ValueError(f"cycle: {' → '.join(path + (name,))}")
for dep in REGISTRY[name]["requires"]:
dep_name, major = dep.split("@")
if dep_name not in REGISTRY:
raise LookupError(f"{name} needs {dep_name}, which is not in the library")
have = REGISTRY[dep_name]["version"]
if have.split(".")[0] != major:
raise LookupError(f"{name} needs {dep_name} {major}.x, the library has {have}")
resolve(dep_name, order, path + (name,))
order.append(name)
return orderfor name in ["literature-review", "reading-list", "weekly-report", "thesis-chapter"]:
try:
print(f"✅ {name:18} → {resolve(name)}")
except (LookupError, ValueError) as e:
print(f"❌ {name:18} → {e}")✅ literature-review → ['paper-summary', 'citation-format', 'literature-review']
✅ reading-list → ['citation-format', 'reading-list']
❌ weekly-report → weekly-report needs meeting-notes, which is not in the library
❌ thesis-chapter → thesis-chapter needs citation-format 2.x, the library has 1.1.0
# ✏️ TODO 3 (▶ วิดีโอ 3:18): หา skill ที่มี sub อยู่ใน requires
def used_by(sub):
return [n for n, s in REGISTRY.items() if ___]
print("citation-format is used by:", used_by("citation-format"))def used_by(sub):
return [n for n, s in REGISTRY.items() if any(d.split("@")[0] == sub for d in s["requires"])]
print("citation-format is used by:", used_by("citation-format"))citation-format is used by: ['literature-review', 'reading-list', 'thesis-chapter']
A3. รัน skill ที่ประกอบขึ้น
เปิดใช้ทุก skill ตามลำดับที่คลี่ได้ — skill ย่อยอยู่ก่อนใน system prompt
order = resolve("literature-review")
system = BASE + "".join(f"\n\n# Skill: {n} {REGISTRY[n]['version']}\n{REGISTRY[n]['instructions']}" for n in order)
tools = sorted({t for n in order for t in REGISTRY[n]["tools"]})
print(run_agent(system, "Write a short literature review of 3 papers on agent memory.", tools)) 🔧 search_papers({'query': 'agent memory LLM'})
🔧 get_paper({'paper_id': '2504.19413'})
🔧 get_paper({'paper_id': '2502.12110'})
🔧 get_paper({'paper_id': '2310.08560'})
Mem0 focuses on creating scalable long-term memory by having an LLM extract, update, or delete specific facts from conversations [2504.19413]. A-MEM approaches memory by organizing information into linked notes that use keywords and tags to connect new information to old data [2502.12110]. MemGPT treats memory management like a computer operating system, moving facts between a limited main context and a larger external storage area [2310.08560]. While Mem0 and A-MEM focus on how information is structured and updated, MemGPT focuses on the technical movement of data between different storage layers.
References
Chhikara et al. (2025). Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory. arXiv:2504.19413
Xu et al. (2025). A-MEM: Agentic Memory for LLM Agents. arXiv:2502.12110
Packer et al. (2023). MemGPT: Towards LLMs as Operating Systems. arXiv:2310.08560
B1. คลังที่เรียนรู้เอง: เขียน skill ใหม่เป็นโค้ด
แบบ Voyager: skill คือ โค้ดที่ผ่านการตรวจ เก็บไว้ใช้ซ้ำ ทุก skill คือฟังก์ชัน run(papers) ที่รับคลัง paper อย่างเดียว · model เขียน code + test · เรารัน test ก่อนเก็บ
⚠️ exec รันโค้ดที่ model เขียนบนเครื่องเรา — ทำแบบนี้ เฉพาะใน lab ระบบจริงต้องรันใน sandbox (EP08)
LIBRARY = Path("skills/learned") # delete this folder to start again from an empty library
LIBRARY.mkdir(parents=True, exist_ok=True)
WRITE = ("You write reusable Python skills for a research assistant. A skill is one function run(papers) that takes "
"ONLY papers (no other arguments). papers is a dict: arXiv id -> {title, authors, year, summary}. "
"It returns a JSON-serializable value. Make it general, useful for similar questions later. Standard library only. "
"Also write test: Python lines with assert statements that call run() on a small papers dict built in the test. "
"name: short kebab-case. description: one sentence a router can match later.")# ✏️ TODO 4 (▶ วิดีโอ 4:59): รัน test ต่อจากโค้ดของ skill ใน namespace เดียวกัน
def verify(code, test):
ns = {}
try:
exec(code, ns)
___
return None
except Exception as e:
return f"{type(e).__name__}: {e}"
def learn(task, tries=3):
schema = {"type": "object", "additionalProperties": False, "required": ["name", "description", "code", "test"],
"properties": {k: {"type": "string"} for k in ["name", "description", "code", "test"]}}
feedback = ""
for i in range(1, tries + 1):
try:
s = ask_json(WRITE, task + feedback, schema, "skill")
except json.JSONDecodeError:
print(f" ✍️ try {i}: the answer was cut off")
feedback = "\n\nYour last answer was cut off. Keep the code and test short."
continue
error = verify(s["code"], s["test"])
print(f" ✍️ try {i}: {s['name']} → {error or 'test passed'}")
if not error:
folder = LIBRARY / s["name"]
folder.mkdir(exist_ok=True)
(folder / "SKILL.md").write_text(f"---\nname: {s['name']}\ndescription: {s['description']}\n"
f"version: 1.0.0\nverified: true\n---\n")
(folder / "skill.py").write_text(s["code"])
return s["name"]
feedback = f"\n\nYour last code failed its test: {error}. Fix it."
return Nonedef verify(code, test):
ns = {}
try:
exec(code, ns)
exec(test, ns)
return None
except Exception as e:
return f"{type(e).__name__}: {e}"
def learn(task, tries=3):
schema = {"type": "object", "additionalProperties": False, "required": ["name", "description", "code", "test"],
"properties": {k: {"type": "string"} for k in ["name", "description", "code", "test"]}}
feedback = ""
for i in range(1, tries + 1):
try:
s = ask_json(WRITE, task + feedback, schema, "skill")
except json.JSONDecodeError:
print(f" ✍️ try {i}: the answer was cut off")
feedback = "\n\nYour last answer was cut off. Keep the code and test short."
continue
error = verify(s["code"], s["test"])
print(f" ✍️ try {i}: {s['name']} → {error or 'test passed'}")
if not error:
folder = LIBRARY / s["name"]
folder.mkdir(exist_ok=True)
(folder / "SKILL.md").write_text(f"---\nname: {s['name']}\ndescription: {s['description']}\n"
f"version: 1.0.0\nverified: true\n---\n")
(folder / "skill.py").write_text(s["code"])
return s["name"]
feedback = f"\n\nYour last code failed its test: {error}. Fix it."
return NoneB2. ใช้ skill ที่เก็บไว้ซ้ำ
solve(question): ให้ router เลือกจากคลัง → ไม่มีที่เหมาะ (none) → learn → รัน run(PAPERS) → model ตอบจากผลของโค้ด
def pick(question):
names = [p.parent.name for p in sorted(LIBRARY.glob("*/SKILL.md"))]
menu = "\n".join(f"- {n}: {yaml.safe_load((LIBRARY / n / 'SKILL.md').read_text().split('---')[1])['description']}"
for n in names)
schema = {"type": "object", "additionalProperties": False, "required": ["skill"],
"properties": {"skill": {"type": "string", "enum": names + ["none"]}}}
return ask_json(f"Pick the code skill whose result can answer the question, or 'none'.\n\nSkills:\n{menu}",
question, schema, "pick")["skill"]
# ✏️ TODO 5 (▶ วิดีโอ 6:10): ถ้าไม่มี skill ที่เหมาะ ให้เขียน skill ใหม่
def solve(question):
name = pick(question)
print(f"📚 library: {sorted(p.name for p in LIBRARY.iterdir())} → {name}")
if name == "none":
name = ___
ns = {}
exec((LIBRARY / name / "skill.py").read_text(), ns)
result = ns["run"](PAPERS)
print(f" ▶ {name}(PAPERS) = {json.dumps(result)[:160]}")
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, messages=[
{"role": "system", "content": "Answer the question from the skill's result only, in one sentence."},
{"role": "user", "content": f"Question: {question}\nResult of {name}: {json.dumps(result)}"}])
COST["chat"] += r.usage.cost
print(f" 💬 {r.choices[0].message.content}")def pick(question):
names = [p.parent.name for p in sorted(LIBRARY.glob("*/SKILL.md"))]
menu = "\n".join(f"- {n}: {yaml.safe_load((LIBRARY / n / 'SKILL.md').read_text().split('---')[1])['description']}"
for n in names)
schema = {"type": "object", "additionalProperties": False, "required": ["skill"],
"properties": {"skill": {"type": "string", "enum": names + ["none"]}}}
return ask_json(f"Pick the code skill whose result can answer the question, or 'none'.\n\nSkills:\n{menu}",
question, schema, "pick")["skill"]
def solve(question):
name = pick(question)
print(f"📚 library: {sorted(p.name for p in LIBRARY.iterdir())} → {name}")
if name == "none":
name = learn(question)
ns = {}
exec((LIBRARY / name / "skill.py").read_text(), ns)
result = ns["run"](PAPERS)
print(f" ▶ {name}(PAPERS) = {json.dumps(result)[:160]}")
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, messages=[
{"role": "system", "content": "Answer the question from the skill's result only, in one sentence."},
{"role": "user", "content": f"Question: {question}\nResult of {name}: {json.dumps(result)}"}])
COST["chat"] += r.usage.cost
print(f" 💬 {r.choices[0].message.content}")for question in ["How many papers per year are in the library?",
"How many papers from 2023 are in the library?",
"List the papers from newest to oldest.",
"Which papers in the library are from the most recent year?"]:
print(f"\n❓ {question}")
solve(question)
❓ How many papers per year are in the library?
📚 library: [] → none
✍️ try 1: papers-per-year-count → test passed
▶ papers-per-year-count(PAPERS) = {"2023": 6, "2025": 2}
💬 There are 6 papers in 2023 and 2 papers in 2025.
❓ How many papers from 2023 are in the library?
📚 library: ['papers-per-year-count'] → papers-per-year-count
▶ papers-per-year-count(PAPERS) = {"2023": 6, "2025": 2}
💬 There are 6 papers from 2023 in the library.
❓ List the papers from newest to oldest.
📚 library: ['papers-per-year-count'] → none
✍️ try 1: sort-papers-by-year → SyntaxError: unterminated string literal (detected at line 43) (<string>, line 43)
✍️ try 2: sort-papers-by-year → test passed
▶ sort-papers-by-year(PAPERS) = [{"title": "Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory", "authors": "Chhikara et al.", "year": 2025, "summary": "an LLM extracts f
💬 The papers from newest to oldest are Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory (2025), A-MEM: Agentic Memory for LLM Agents (2025), MemGPT: Towards LLMs as Operating Systems (2023), Generative Agents: Interactive Simulacra of Human Behavior (2023), Reflexion: Language Agents with Verbal Reinforcement Learning (2023), Voyager: An Open-Ended Embodied Agent with Large Language Models (2023), ReAct: Synergizing Reasoning and Acting in Language Models (2023), and Toolformer: Language Models Can Teach Themselves to Use Tools (2023).
❓ Which papers in the library are from the most recent year?
📚 library: ['papers-per-year-count', 'sort-papers-by-year'] → sort-papers-by-year
▶ sort-papers-by-year(PAPERS) = [{"title": "Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory", "authors": "Chhikara et al.", "year": 2025, "summary": "an LLM extracts f
💬 The papers from the most recent year (2025) are "Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory" and "A-MEM: Agentic Memory for LLM Agents."
for folder in sorted(LIBRARY.iterdir()):
print(f"# {folder.name}\n{(folder / 'SKILL.md').read_text()}{(folder / 'skill.py').read_text()}\n")
print(f"cost: ${COST['chat']:.5f}")# papers-per-year-count
---
name: papers-per-year-count
description: Counts the number of papers published in each year within the provided library.
version: 1.0.0
verified: true
---
import json
from collections import Counter
def run(papers):
"""
Calculates the number of papers published per year.
Args:
papers (dict): A dictionary where keys are arXiv IDs and values are
dicts containing {'title', 'authors', 'year', 'summary'}.
Returns:
dict: A dictionary mapping years (as strings) to the count of papers.
"""
years = []
for paper_id in papers:
year = papers[paper_id].get('year')
if year is not None:
# Ensure year is treated as a string for consistent JSON serialization
years.append(str(year))
counts = Counter(years)
# Return sorted by year for better readability
return dict(sorted(counts.items()))
# Test
def test_papers_per_year_count():
sample_papers = {
"arxiv:1": {"title": "Paper A", "authors": ["A"], "year": 2020, "summary": "..."},
"arxiv:2": {"title": "Paper B", "authors": ["B"], "year": 2020, "summary": "..."},
"arxiv:3": {"title": "Paper C", "authors": ["C"], "year": 2021, "summary": "..."},
"arxiv:4": {"title": "Paper D", "authors": ["D"], "year": 2022, "summary": "..."},
"arxiv:5": {"title": "Paper E", "authors": ["E"], "year": "2022", "summary": "..."},
}
result = run(sample_papers)
expected = {"2020": 2, "2021": 1, "2022": 2}
assert result == expected, f"Expected {expected}, got {result}"
if __name__ == "__main__":
test_papers_per_year_count()
print("Test passed!")
# sort-papers-by-year
---
name: sort-papers-by-year
description: Sorts a dictionary of papers by their publication year in descending order.
version: 1.0.0
verified: true
---
import json
def run(papers):
"""
Sorts the papers dictionary by year in descending order (newest to oldest).
Returns a list of paper dictionaries sorted by year.
"""
# Convert dict to list of dicts and include the id for reference
paper_list = []
for paper_id, info in papers.items():
item = info.copy()
item['id'] = paper_id
paper_list.append(item)
# Sort by year (descending). Handle cases where year might be missing or non-integer.
def sort_key(x):
try:
return int(x.get('year', 0))
except (ValueError, TypeError):
return 0
sorted_list = sorted(paper_list, key=sort_key, reverse=True)
return sorted_list
if __name__ == "__main__":
# Test case
test_papers = {
"arxiv:1": {"title": "Old Paper", "authors": ["A"], "year": 2010, "summary": "..."},
"arxiv:2": {"title": "New Paper", "authors": ["B"], "year": 2023, "summary": "..."},
"arxiv:3": {"title": "Mid Paper", "authors": ["C"], "year": 2015, "summary": "..."}
}
result = run(test_papers)
assert result[0]['year'] == 2023
assert result[1]['year'] == 2015
assert result[2]['year'] == 2010
assert len(result) == 3
print("Test passed!")
cost: $0.00127
สรุป
| ส่วน | สิ่งที่เห็น |
|---|---|
| A: composition | requires + เวอร์ชัน → ลำดับแบบ topological · หยุดก่อนทำงานเมื่อ skill หาย หรือเวอร์ชันไม่ตรง · citation-format ใช้ร่วมกันสามตัว |
| A: run | literature-review ไม่มี tool ของตัวเอง แต่ได้ย่อหน้าที่อ้างอิง + รายการ APA จาก skill ย่อย |
| B: learning | ไม่มี skill → เขียนโค้ด + test → ตรวจ → เก็บ · คำถามถัดไปใช้ซ้ำ |
แบบฝึกหัด
- ทำให้กราฟวน: ให้
citation-formatต้องใช้literature-review@1แล้วดูข้อความ error - เพิ่ม
meeting-notes1.0.0 เข้าคลัง แล้วคลี่weekly-reportอีกครั้ง - ส่วน B: เขียน test ของเราเอง (ไม่ใช่ของ model) ที่เทียบกับคำตอบที่รู้ เช่น ปี 2023 ต้องได้ 6 เรื่อง แล้วใช้ตรวจก่อนเก็บ
ถัดไป — Lab 4: skill ชุดเดิมกับ framework จริง — deepagents