Skip to main content

Lab 1 — A2A server กับ client เขียนเอง

Lab walkthrough · EP16 A2A Protocol: How Agents Talk Across Systems

หมายเหตุวิธีใช้หน้านี้

หน้านี้คือ notebook เฉลยของ lab นี้ทีละ cell พร้อม output จากการรันจริงตอนอัดคลิป ไว้อ่านทวนก่อนหรือหลังลงมือ cell ที่มี ✏️ TODO แสดงโค้ดแบบใน starter notebook ส่วนเฉลยเต็มอยู่ในกล่อง ดูเฉลย ลองเขียนเองก่อนค่อยเปิด

▶ วิดีโอ · ✏️ Starter ใน Colab · ✅ เฉลยใน Colab · กลับไปหน้า EP16 A2A Protocol: How Agents Talk Across Systems

model ตอบไม่เหมือนเดิมทุกครั้ง output ที่คุณรันเองจึงอาจต่างจากหน้านี้

คลิปทฤษฎีบอกว่า agent ต่างองค์กรคุยกันผ่าน A2A ได้ เพราะมีของสามอย่าง: Agent Card ที่ประกาศความสามารถ, task ที่เดินตามวงจรชีวิต และข้อความที่ประกอบด้วย part (§23.2) Lab นี้เราจะเขียน ResearchAgent ของห้องสมุดมหาวิทยาลัยเป็น A2A server แล้วเขียน client ฝั่งเราที่ส่งงานให้มัน — ตามตัวอย่าง §23.9 ของตำรา

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

  1. โครงข้อมูลของ A2A: Part · Message · TaskStatus · Artifact · Task
  2. Agent Card ที่ /.well-known/agent.json
  3. สมองของ agent: ตัดสินใจว่าจะ ตอบ · ถามกลับ · หรือ ปฏิเสธ
  4. server ด้วย FastAPI: รับ task, ถามสถานะ, ทำงานเบื้องหลัง
  5. client ที่อ่านการ์ด ส่ง task แล้ว poll จนเสร็จ
  6. ลองสามแบบ: งานชัด · งานกำกวม (input-required แล้วตอบกลับบน task id เดิม) · งานนอกขอบเขต (rejected)

server รันอยู่ใน notebook เดียวกัน ผ่าน httpx.ASGITransport — ไม่ต้องเปิด port จึงใช้บน Colab ได้ ชื่อ endpoint ใช้ตามตำรา (REST binding) สเปกรุ่นปัจจุบันเปลี่ยนชื่อไปบ้าง ดูของจริงใน Lab 4

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

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

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key สมัครที่ openrouter.ai → Keys → Create Key แล้วเติมเครดิต (lab นี้ใช้ไม่ถึงหนึ่งในสิบของเซ็นต์ดอลลาร์)
Packages fastapi, httpx, 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 "fastapi>=0.110" "httpx>=0.27" "openai>=1.50" python-dotenv "pydantic>=2"
import asyncio, json, os, uuid
from datetime import datetime, timezone
from typing import Literal
import httpx
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel, Field
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"]

client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5)
COST = {"chat": 0.0}

Model: google/gemma-4-26b-a4b-it — model เดียวกับทุก EP ล็อก provider เป็น Makora · lab นี้ต้องการ structured output: สมองของ agent ตอบเป็น JSON ตาม schema ว่าจะ answer · ask · reject · ราคา 0.09 ดอลลาร์ต่อล้าน token ขาเข้า และ 0.28 ต่อล้าน token ขาออก — รันทั้ง lab ราวสองในร้อยของเซ็นต์ · รุ่น :free ใช้ไม่ได้ (ทดสอบ 2026-11-29: 3 ใน 3 ครั้งได้ 429)

MODEL = "google/gemma-4-26b-a4b-it"
EXTRA = {"reasoning": {"enabled": False},
         "provider": {"order": ["makora"], "allow_fallbacks": False}}

def llm(messages, **kw):
    r = client.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, messages=messages, **kw)
    COST["chat"] += r.usage.cost
    return r.choices[0].message.content

1. โครงข้อมูลของ A2A

ตามโค้ด §23.9 ของตำรา:

ชนิด คืออะไร
Part ชิ้นหนึ่งของข้อความ: text · file · data (ตาราง 23.2)
Message ข้อความหนึ่งข้อความ: ผู้พูด (user / agent) + รายการ part
TaskStatus สถานะตอนนี้ + ข้อความอธิบาย + เวลา
Artifact ผลงานที่ agent ส่งคืน (ก็เป็นรายการ part)
Task งานหนึ่งชิ้น: id · สถานะ · ข้อความทั้งหมด · ผลงาน
class Part(BaseModel):
    type: Literal["text", "file", "data"]
    text: str | None = None
    data: dict | None = None
    mimeType: str | None = None
    uri: str | None = None

class Message(BaseModel):
    role: Literal["user", "agent"]
    parts: list[Part]

# ✏️ TODO 1 (▶ วิดีโอ 2:51): กำหนดสถานะทั้งเจ็ดของ task ใน A2A

State = Literal["submitted", "working", ___, "completed", "failed", ___, "canceled"]

class TaskStatus(BaseModel):
    state: State
    message: str | None = None
    timestamp: str = Field(default_factory=lambda: datetime.now(timezone.utc).isoformat())

class Artifact(BaseModel):
    parts: list[Part]

class Task(BaseModel):
    id: str
    status: TaskStatus
    messages: list[Message] = []
    artifacts: list[Artifact] = []
    history: list[str] = []
class Part(BaseModel):
    type: Literal["text", "file", "data"]
    text: str | None = None
    data: dict | None = None
    mimeType: str | None = None
    uri: str | None = None

class Message(BaseModel):
    role: Literal["user", "agent"]
    parts: list[Part]

State = Literal["submitted", "working", "input-required", "completed", "failed", "rejected", "canceled"]

class TaskStatus(BaseModel):
    state: State
    message: str | None = None
    timestamp: str = Field(default_factory=lambda: datetime.now(timezone.utc).isoformat())

class Artifact(BaseModel):
    parts: list[Part]

class Task(BaseModel):
    id: str
    status: TaskStatus
    messages: list[Message] = []
    artifacts: list[Artifact] = []
    history: list[str] = []

2. Agent Card

การ์ดของ ResearchAgent ย่อจาก §23.2.2 และ §23.9 — ใครอยากรู้ว่า agent ทำอะไรได้ ก็อ่านการ์ดนี้ก่อน skill ในการ์ดคือ งานแบบหนึ่งที่ agent รับทำ (ไม่ใช่ไฟล์ SKILL.md ของ EP14)

AGENT_CARD = {
    "name": "ResearchAgent",
    "description": "The university library's agent. Searches the library's papers and summarizes findings.",
    "url": "http://library-agent",
    "version": "1.0.0",
    "capabilities": {"streaming": False, "pushNotifications": False, "stateTransitionHistory": True},
    "authentication": {"schemes": ["Bearer"]},
    "skills": [{
        "id": "literature-search",
        "name": "Literature Search",
        "description": "Search and summarize the library's papers on a topic.",
        "tags": ["research", "literature", "papers", "RLHF"],
        "examples": ["What does the literature say about RLHF for code generation?"],
        "inputModes": ["text"],
        "outputModes": ["text", "data"],
    }],
}

3. ข้างในของ ResearchAgent

ห้องสมุดมีสองหมวดเรื่อง RL จาก feedback: chat (ฝึก model แชต) และ code (ฝึก model เขียนโค้ด) สมองของ agent อ่านบทสนทนาทั้งหมด แล้วตอบเป็น JSON ว่าจะทำอะไร:

action เมื่อไร สถานะของ task
answer คำขอชัด ตรงหมวดเดียว completed
ask คำขอเข้าได้ทั้งสองหมวด input-required
reject ไม่ใช่งานค้น paper rejected

ฝั่งเราไม่เห็นส่วนนี้เลย — นี่คือ opaque execution (§23.2.1)

PAPERS = {  # teaching data: real arXiv ids, titles, first authors and years; one-line summaries written for this lab
    "2009.01325": {"title": "Learning to summarize from human feedback", "authors": "Stiennon et al.", "year": 2020, "collection": "chat",
                   "summary": "trains a reward model on human comparisons of summaries, then tunes the summarizer against it with PPO"},
    "2203.02155": {"title": "Training language models to follow instructions with human feedback", "authors": "Ouyang et al.", "year": 2022, "collection": "chat",
                   "summary": "InstructGPT: supervised tuning on human demonstrations, then RL on human rankings of the model's answers"},
    "2204.05862": {"title": "Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback", "authors": "Bai et al.", "year": 2022, "collection": "chat",
                   "summary": "RLHF for an assistant that is both helpful and harmless, with preference data collected in weekly rounds"},
    "2212.08073": {"title": "Constitutional AI: Harmlessness from AI Feedback", "authors": "Bai et al.", "year": 2022, "collection": "chat",
                   "summary": "replaces human harmlessness labels with AI feedback guided by a short list of written principles"},
    "2305.18290": {"title": "Direct Preference Optimization: Your Language Model is Secretly a Reward Model", "authors": "Rafailov et al.", "year": 2023, "collection": "chat",
                   "summary": "DPO: learns from preference pairs with a simple classification loss, with no separate reward model or RL loop"},
    "2207.01780": {"title": "CodeRL: Mastering Code Generation through Pretrained Models and Deep Reinforcement Learning", "authors": "Le et al.", "year": 2022, "collection": "code",
                   "summary": "an actor model writes programs and a critic trained on unit-test results gives the reward"},
    "2301.13816": {"title": "Execution-based Code Generation using Deep Reinforcement Learning", "authors": "Shojaee et al.", "year": 2023, "collection": "code",
                   "summary": "PPOCoder: tunes a code model with PPO, using compiler and execution feedback as the reward"},
    "2307.04349": {"title": "RLTF: Reinforcement Learning from Unit Test Feedback", "authors": "Liu et al.", "year": 2023, "collection": "code",
                   "summary": "online RL with fine-grained unit-test feedback that points at where the program went wrong"},
}

def search_papers(collection):
    return [{"id": pid, **p} for pid, p in PAPERS.items() if p["collection"] == collection]
# ✏️ TODO 2 (▶ วิดีโอ 4:47): ให้ action เลือกได้แค่สามทาง
DECIDE = {"type": "json_schema", "json_schema": {"name": "decision", "strict": True, "schema": {
    "type": "object", "additionalProperties": False, "required": ["action", "collection", "question"],
    "properties": {"action": {"type": "string", "enum": ___},
                   "collection": {"type": "string", "enum": ["chat", "code", "none"]},
                   "question": {"type": "string"}}}}}

SYSTEM = ("You are ResearchAgent, the literature-search agent of a university library. "
          "The library has two collections of RLHF papers: 'chat' (RLHF for chat assistants) and 'code' (RLHF for code generation). "
          "Read the whole conversation and decide:\n"
          "- answer: a literature request that clearly fits one collection; set collection.\n"
          "- ask: a literature request that could fit both collections; put one short clarifying question in question. "
          "If the user has already answered your question, choose answer.\n"
          "- reject: not a literature-search request.\n"
          "Use collection 'none' and an empty question when they don't apply.")

def decide(task):
    convo = [{"role": "user" if m.role == "user" else "assistant", "content": m.parts[0].text} for m in task.messages]
    return json.loads(llm([{"role": "system", "content": SYSTEM}, *convo], response_format=DECIDE))

def summarize(request, papers):
    return llm([{"role": "system", "content": "Summarize what these papers do in three sentences. "
                                              "End each sentence with the id of the paper it comes from in brackets."},
                {"role": "user", "content": f"Request: {request}\nPapers: {json.dumps(papers)}"}])
DECIDE = {"type": "json_schema", "json_schema": {"name": "decision", "strict": True, "schema": {
    "type": "object", "additionalProperties": False, "required": ["action", "collection", "question"],
    "properties": {"action": {"type": "string", "enum": ["answer", "ask", "reject"]},
                   "collection": {"type": "string", "enum": ["chat", "code", "none"]},
                   "question": {"type": "string"}}}}}

SYSTEM = ("You are ResearchAgent, the literature-search agent of a university library. "
          "The library has two collections of RLHF papers: 'chat' (RLHF for chat assistants) and 'code' (RLHF for code generation). "
          "Read the whole conversation and decide:\n"
          "- answer: a literature request that clearly fits one collection; set collection.\n"
          "- ask: a literature request that could fit both collections; put one short clarifying question in question. "
          "If the user has already answered your question, choose answer.\n"
          "- reject: not a literature-search request.\n"
          "Use collection 'none' and an empty question when they don't apply.")

def decide(task):
    convo = [{"role": "user" if m.role == "user" else "assistant", "content": m.parts[0].text} for m in task.messages]
    return json.loads(llm([{"role": "system", "content": SYSTEM}, *convo], response_format=DECIDE))

def summarize(request, papers):
    return llm([{"role": "system", "content": "Summarize what these papers do in three sentences. "
                                              "End each sentence with the id of the paper it comes from in brackets."},
                {"role": "user", "content": f"Request: {request}\nPapers: {json.dumps(papers)}"}])

4. A2A server

route ทำอะไร
GET /.well-known/agent.json คืน Agent Card
POST /tasks/send รับ task ใหม่ หรือรับคำตอบของ task ที่รอ input-required
GET /tasks/{id} คืน task ตอนนี้ (ให้ client poll)

/tasks/send ตอบทันที แล้วทำงานต่อเบื้องหลัง — งานยาวต้องไม่บล็อกผู้เรียก (asynchrony, §23.1)

TASKS: dict[str, Task] = {}
app = FastAPI(title="ResearchAgent A2A server")

def set_state(task, state, message=None):
    task.status = TaskStatus(state=state, message=message)
    task.history.append(state)

# ✏️ TODO 3 (▶ วิดีโอ 6:21): เปิด Agent Card ไว้ที่ path ตายตัวของ A2A

@app.get(___)
async def agent_card():
    return AGENT_CARD

@app.post("/tasks/send")
async def send_task(request: Request):
    body = await request.json()
    message = Message(**body["message"])
    task_id = body.get("id") or str(uuid.uuid4())
    # ✏️ TODO 4 (▶ วิดีโอ 6:38): รับคำตอบเฉพาะ task ที่รอข้อมูลอยู่ แล้วกลับไปทำงานต่อ
    if task_id in TASKS:
        task = TASKS[task_id]
        if task.status.state != ___:
            raise HTTPException(409, f"task is {task.status.state}, not waiting for input")
        task.messages.append(message)
        set_state(task, ___)
    else:
        task = Task(id=task_id, status=TaskStatus(state="submitted"), messages=[message], history=["submitted"])
        TASKS[task_id] = task
    asyncio.create_task(execute(task_id))
    return task.model_dump()

@app.get("/tasks/{task_id}")
async def get_task(task_id: str):
    if task_id not in TASKS:
        raise HTTPException(404, "task not found")
    return TASKS[task_id].model_dump()
TASKS: dict[str, Task] = {}
app = FastAPI(title="ResearchAgent A2A server")

def set_state(task, state, message=None):
    task.status = TaskStatus(state=state, message=message)
    task.history.append(state)

@app.get("/.well-known/agent.json")
async def agent_card():
    return AGENT_CARD

@app.post("/tasks/send")
async def send_task(request: Request):
    body = await request.json()
    message = Message(**body["message"])
    task_id = body.get("id") or str(uuid.uuid4())
    if task_id in TASKS:
        task = TASKS[task_id]
        if task.status.state != "input-required":
            raise HTTPException(409, f"task is {task.status.state}, not waiting for input")
        task.messages.append(message)
        set_state(task, "working")
    else:
        task = Task(id=task_id, status=TaskStatus(state="submitted"), messages=[message], history=["submitted"])
        TASKS[task_id] = task
    asyncio.create_task(execute(task_id))
    return task.model_dump()

@app.get("/tasks/{task_id}")
async def get_task(task_id: str):
    if task_id not in TASKS:
        raise HTTPException(404, "task not found")
    return TASKS[task_id].model_dump()
async def execute(task_id):
    task = TASKS[task_id]
    if task.status.state == "submitted":
        set_state(task, "working")
    try:
        d = await asyncio.to_thread(decide, task)
        # ✏️ TODO 5 (▶ วิดีโอ 7:41): ถ้าต้องถามกลับ ให้ task รอข้อมูลพร้อมคำถาม
        if d["action"] == "reject":
            set_state(task, "rejected", "Outside my skills: I only search the library's papers.")
        elif d["action"] == "ask":
            task.messages.append(Message(role="agent", parts=[Part(type="text", text=d["question"])]))
            set_state(task, ___, ___)
        else:
            papers = search_papers(d["collection"])
            request = " ".join(m.parts[0].text for m in task.messages if m.role == "user")
            summary = await asyncio.to_thread(summarize, request, papers)
            task.artifacts = [Artifact(parts=[
                Part(type="text", text=summary),
                Part(type="data", data={"collection": d["collection"], "papers": [p["id"] for p in papers]})])]
            set_state(task, "completed")
    except Exception as e:
        set_state(task, "failed", str(e))
async def execute(task_id):
    task = TASKS[task_id]
    if task.status.state == "submitted":
        set_state(task, "working")
    try:
        d = await asyncio.to_thread(decide, task)
        if d["action"] == "reject":
            set_state(task, "rejected", "Outside my skills: I only search the library's papers.")
        elif d["action"] == "ask":
            task.messages.append(Message(role="agent", parts=[Part(type="text", text=d["question"])]))
            set_state(task, "input-required", d["question"])
        else:
            papers = search_papers(d["collection"])
            request = " ".join(m.parts[0].text for m in task.messages if m.role == "user")
            summary = await asyncio.to_thread(summarize, request, papers)
            task.artifacts = [Artifact(parts=[
                Part(type="text", text=summary),
                Part(type="data", data={"collection": d["collection"], "papers": [p["id"] for p in papers]})])]
            set_state(task, "completed")
    except Exception as e:
        set_state(task, "failed", str(e))

5. A2A client ฝั่งเรา

ย่อจาก A2AClient ใน §23.9: อ่านการ์ด · ส่ง task · ถามสถานะ · รอจนเสร็จ (poll) httpx.ASGITransport ส่ง request เข้า FastAPI app ตรงๆ ใน notebook เดียวกัน — โค้ด client เหมือนเรียก server จริงทุกบรรทัด

http = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://library-agent")
class A2AClient:
    def __init__(self, http):
        self.http = http

    async def get_agent_card(self):
        r = await self.http.get("/.well-known/agent.json")
        r.raise_for_status()
        return r.json()

    async def send_task(self, text, task_id=None):
        msg = Message(role="user", parts=[Part(type="text", text=text)])
        r = await self.http.post("/tasks/send", json={"id": task_id, "message": msg.model_dump()})
        r.raise_for_status()
        return Task(**r.json())

    async def get_task(self, task_id):
        r = await self.http.get(f"/tasks/{task_id}")
        r.raise_for_status()
        return Task(**r.json())

    # ✏️ TODO 6 (▶ วิดีโอ 9:28): poll ต่อไปตราบใดที่ task ยังไม่ถึงสถานะที่ต้องให้เราดู

    async def wait(self, task, every=0.5):
        while task.status.state in ___:
            await asyncio.sleep(every)
            task = await self.get_task(task.id)
        return task

lib = A2AClient(http)
class A2AClient:
    def __init__(self, http):
        self.http = http

    async def get_agent_card(self):
        r = await self.http.get("/.well-known/agent.json")
        r.raise_for_status()
        return r.json()

    async def send_task(self, text, task_id=None):
        msg = Message(role="user", parts=[Part(type="text", text=text)])
        r = await self.http.post("/tasks/send", json={"id": task_id, "message": msg.model_dump()})
        r.raise_for_status()
        return Task(**r.json())

    async def get_task(self, task_id):
        r = await self.http.get(f"/tasks/{task_id}")
        r.raise_for_status()
        return Task(**r.json())

    async def wait(self, task, every=0.5):
        while task.status.state in ("submitted", "working"):
            await asyncio.sleep(every)
            task = await self.get_task(task.id)
        return task

lib = A2AClient(http)

6. ลองคุยกับห้องสมุด

  1. ค้นพบ: อ่าน Agent Card ก่อนส่งงาน
  2. งานชัด: submitted → working → completed
  3. งานกำกวม: … → input-required → ตอบกลับบน task id เดิม → working → completed (multi-turn, §23.3.3)
  4. งานนอกขอบเขต: … → rejected
card = await lib.get_agent_card()
for s in card["skills"]:
    print(f"{card['name']} v{card['version']} · skill {s['id']}: {s['description']}")
    print("  example:", s["examples"][0])
ResearchAgent v1.0.0 · skill literature-search: Search and summarize the library's papers on a topic.
  example: What does the literature say about RLHF for code generation?
task = await lib.send_task("What does the literature say about RLHF for code generation?")
print("sent:", task.id[:8], task.status.state)
task = await lib.wait(task)
print(" → ".join(task.history))
sent: 22710621 submitted
submitted → working → completed
text, data = task.artifacts[0].parts
print(text.text)
print("\ndata part:", data.data)
CodeRL utilizes an actor-critic framework where the critic provides rewards based on the results of unit tests [2207.01780]. PPOCoder employs Proximal Policy Optimization to fine-tune models using feedback derived from compilers and code execution [2301.13816]. RLTF implements online reinforcement learning that leverages fine-grained unit-test feedback to identify specific errors within a program [2307.04349].

data part: {'collection': 'code', 'papers': ['2207.01780', '2301.13816', '2307.04349']}
task = await lib.wait(await lib.send_task("Summarize the papers on RLHF."))
print(task.status.state, "·", task.status.message)
input-required · Could you please specify if you are interested in RLHF papers related to chat assistants or those focused on code generation?
# ✏️ TODO 7 (▶ วิดีโอ 11:38): ตอบคำถามของ agent บน task เดิม
task = await lib.wait(await lib.send_task("Code generation, please.", task_id=___))
print(" → ".join(task.history))
print("papers:", task.artifacts[0].parts[1].data["papers"])
task = await lib.wait(await lib.send_task("Code generation, please.", task_id=task.id))
print(" → ".join(task.history))
print("papers:", task.artifacts[0].parts[1].data["papers"])
submitted → working → input-required → working → completed
papers: ['2207.01780', '2301.13816', '2307.04349']
task = await lib.wait(await lib.send_task("Book me a flight to Tokyo."))
print(" → ".join(task.history), "·", task.status.message)

r = await http.post("/tasks/send", json={"id": task.id, "message": {"role": "user", "parts": [{"type": "text", "text": "Please?"}]}})
print(r.status_code, r.json()["detail"])
submitted → working → rejected · Outside my skills: I only search the library's papers.
409 task is rejected, not waiting for input
print(f"tasks on the server: {len(TASKS)} · cost: USD {COST['chat']:.5f}")
tasks on the server: 3 · cost: USD 0.00019

สรุป

ชิ้นส่วน ในโค้ด ตำรา
Agent Card AGENT_CARD ที่ GET /.well-known/agent.json — skill · tags · examples · input/output modes §23.2.2
task lifecycle State เจ็ดสถานะ, set_state จด history §23.2.3
asynchrony /tasks/send ตอบทันที, asyncio.create_task ทำงานเบื้องหลัง §23.1, §23.9
polling A2AClient.wait ถาม GET /tasks/{id} จนพ้น submitted/working §23.2.5
multi-turn input-required → ตอบบน task id เดิม → working §23.3.3
parts artifact = text ให้คนอ่าน + data ให้โปรแกรมอ่าน §23.5, ตาราง 23.2
opaque execution ฝั่งเราเห็นแค่การ์ดกับ task ไม่เห็น decide §23.2.1

แบบฝึกหัด

  1. ส่ง "Summarize the papers on RLHF." แล้วตอบว่า "Both, please." — agent ทำอย่างไร แก้ schema หรือ search_papers ตรงไหนให้คืนทั้งสองหมวด
  2. เพิ่ม route POST /tasks/{id}/cancel ที่เปลี่ยน task เป็น canceled (และคืน 409 ถ้า task จบแล้ว)
  3. ทำให้ execute โยน exception (เช่นเปลี่ยน MODEL เป็นชื่อที่ไม่มี) แล้วดูว่า task จบที่สถานะไหน และ status.message บอกอะไร

ถัดไป — Lab 2: ผลไม่ต้องรอ poll: stream ด้วย SSE, แจ้งกลับผ่าน webhook และข้อความที่แนบไฟล์