Lab 1 — Supervisor กับ worker เขียนเอง
Lab walkthrough · EP15 Multi-Agent Systems: When and How Agents Work Together
หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด
▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP15 Multi-Agent Systems: When and How Agents Work Together
model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้
คลิปทฤษฎีบอกว่าแบบที่ง่ายที่สุดของทีม agent คือ supervisor ตัวกลางที่เลือกว่าใครทำต่อ แล้วรวมผล (§24.2.1) Lab นี้เราจะสร้างทีมวิจัยสามตัว — researcher, writer, reviewer — กับ supervisor หนึ่งตัว ให้เขียนรายงานสั้นจาก paper
สิ่งที่จะได้ทำ
- ตัวนับ token แยกตาม agent (วัด “token รวมทุก agent” ตามตาราง 24.3)
AgentMessageข้อความที่มี performative:request·inform·failure(§24.4)- worker สามตัว แต่ละตัวได้ context เฉพาะส่วนของตัวเอง (§24.4.3)
- ทดสอบ reviewer ก่อนไว้ใจมัน
- supervisor ที่ตอบเป็น JSON ว่าใครทำต่อ และลูปที่มีเพดานรอบ
- รันทีม โดย tool ค้นหาล่มหนึ่งครั้ง แล้วเทียบ token กับ agent ตัวเดียว
ข้อมูล paper เป็นข้อมูลจำลองเพื่อการสอน (เลข arXiv ชื่อ ผู้เขียน และปีเป็นของจริง บทสรุปบรรทัดเดียวเขียนขึ้นสำหรับ lab) การล่มของ tool ก็จำลอง ส่วน output ของ model มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §24.2.1, §24.4, §24.5.1, §24.8.6 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึงครึ่งเซ็นต์ดอลลาร์) |
| Packages | openai, python-dotenv, pydantic (ติดตั้งใน 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 "pydantic>=2"import json, os, re
from collections import Counter
from typing import Literal
from pydantic import BaseModel
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 และ tool ที่ล่มได้
คลัง paper จำลองแปดเรื่องกับ tool สองตัวจาก EP14: search_papers(query) และ get_paper(paper_id) เพิ่ม OUTAGE ไว้จำลองว่า tool ไม่ตอบ (TimeoutError) — เพื่อดูว่าทีมรับมือกับความล้มเหลวอย่างไร (หน้าที่ข้อสี่ของ supervisor, §24.2.1)
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 = [
{"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"]}}},
{"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"]}}},
]OUTAGE = {"search_papers": 0} # how many calls to each tool will time out (simulated)
def run_tool(name, args):
if OUTAGE.get(name, 0) > 0:
OUTAGE[name] -= 1
raise TimeoutError(f"{name} did not answer in 10 s")
return FUNCS[name](**args)Model: google/gemma-4-26b-a4b-it — model เดียวกับทุก EP ล็อก provider เป็น Makora · lab นี้ต้องการ tool calling (researcher) และ structured output (supervisor กับ reviewer ตอบเป็น JSON ตาม schema) · ราคา 0.09 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.28 ต่อล้าน token ขาออก — ทีมทำงานหนึ่งรอบราว 0.05 เซ็นต์ · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-27: 3 ใน 3 ครั้งได้ 429)
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}TOKENS = Counter() # tokens used, per agent
def llm(agent, messages, **kw):
r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, messages=messages, **kw)
TOKENS[agent] += r.usage.total_tokens
COST["chat"] += r.usage.cost
return r.choices[0].message2. ข้อความระหว่าง agent
ย่อจาก Listing 24.3 ของตำรา: ผู้ส่ง ผู้รับ performative และเนื้อความ เราใช้แค่สามแบบจากแปดแบบในตาราง 24.1:
| performative | ความหมาย | ใครส่ง |
|---|---|---|
request |
ขอให้ทำ | supervisor → worker |
inform |
แจ้งผล | worker → supervisor |
failure |
ทำไม่สำเร็จ | worker → supervisor |
# ✏️ TODO 1 (▶ วิดีโอ 3:29): กำหนดให้ performative รับได้แค่สามแบบ
class AgentMessage(BaseModel):
sender: str
receiver: str
performative: ___
content: str
def to_prompt(self):
return f"[MESSAGE from {self.sender}]\nType: {self.performative}\nContent: {self.content}"class AgentMessage(BaseModel):
sender: str
receiver: str
performative: Literal["request", "inform", "failure"]
content: str
def to_prompt(self):
return f"[MESSAGE from {self.sender}]\nType: {self.performative}\nContent: {self.content}"3. worker สามตัว
| worker | tool | ได้เห็นอะไร |
|---|---|---|
| researcher | search_papers, get_paper |
แค่คำสั่งจาก supervisor |
| writer | ไม่มี | คำสั่ง + โน้ตของ researcher (+ ข้อติของ reviewer ถ้ามี) |
| reviewer | ไม่มี | โน้ต + ประโยคของร่าง |
แต่ละตัวได้ เฉพาะ context ที่ต้องใช้ ไม่ใช่ประวัติทั้งหมด (หน้าที่ context management ของ supervisor, §24.2.1, §24.4.3) ทุกตัวเขียนและอ่านงานผ่าน state — dict กลางของทีม
def tool_loop(agent, system, task, max_steps=8):
msgs = [{"role": "system", "content": system}, {"role": "user", "content": task}]
for _ in range(max_steps):
msg = llm(agent, msgs, tools=SPECS)
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" 🔧 {agent}: {call.function.name}({args})")
msgs.append({"role": "tool", "tool_call_id": call.id, "content": run_tool(call.function.name, args)})
return NoneRESEARCHER = ("You are a researcher. Use the tools to find papers for the request and open each one with get_paper. "
"Reply with notes only: one bullet per paper, '- [id] title (year): one-sentence finding'. "
"Use only what get_paper returned.")
# ✏️ TODO 2 (▶ วิดีโอ 4:52): ถ้า tool ล่ม ให้ตอบเป็นข้อความ failure แทนที่จะล้มทั้งระบบ
def researcher(req, state):
try:
notes = tool_loop("researcher", RESEARCHER, req.to_prompt())
except TimeoutError as e:
return AgentMessage(sender="researcher", receiver="supervisor", performative=___,
content=f"search failed: {e}")
state["notes"] = notes
return AgentMessage(sender="researcher", receiver="supervisor", performative="inform", content=notes)RESEARCHER = ("You are a researcher. Use the tools to find papers for the request and open each one with get_paper. "
"Reply with notes only: one bullet per paper, '- [id] title (year): one-sentence finding'. "
"Use only what get_paper returned.")
def researcher(req, state):
try:
notes = tool_loop("researcher", RESEARCHER, req.to_prompt())
except TimeoutError as e:
return AgentMessage(sender="researcher", receiver="supervisor", performative="failure",
content=f"search failed: {e}")
state["notes"] = notes
return AgentMessage(sender="researcher", receiver="supervisor", performative="inform", content=notes)WRITER = ("You are a writer. Write what the request asks using ONLY the notes you are given. "
"Every sentence, the first one too, must end with the id of the paper it comes from, like [2310.08560]. "
"No other facts.")
def writer(req, state):
prompt = req.to_prompt() + f"\n\nNotes:\n{state['notes']}"
if state.get("feedback"):
prompt += f"\n\nReviewer feedback:\n{state['feedback']}"
draft = llm("writer", [{"role": "system", "content": WRITER}, {"role": "user", "content": prompt}]).content
state["draft"] = draft
return AgentMessage(sender="writer", receiver="supervisor", performative="inform", content=draft)4. ทดสอบ reviewer ก่อนไว้ใจมัน
reviewer คือเหตุผลเรื่อง robustness ของทีม (§24.1) — แต่ถ้ามันปล่อยผ่านทุกอย่าง ทีมก็ไม่ได้ทนทานขึ้น ทดสอบด้วยร่างที่เรา ฝังจุดผิดไว้เอง: ประโยคที่สามไม่มีการอ้างอิง และโน้ตก็ไม่ได้พูดถึง
TEST_NOTES = ("- [2310.08560] MemGPT (2023): pages facts between a small main context and a large external store.\n"
"- [2504.19413] Mem0 (2025): extracts facts and adds, updates or deletes them in a long-term store.")
BAD_DRAFT = ("MemGPT pages facts between main context and an external store [2310.08560]. "
"Mem0 extracts facts into a long-term store [2504.19413]. "
"Most production agents today use MemGPT.")VERDICT = {"type": "object", "properties": {"verdict": {"type": "string", "enum": ["APPROVED", "NEEDS_REVISION"]}},
"required": ["verdict"], "additionalProperties": False}
def review_whole(notes, draft):
r = llm("test", [{"role": "system", "content": "You are a strict reviewer. Approve only if every sentence "
"cites an id from the notes and says only what the notes say."},
{"role": "user", "content": f"Notes:\n{notes}\n\nDraft:\n{draft}"}],
response_format={"type": "json_schema", "json_schema": {"name": "verdict", "strict": True, "schema": VERDICT}})
return json.loads(r.content)["verdict"]
for _ in range(3):
print(review_whole(TEST_NOTES, BAD_DRAFT))APPROVED
APPROVED
APPROVED
REVIEWER = ("You are a strict reviewer. You get the notes and the draft's sentences, numbered. "
"For each sentence, answer whether the notes support it. A sentence with no [id] is not supported.")
def review_sentences(notes, draft, agent="reviewer"):
sents = [s for s in re.split(r"(?<=[.!?])\s+", draft.strip()) if s]
numbered = "\n".join(f"{i}. {s}" for i, s in enumerate(sents, 1))
# ✏️ TODO 3 (▶ วิดีโอ 7:04): คืนรายการประโยคที่ reviewer บอกว่าโน้ตไม่รองรับ
schema = {"type": "object", "properties": {"checks": {"type": "array", "minItems": len(sents), "maxItems": len(sents),
"items": {"type": "object", "properties": {"n": {"type": "integer"}, "supported": {"type": "boolean"}},
"required": ["n", "supported"], "additionalProperties": False}}},
"required": ["checks"], "additionalProperties": False}
r = llm(agent, [{"role": "system", "content": REVIEWER},
{"role": "user", "content": f"Notes:\n{notes}\n\nSentences:\n{numbered}"}],
response_format={"type": "json_schema", "json_schema": {"name": "review", "strict": True, "schema": schema}})
checks = json.loads(r.content)["checks"]
return [___ for c in checks if ___]REVIEWER = ("You are a strict reviewer. You get the notes and the draft's sentences, numbered. "
"For each sentence, answer whether the notes support it. A sentence with no [id] is not supported.")
def review_sentences(notes, draft, agent="reviewer"):
sents = [s for s in re.split(r"(?<=[.!?])\s+", draft.strip()) if s]
numbered = "\n".join(f"{i}. {s}" for i, s in enumerate(sents, 1))
schema = {"type": "object", "properties": {"checks": {"type": "array", "minItems": len(sents), "maxItems": len(sents),
"items": {"type": "object", "properties": {"n": {"type": "integer"}, "supported": {"type": "boolean"}},
"required": ["n", "supported"], "additionalProperties": False}}},
"required": ["checks"], "additionalProperties": False}
r = llm(agent, [{"role": "system", "content": REVIEWER},
{"role": "user", "content": f"Notes:\n{notes}\n\nSentences:\n{numbered}"}],
response_format={"type": "json_schema", "json_schema": {"name": "review", "strict": True, "schema": schema}})
checks = json.loads(r.content)["checks"]
return [sents[c["n"] - 1] for c in checks if not c["supported"]]for _ in range(3):
print(review_sentences(TEST_NOTES, BAD_DRAFT, agent="test"))['Most production agents today use MemGPT.']
['Most production agents today use MemGPT.']
['Most production agents today use MemGPT.']
def reviewer(req, state):
bad = review_sentences(state["notes"], state["draft"])
state["verdict"] = "NEEDS_REVISION" if bad else "APPROVED"
state["feedback"] = ("Unsupported sentences:\n" + "\n".join(bad)) if bad else ""
return AgentMessage(sender="reviewer", receiver="supervisor", performative="inform",
content=f"{state['verdict']}\n{state['feedback']}".strip())
WORKERS = {"researcher": researcher, "writer": writer, "reviewer": reviewer}5. Supervisor
supervisor ไม่ได้ทำงานเอง มันเห็น สถานะ ของงาน + ข้อความล่าสุด แล้วตอบเป็น JSON ว่าใครทำต่อ (next) พร้อมคำสั่ง (instruction) เหมือน supervisor_node + route ในตัวอย่าง LangGraph ของตำรา: ทุก worker กลับมาที่ supervisor เสมอ และจบด้วย FINISH
SUPERVISOR = ("You are the supervisor of a research team. Workers: researcher (finds and reads papers, has tools), "
"writer (writes from the researcher's notes), reviewer (checks the draft against the notes). "
"Pick who acts next and give them a short instruction. Answer FINISH only after the reviewer APPROVED "
"the draft. If a worker reports a failure, decide whether to retry.")
# ✏️ TODO 4 (▶ วิดีโอ 8:44): จำกัดให้ supervisor เลือกได้แค่ worker สามตัว หรือ FINISH
ROUTE = {"type": "object", "properties": {
"next": {"type": "string", "enum": ___},
"instruction": {"type": "string"}},
"required": ["next", "instruction"], "additionalProperties": False}SUPERVISOR = ("You are the supervisor of a research team. Workers: researcher (finds and reads papers, has tools), "
"writer (writes from the researcher's notes), reviewer (checks the draft against the notes). "
"Pick who acts next and give them a short instruction. Answer FINISH only after the reviewer APPROVED "
"the draft. If a worker reports a failure, decide whether to retry.")
ROUTE = {"type": "object", "properties": {
"next": {"type": "string", "enum": ["researcher", "writer", "reviewer", "FINISH"]},
"instruction": {"type": "string"}},
"required": ["next", "instruction"], "additionalProperties": False}def status(state):
return (f"notes: {'yes' if state.get('notes') else 'not yet'}\n"
f"draft: {'yes' if state.get('draft') else 'not yet'}\n"
f"review: {state.get('verdict', 'not yet')}")def run_team(task, max_rounds=10):
state, inbox = {}, None
for rnd in range(1, max_rounds + 1):
user = f"Task: {task}\n\nStatus:\n{status(state)}"
if inbox:
user += f"\n\nLast message:\n{inbox.to_prompt()}"
r = llm("supervisor", [{"role": "system", "content": SUPERVISOR}, {"role": "user", "content": user}],
response_format={"type": "json_schema", "json_schema": {"name": "route", "strict": True, "schema": ROUTE}})
route = json.loads(r.content)
# ✏️ TODO 5 (▶ วิดีโอ 9:31): ส่ง request ให้ worker ที่ supervisor เลือก แล้วเก็บคำตอบไว้ให้รอบหน้า
if route["next"] == "FINISH":
print(f"{rnd}. supervisor → FINISH")
return state
req = AgentMessage(sender="supervisor", receiver=route["next"], performative="request",
content=route["instruction"])
print(f"{rnd}. supervisor → {req.receiver} [request] {req.content[:80]}")
inbox = ___
print(f" {inbox.sender} → supervisor [{inbox.performative}] {inbox.content[:80]!r}")
print("stopped: max rounds")
return statedef run_team(task, max_rounds=10):
state, inbox = {}, None
for rnd in range(1, max_rounds + 1):
user = f"Task: {task}\n\nStatus:\n{status(state)}"
if inbox:
user += f"\n\nLast message:\n{inbox.to_prompt()}"
r = llm("supervisor", [{"role": "system", "content": SUPERVISOR}, {"role": "user", "content": user}],
response_format={"type": "json_schema", "json_schema": {"name": "route", "strict": True, "schema": ROUTE}})
route = json.loads(r.content)
if route["next"] == "FINISH":
print(f"{rnd}. supervisor → FINISH")
return state
req = AgentMessage(sender="supervisor", receiver=route["next"], performative="request",
content=route["instruction"])
print(f"{rnd}. supervisor → {req.receiver} [request] {req.content[:80]}")
inbox = WORKERS[req.receiver](req, state)
print(f" {inbox.sender} → supervisor [{inbox.performative}] {inbox.content[:80]!r}")
print("stopped: max rounds")
return state6. รันทีม โดย tool ค้นหาล่มหนึ่งครั้ง
งาน: รายงานสองย่อหน้าเรื่อง agent เก็บและจัดการความจำระยะยาวอย่างไร อ้าง paper สามเรื่อง ตั้ง OUTAGE["search_papers"] = 1 — การค้นครั้งแรกจะไม่ตอบ
TASK = "Write a 2-paragraph report on how LLM agents store and manage long-term memory, citing 3 papers."
TOKENS.clear()
OUTAGE["search_papers"] = 1
state = run_team(TASK)1. supervisor → researcher [request] Find and summarize 3 key papers regarding long-term memory management in LLM age
🔧 researcher: search_papers({'query': 'long-term memory management LLM agents vector database RAG hierarchical memory'})
researcher → supervisor [failure] 'search failed: search_papers did not answer in 10 s'
2. supervisor → researcher [request] Retry the search for papers focusing on 'LLM agent long-term memory architecture
🔧 researcher: search_papers({'query': 'LLM agent long-term memory architectures'})
🔧 researcher: search_papers({'query': 'vector databases for LLM memory'})
🔧 researcher: get_paper({'paper_id': '2504.19413'})
🔧 researcher: get_paper({'paper_id': '2502.12110'})
🔧 researcher: get_paper({'paper_id': '2310.08560'})
🔧 researcher: get_paper({'paper_id': '2304.03442'})
researcher → supervisor [inform] '- [2504.19413] Mem0: Building Production-Ready AI Agents with Scalable Long-Term'
3. supervisor → writer [request] Write a 2-paragraph report on how LLM agents store and manage long-term memory u
writer → supervisor [inform] 'LLM agents utilize various architectural approaches to manage long-term memory. '
4. supervisor → reviewer [request] Check the draft against the researcher's notes to ensure it accurately reflects
reviewer → supervisor [inform] 'NEEDS_REVISION\nUnsupported sentences:\nLLM agents utilize various architectural a'
5. supervisor → writer [request] Rewrite the report to address the reviewer's feedback. Ensure every sentence is
writer → supervisor [inform] 'Mem0 proposes a system where an LLM extracts, adds, updates, or deletes facts fr'
6. supervisor → reviewer [request] Check the writer's draft against the researcher's notes to ensure all 3 required
reviewer → supervisor [inform] 'APPROVED'
7. supervisor → FINISH
print(state["draft"])
print("\nreview:", state["verdict"])Mem0 proposes a system where an LLM extracts, adds, updates, or deletes facts from conversations to maintain a scalable long-term store [2504.19413]. A-MEM introduces a memory architecture where each memory is a linked note with keywords and tags that dynamically update links to existing notes [2502.12110]. MemGPT presents a memory management approach where the LLM pages facts between a limited main context and a large external store, mimicking an operating system's virtual memory [2310.08560]. Generative Agents describes an architecture where agents maintain a memory stream and use recency, importance, and relevance to score and reflect on memories [2304.03442].
review: APPROVED
team = dict(TOKENS)
for agent, n in sorted(team.items(), key=lambda kv: -kv[1]):
print(f"{agent:<11} {n:>6,} tokens")
print(f"{'team total':<11} {sum(team.values()):>6,} tokens")researcher 3,121 tokens
supervisor 2,087 tokens
writer 1,143 tokens
reviewer 1,114 tokens
team total 7,465 tokens
7. เทียบกับ agent ตัวเดียว
งานเดียวกัน ให้ agent ตัวเดียวที่มี tool ทั้งสองตัวทำ (ไม่มี tool ล่ม) แล้วเทียบ token
TOKENS.clear()
answer = tool_loop("single", "You are a research assistant. Use the tools, open each paper with get_paper, "
"and end every sentence with the id of the paper it comes from.", TASK)
print(answer)
print(f"\nsingle agent: {TOKENS['single']:,} tokens · team: {sum(team.values()):,} tokens") 🔧 single: search_papers({'query': 'LLM agents long-term memory architecture'})
🔧 single: get_paper({'paper_id': '2310.08560'})
🔧 single: get_paper({'paper_id': '2504.19413'})
🔧 single: get_paper({'paper_id': '2304.03442'})
LLM agents manage long-term memory through various architectural approaches designed to overcome the limitations of fixed context windows. One prominent method involves treating the LLM as an operating system, where the agent manages memory by paging facts between a limited main context and a much larger external storage system, similar to virtual memory management (2310.08560). Another approach focuses on a structured memory stream where agents record observations and then score these memories based on criteria such as recency, importance, and relevance to facilitate retrieval (2304.03442). These agents can further refine their knowledge by writing reflections to synthesize complex information from their memory streams (2304.03442).
Modern frameworks have also introduced more dynamic and scalable ways to maintain agentic knowledge. For instance, some systems allow agents to actively manage their long-term stores by extracting specific facts from conversations and autonomously deciding whether to add, update, or delete information (2504.19413). This ability to perform CRUD (Create, Read, Update, Delete) operations on their own memory ensures that the agent's knowledge remains accurate and evolves over time (2504.19413). By combining these retrieval and management strategies, agents can maintain a coherent and persistent identity across extended interactions (2304.03442).
single agent: 2,889 tokens · team: 7,465 tokens
สรุป
| ชิ้นส่วน | ในโค้ด | ตำรา |
|---|---|---|
| supervisor | run_team + ROUTE (เลือก next ทุกรอบ, จบด้วย FINISH) |
§24.2.1 |
| ข้อความ | AgentMessage กับ request · inform · failure |
§24.4.1–24.4.2 |
| ส่ง context เฉพาะส่วน | worker แต่ละตัวเห็นแค่ของตัวเอง, supervisor เห็นแค่ status |
§24.4.3 |
| จัดการความล้มเหลว | tool ล่ม → failure → supervisor สั่งลองใหม่ |
§24.2.1 |
| ผู้ตรวจ | reviewer ทีละประโยค (แบบทั้งก้อนปล่อยผ่านร่างที่ผิด) | §24.1 robustness |
| ต้นทุน | TOKENS แยกตาม agent — ทีมแพงกว่า agent ตัวเดียวหลายเท่า |
ตาราง 24.3, §24.8.1 |
แบบฝึกหัด
- ตั้ง
OUTAGE["search_papers"] = 20แล้วรันทีม — supervisor ทำอย่างไร และอะไรหยุดลูป - เพิ่ม performative
queryให้ writer ถาม researcher ได้เมื่อโน้ตไม่พอ (ต้องแก้AgentMessageและrun_teamตรงไหน) - ให้ supervisor เห็นโน้ตทั้งหมดแทน
statusแล้วดูว่า token ของ supervisor เปลี่ยนไปเท่าไร
ถัดไป — Lab 2: กลไกประสานงาน: กระดานกลาง (blackboard) กราฟงานที่รันพร้อมกัน และการประมูลงาน