Skip to main content

Lab 4 — ทีมเดิมด้วย LangGraph: supervisor graph และ swarm

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 ที่คุณรันเองจึงอาจต่างจากหน้านี้

สร้างทีมของ Lab 1 ใหม่ด้วย LangGraph แล้วเทียบกับโค้ดที่เราเขียนเอง

สิ่งที่จะได้ทำ

  1. Supervisor graph: worker เป็น node, supervisor เลือกคนต่อไปด้วย Command(goto=...) (§24.2.1 — ตำรายกตัวอย่าง LangGraph)
  2. Trace: ดูทุกขั้นด้วย stream(stream_mode="updates") และหยุดลูปด้วย recursion_limit
  3. Swarm: ไม่มี supervisor — agent ที่ถืองานส่งต่อเองด้วย Command (§24.2.4)
  4. เทียบ token ระหว่างสองแบบ

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

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

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึงครึ่งเซ็นต์ดอลลาร์)
Packages langgraph, langchain, langchain-openai, python-dotenv (ล็อกเวอร์ชันไว้ใน cell ถัดไป)

ใส่ API key

  • Colab: ไอคอน 🔑 Secrets → ชื่อ OPENROUTER_API_KEY → เปิด Notebook access
  • เครื่องตัวเอง: สร้างไฟล์ .env ในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัด OPENROUTER_API_KEY=sk-or-...

⚠️ อย่าใส่ key ลงในโค้ดโดยตรง และอย่าแชร์ไฟล์ .env

%pip install -q "langgraph==1.2.21" "langchain==1.5.0" "langchain-core==1.8.0" "langchain-openai==1.7.4" python-dotenv
import json, os, re
from collections import Counter
from contextlib import contextmanager
from typing import TypedDict
from langchain.agents import create_agent
from langchain_core.callbacks import get_usage_metadata_callback
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.errors import GraphRecursionError
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command
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"},
}
OUTAGE = {"search_papers": 0}   # how many calls to each tool will time out (simulated)

@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."""
    if OUTAGE["search_papers"] > 0:
        OUTAGE["search_papers"] -= 1
        raise TimeoutError("search_papers did not answer in 10 s")
    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]})

Model: google/gemma-4-26b-a4b-it ล็อก provider เป็น Makora — วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1

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}})

TOKENS = Counter()   # tokens used, per agent

@contextmanager
def counted(agent):
    with get_usage_metadata_callback() as cb:
        yield
    TOKENS[agent] += sum(u["total_tokens"] for u in cb.usage_metadata.values())

1. State และ worker เป็น node

Lab 1 (เขียนเอง) LangGraph
state = {} + AgentMessage ใน inbox TeamState — state ที่ทุก node อ่านและคืนค่าที่เปลี่ยน
ฟังก์ชัน worker คืน AgentMessage node คืน dict ที่จะ รวมเข้า state
tool_loop เขียนเอง create_agent(model, tools, system_prompt)
class TeamState(TypedDict, total=False):
    task: str
    instruction: str   # the supervisor's request to the next worker
    notes: str
    draft: str
    verdict: str
    feedback: str
    last: str          # the last worker's reply: "<sender> [<performative>] <content>"
# ✏️ TODO 1 (▶ วิดีโอ 2:25): สร้าง agent ที่ใช้สอง tool ค้นหาและเปิด paper
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.")
research_agent = create_agent(model, tools=___, system_prompt=RESEARCHER)

def researcher(state):
    with counted("researcher"):
        try:
            out = research_agent.invoke({"messages": [{"role": "user", "content": state.get("instruction") or state["task"]}]})
        except TimeoutError as e:
            return {"last": f"researcher [failure] search failed: {e}"}
    used = [c["name"] for m in out["messages"] for c in (getattr(m, "tool_calls", None) or [])]
    print("    🔧 researcher:", used)
    notes = out["messages"][-1].content
    return {"notes": notes, "last": f"researcher [inform] {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.")
research_agent = create_agent(model, tools=[search_papers, get_paper], system_prompt=RESEARCHER)

def researcher(state):
    with counted("researcher"):
        try:
            out = research_agent.invoke({"messages": [{"role": "user", "content": state.get("instruction") or state["task"]}]})
        except TimeoutError as e:
            return {"last": f"researcher [failure] search failed: {e}"}
    used = [c["name"] for m in out["messages"] for c in (getattr(m, "tool_calls", None) or [])]
    print("    🔧 researcher:", used)
    notes = out["messages"][-1].content
    return {"notes": notes, "last": f"researcher [inform] {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(state):
    prompt = f"{state.get('instruction') or state['task']}\n\nNotes:\n{state['notes']}"
    if state.get("feedback"):
        prompt += f"\n\nReviewer feedback:\n{state['feedback']}"
    with counted("writer"):
        draft = model.invoke([("system", WRITER), ("user", prompt)]).content
    return {"draft": draft, "last": f"writer [inform] {draft}"}

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):
    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 = {"title": "review", "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}
    checks = model.with_structured_output(schema, method="json_schema", strict=True).invoke(
        [("system", REVIEWER), ("user", f"Notes:\n{notes}\n\nSentences:\n{numbered}")])["checks"]
    return [sents[c["n"] - 1] for c in checks if not c["supported"]]

def reviewer(state):
    with counted("reviewer"):
        bad = review_sentences(state["notes"], state["draft"])
    verdict = "NEEDS_REVISION" if bad else "APPROVED"
    feedback = ("Unsupported sentences:\n" + "\n".join(bad)) if bad else ""
    return {"verdict": verdict, "feedback": feedback, "last": f"reviewer [inform] {verdict} {feedback}".strip()}

2. Supervisor graph

START → supervisor ─Command(goto)→ researcher ─┐
            ↑      ─Command(goto)→ writer     ─┤
            │      ─Command(goto)→ reviewer   ─┤
            └──────────────────────────────────┘   supervisor → END เมื่อ FINISH

Command(goto=..., update=...) = เลือก node ถัดไป และ เขียน state ในคำสั่งเดียว

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 = {"title": "route", "type": "object", "properties": {
             "next": {"type": "string", "enum": ["researcher", "writer", "reviewer", "FINISH"]},
             "instruction": {"type": "string"}},
         "required": ["next", "instruction"], "additionalProperties": False}
router = model.with_structured_output(ROUTE, method="json_schema", strict=True)

# ✏️ TODO 2 (▶ วิดีโอ 3:51): ไปที่ worker ที่เลือก หรือไปที่ END ถ้าตอบ FINISH

def supervisor(state):
    status = (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')}")
    user = f"Task: {state['task']}\n\nStatus:\n{status}"
    if state.get("last"):
        user += f"\n\nLast message:\n{state['last']}"
    with counted("supervisor"):
        route = router.invoke([("system", SUPERVISOR), ("user", user)])
    return Command(goto=___,
                   update={"instruction": route["instruction"]})
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 = {"title": "route", "type": "object", "properties": {
             "next": {"type": "string", "enum": ["researcher", "writer", "reviewer", "FINISH"]},
             "instruction": {"type": "string"}},
         "required": ["next", "instruction"], "additionalProperties": False}
router = model.with_structured_output(ROUTE, method="json_schema", strict=True)

def supervisor(state):
    status = (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')}")
    user = f"Task: {state['task']}\n\nStatus:\n{status}"
    if state.get("last"):
        user += f"\n\nLast message:\n{state['last']}"
    with counted("supervisor"):
        route = router.invoke([("system", SUPERVISOR), ("user", user)])
    return Command(goto=END if route["next"] == "FINISH" else route["next"],
                   update={"instruction": route["instruction"]})
# ✏️ TODO 3 (▶ วิดีโอ 4:10): ให้ worker ทุกตัวมีเส้นกลับมาหา supervisor
builder = StateGraph(TeamState)
builder.add_node("supervisor", supervisor)
for name, node in [("researcher", researcher), ("writer", writer), ("reviewer", reviewer)]:
    builder.add_node(name, node)
    ___
builder.add_edge(START, "supervisor")
team = builder.compile()
builder = StateGraph(TeamState)
builder.add_node("supervisor", supervisor)
for name, node in [("researcher", researcher), ("writer", writer), ("reviewer", reviewer)]:
    builder.add_node(name, node)
    builder.add_edge(name, "supervisor")
builder.add_edge(START, "supervisor")
team = builder.compile()

3. Trace: ดูทุกขั้นด้วย stream

  • stream(..., stream_mode="updates") คืน ค่าที่ node เพิ่งเปลี่ยน ทีละขั้น — เห็นเส้นทางของงานทั้งหมด (การวัดระดับ interaction ในตาราง 24.3)
  • recursion_limit = เพดานจำนวนขั้น แทน max_rounds ของ Lab 1
# ✏️ TODO 4 (▶ วิดีโอ 4:45): ขอค่าที่ node เพิ่งเปลี่ยนทีละขั้น
def trace(graph, task, limit=25):
    TOKENS.clear()
    OUTAGE["search_papers"] = 1
    state = {"task": task}
    for step in graph.stream(state, {"recursion_limit": limit}, stream_mode=___):
        for node, update in step.items():
            update = update or {}
            state.update(update)
            if node == "supervisor":
                print(f"supervisor: {update.get('instruction', '')[:90]}")
            else:
                print(f"   {update.get('last', '')[:90]!r}")
    return state
def trace(graph, task, limit=25):
    TOKENS.clear()
    OUTAGE["search_papers"] = 1
    state = {"task": task}
    for step in graph.stream(state, {"recursion_limit": limit}, stream_mode="updates"):
        for node, update in step.items():
            update = update or {}
            state.update(update)
            if node == "supervisor":
                print(f"supervisor: {update.get('instruction', '')[:90]}")
            else:
                print(f"   {update.get('last', '')[:90]!r}")
    return state
TASK = "Write a 2-paragraph report on how LLM agents store and manage long-term memory, citing 3 papers."
state = trace(team, TASK)
supervisor: Find and summarize 3 key papers regarding long-term memory management in LLM agents (e.g.,
   'researcher [failure] search failed: search_papers did not answer in 10 s'
supervisor: Retry the search for papers specifically focusing on 'LLM agent long-term memory architect
    🔧 researcher: ['search_papers', 'get_paper', 'get_paper', 'get_paper', 'get_paper']
   'researcher [inform] - [2504.19413] Mem0: Building Production-Ready AI Agents with Scalable'
supervisor: Write a 2-paragraph report on how LLM agents store and manage long-term memory using the p
   'writer [inform] LLM agents utilize various architectures to manage long-term information. '
supervisor: Check the draft against the notes to ensure it accurately reflects the research and includ
   'reviewer [inform] NEEDS_REVISION Unsupported sentences:\nLLM agents utilize various archite'
supervisor: Rewrite the report to address the reviewer's feedback. Ensure the sentences 'LLM agents ut
   'writer [inform] LLM agents manage long-term information by extracting facts from conversat'
supervisor: Check if the draft accurately reflects the notes and includes exactly 3 citations as reque
   'reviewer [inform] APPROVED'
supervisor: The report is approved. Task complete.
print(state["draft"])
print("\nreview:", state["verdict"])
supervised = dict(TOKENS)
for agent, n in sorted(supervised.items(), key=lambda kv: -kv[1]):
    print(f"{agent:<11} {n:>6,} tokens")
print(f"{'team total':<11} {sum(supervised.values()):>6,} tokens")
LLM agents manage long-term information by extracting facts from conversations to add, update, or delete them in a scalable long-term store [2504.19413]. One method uses a memory stream where observations are scored by recency, importance, and relevance, followed by a reflection process [2304.03442].

Memory can also be implemented as a system of linked notes with keywords and tags where new entries update links to existing ones [2502.12110]. Additionally, memory is managed by paging facts between a limited main context and a large external store, mimicking an operating system's virtual memory [2310.08560].

review: APPROVED
researcher   2,243 tokens
supervisor   2,092 tokens
writer       1,083 tokens
reviewer     1,056 tokens
team total   6,474 tokens
try:
    trace(team, TASK, limit=4)
except GraphRecursionError as e:
    print("⛔", str(e).splitlines()[0])
supervisor: Find and summarize 3 key papers regarding long-term memory management in LLM agents (e.g.,
   'researcher [failure] search failed: search_papers did not answer in 10 s'
supervisor: Retry the search for papers focusing on 'LLM agent long-term memory architectures', 'RAG f
    🔧 researcher: ['search_papers', 'get_paper', 'get_paper', 'get_paper', 'get_paper']
   'researcher [inform] - [2504.19413] Mem0: Building Production-Ready AI Agents with Scalable'
⛔ Recursion limit of 4 reached without hitting a stop condition. You can increase the limit by setting the `recursion_limit` config key.

4. Swarm: ไม่มี supervisor (§24.2.4)

worker ตัวเดิม แต่ แต่ละตัวคืน Command เอง — ตัวที่ถืองานตัดสินใจว่าส่งต่อให้ใคร

  • researcher: ล่ม → ลองใหม่เอง · สำเร็จ → writer
  • writer → reviewer
  • reviewer: ไม่ผ่าน → writer · ผ่าน → END
def researcher_swarm(state):
    update = researcher(state)
    if "[failure]" in update["last"]:
        print("   researcher: failed, I'll retry myself")
        return Command(goto="researcher", update=update)
    return Command(goto="writer", update=update)

def writer_swarm(state):
    return Command(goto="reviewer", update=writer(state))

# ✏️ TODO 5 (▶ วิดีโอ 6:54): ไม่ผ่าน ส่งกลับให้ writer ผ่าน ไปที่ END

def reviewer_swarm(state):
    update = reviewer(state)
    return Command(goto=___, update=update)

builder = StateGraph(TeamState)
builder.add_node("researcher", researcher_swarm)
builder.add_node("writer", writer_swarm)
builder.add_node("reviewer", reviewer_swarm)
builder.add_edge(START, "researcher")
swarm = builder.compile()
def researcher_swarm(state):
    update = researcher(state)
    if "[failure]" in update["last"]:
        print("   researcher: failed, I'll retry myself")
        return Command(goto="researcher", update=update)
    return Command(goto="writer", update=update)

def writer_swarm(state):
    return Command(goto="reviewer", update=writer(state))

def reviewer_swarm(state):
    update = reviewer(state)
    return Command(goto="writer" if update["verdict"] == "NEEDS_REVISION" else END, update=update)

builder = StateGraph(TeamState)
builder.add_node("researcher", researcher_swarm)
builder.add_node("writer", writer_swarm)
builder.add_node("reviewer", reviewer_swarm)
builder.add_edge(START, "researcher")
swarm = builder.compile()
state = trace(swarm, TASK)
print("\nreview:", state["verdict"])
swarmed = dict(TOKENS)
print(f"supervisor graph: {sum(supervised.values()):,} tokens · swarm: {sum(swarmed.values()):,} tokens")
   researcher: failed, I'll retry myself
   'researcher [failure] search failed: search_papers did not answer in 10 s'
    🔧 researcher: ['search_papers', 'get_paper', 'get_paper', 'get_paper']
   'researcher [inform] LLM agents manage long-term memory through various architectural strat'
   'writer [inform] LLM agents manage long-term memory through various architectural strategie'
   'reviewer [inform] APPROVED'

review: APPROVED
supervisor graph: 6,474 tokens · swarm: 4,388 tokens

สรุป

Lab 1 (เขียนเอง) Lab 4 (LangGraph)
state dict + AgentMessage TeamState + node คืนช่องที่เปลี่ยน
tool_loop create_agent
WORKERS[...] + ลูป run_team add_node + Command(goto=...)
max_rounds=10 recursion_limit → GraphRecursionError
print เองทุกขั้น stream(stream_mode="updates")
— swarm: แต่ละตัวคืน Command เอง ไม่มีค่า supervisor แต่กฎตายตัว

ที่ framework ไม่ได้ทำให้: prompt, reviewer ที่ตรวจทีละประโยค, การตัดสินใจว่าทีมคุ้มไหม — ยังเป็นงานของเรา

แบบฝึกหัด

  1. ตั้ง OUTAGE["search_papers"] = 99 แล้วรัน swarm — อะไรหยุดมัน
  2. เพิ่ม checkpointer=InMemorySaver() ตอน compile แล้วใช้ team.get_state_history(...) ดู state ทุกขั้นย้อนหลัง
  3. เพิ่ม node safety_monitor จาก Lab 3 ระหว่าง researcher กับ writer ในกราฟ swarm

ถัดไป — Recap EP15