Skip to main content

Lab 4 — ResearchAgent ตัวเดิม ด้วย SDK ทางการ a2a-sdk

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

Lab 1 เราเขียน A2A server เองทุกบรรทัด ตามชื่อในตำรา แล็บนี้สร้าง agent ตัวเดิม (สมองเดิม: answer / ask / reject) ด้วย a2a-sdk 1.3.0 ซึ่งทำตามสเปกปัจจุบัน A2A 1.0 — หลายชื่อเปลี่ยนไปจากตำรา

Lab 1 (ชื่อในตำรา) a2a-sdk 1.3.0 (สเปก 1.0)
การ์ด /.well-known/agent.json /.well-known/agent-card.json
ส่งงาน POST /tasks/send (REST) JSON-RPC SendMessage (หรือ REST / gRPC)
สถานะ "completed" TASK_STATE_COMPLETED (+ TASK_STATE_AUTH_REQUIRED)
part {"type": "text", "text": ...} {"text": ...} — ชนิดดูจากช่องที่มี
งานของเรา route · ที่เก็บ task · กฎสถานะ · poll เขียนแค่ AgentExecutor ที่เหลือ SDK ทำให้

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

  1. Agent Card แบบสเปก 1.0
  2. AgentExecutor ที่ส่ง event ผ่าน TaskUpdater
  3. ดูของจริงบนสาย: การ์ด และ JSON-RPC ที่ส่งด้วย httpx ตรงๆ
  4. client ของ SDK ลองสี่งานเดิมจาก Lab 1

ข้อมูล paper เป็นข้อมูลจำลองเพื่อการสอน (เหมือน Lab 1) ส่วน output ของ model มาจากการรันจริง

อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §23.2, §23.9 — CC BY-SA 4.0 · A2A Protocol Specification 1.0 · a2a-sdk (Apache 2.0)

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

สิ่งที่ต้องมี รายละเอียด
Python 3.10 ขึ้นไป หรือใช้ Google Colab ซึ่งมีให้แล้ว
OpenRouter API key ตั้งค่าเหมือน Lab 1 (lab นี้ใช้ไม่ถึงหนึ่งในสิบของเซ็นต์ดอลลาร์)
Packages a2a-sdk[http-server] (ล็อกรุ่น 1.3.0), httpx, openai, python-dotenv (ติดตั้งใน cell ถัดไป)

ใส่ API key

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

วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1

%pip install -q "a2a-sdk[http-server]==1.3.0" "httpx>=0.28" "openai>=1.50" python-dotenv
import json, os, uuid
import httpx
from openai import AsyncOpenAI
from starlette.applications import Starlette
from google.protobuf.json_format import MessageToDict
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events import EventQueue
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore, TaskUpdater
from a2a.types import (AgentCapabilities, AgentCard, AgentInterface, AgentSkill,
                       GetTaskRequest, Message, Role, SendMessageRequest, TaskState)
from a2a.helpers import get_message_text, new_data_part, new_task_from_user_message, new_text_part
from a2a.client import ClientConfig, create_client
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"
EXTRA = {"reasoning": {"enabled": False},
         "provider": {"order": ["makora"], "allow_fallbacks": False}}
COST = {"chat": 0.0}
aclient = AsyncOpenAI(base_url="https://openrouter.ai/api/v1", api_key=load_key(), max_retries=5)

async def llm(messages, **kw):
    r = await aclient.chat.completions.create(model=MODEL, temperature=0, extra_body=EXTRA, messages=messages, **kw)
    COST["chat"] += r.usage.cost
    return r.choices[0].message.content
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]

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.")

1. Agent Card แบบสเปก 1.0

การ์ดเป็น protobuf AgentCard ช่องที่เปลี่ยนจาก Lab 1:

  • url ช่องเดียว → supported_interfaces: URL + protocol binding (JSONRPC · HTTP+JSON · GRPC) + รุ่นของโปรโตคอล
  • stateTransitionHistory หายไป · ชนิดข้อมูลเขียนเป็น MIME type เช่น text/plain
  • version คือรุ่นของ agent ไม่ใช่ของโปรโตคอล — เปลี่ยนจาก REST เป็น JSON-RPC คือ interface เปลี่ยน → 3.0.0
# ✏️ TODO 1 (▶ วิดีโอ 1:50): บอกว่ารับงานผ่าน binding แบบไหน
URL = "http://research-agent"
card = AgentCard(
    name="ResearchAgent", version="3.0.0",
    description="Searches the library's RLHF papers and summarizes them.",
    supported_interfaces=[AgentInterface(url=URL, protocol_binding=___, protocol_version="1.0")],
    capabilities=AgentCapabilities(streaming=False, push_notifications=False),
    default_input_modes=["text/plain"], default_output_modes=["text/plain", "application/json"],
    skills=[AgentSkill(id="literature-search", name="Literature Search",
                       description="Search and summarize the library's RLHF papers.", tags=["research", "papers"],
                       examples=["What does the literature say about RLHF for code generation?"])])
URL = "http://research-agent"
card = AgentCard(
    name="ResearchAgent", version="3.0.0",
    description="Searches the library's RLHF papers and summarizes them.",
    supported_interfaces=[AgentInterface(url=URL, protocol_binding="JSONRPC", protocol_version="1.0")],
    capabilities=AgentCapabilities(streaming=False, push_notifications=False),
    default_input_modes=["text/plain"], default_output_modes=["text/plain", "application/json"],
    skills=[AgentSkill(id="literature-search", name="Literature Search",
                       description="Search and summarize the library's RLHF papers.", tags=["research", "papers"],
                       examples=["What does the literature say about RLHF for code generation?"])])

2. AgentExecutor: สมองของ agent

SDK ให้เราเขียน method เดียว execute(context, event_queue):

  • context — ข้อความใหม่ · task ปัจจุบัน (ถ้ามี) · task id
  • event_queue — ทุกอย่างที่ agent อยากบอกผู้เรียก ใส่ลงคิวนี้ (task · สถานะ · ผลงาน)
  • TaskUpdater — ตัวช่วยสร้าง event: start_work() · requires_input() · reject() · add_artifact() · complete()

เราไม่ต้องเขียน route ที่เก็บ task หรือกฎว่าสถานะสุดท้ายห้ามเปลี่ยน — SDK ทำให้

# ✏️ TODO 2 (▶ วิดีโอ 2:38): ใส่คำถามที่ agent ถามไว้ ก่อนข้อความใหม่
def conversation(context):
    task = context.current_task
    msgs = list(task.history) if task else []
    if task and task.status.state == TaskState.TASK_STATE_INPUT_REQUIRED:
        msgs.append(___)   # the agent's own question
    msgs.append(context.message)           # the new message
    return [{"role": "user" if m.role == Role.ROLE_USER else "assistant", "content": get_message_text(m)} for m in msgs]
def conversation(context):
    task = context.current_task
    msgs = list(task.history) if task else []
    if task and task.status.state == TaskState.TASK_STATE_INPUT_REQUIRED:
        msgs.append(task.status.message)   # the agent's own question
    msgs.append(context.message)           # the new message
    return [{"role": "user" if m.role == Role.ROLE_USER else "assistant", "content": get_message_text(m)} for m in msgs]
class ResearchAgentExecutor(AgentExecutor):
    async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
        updater = TaskUpdater(event_queue, context.task_id, context.context_id)
        if not context.current_task:
            await event_queue.enqueue_event(new_task_from_user_message(context.message))
        await updater.start_work()
        # ✏️ TODO 3 (▶ วิดีโอ 3:31): เลือก method ของ TaskUpdater ให้ตรงกับการตัดสินใจ
        d = json.loads(await llm([{"role": "system", "content": SYSTEM}, *conversation(context)], response_format=DECIDE))
        if d["action"] == "reject":
            await updater.___(updater.new_agent_message([new_text_part("Outside my skills: I only search the library's papers.")]))
        elif d["action"] == "ask":
            await updater.___(updater.new_agent_message([new_text_part(d["question"])]))
        else:
            papers = search_papers(d["collection"])
            request = " ".join(get_message_text(m) for m in [*(context.current_task.history if context.current_task else []),
                                                             context.message] if m.role == Role.ROLE_USER)
            summary = await 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)}"}])
            await updater.add_artifact([new_text_part(summary),
                                        new_data_part({"collection": d["collection"], "papers": [p["id"] for p in papers]})],
                                       name="literature-review")
            await updater.complete()

    async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
        await TaskUpdater(event_queue, context.task_id, context.context_id).cancel()
class ResearchAgentExecutor(AgentExecutor):
    async def execute(self, context: RequestContext, event_queue: EventQueue) -> None:
        updater = TaskUpdater(event_queue, context.task_id, context.context_id)
        if not context.current_task:
            await event_queue.enqueue_event(new_task_from_user_message(context.message))
        await updater.start_work()
        d = json.loads(await llm([{"role": "system", "content": SYSTEM}, *conversation(context)], response_format=DECIDE))
        if d["action"] == "reject":
            await updater.reject(updater.new_agent_message([new_text_part("Outside my skills: I only search the library's papers.")]))
        elif d["action"] == "ask":
            await updater.requires_input(updater.new_agent_message([new_text_part(d["question"])]))
        else:
            papers = search_papers(d["collection"])
            request = " ".join(get_message_text(m) for m in [*(context.current_task.history if context.current_task else []),
                                                             context.message] if m.role == Role.ROLE_USER)
            summary = await 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)}"}])
            await updater.add_artifact([new_text_part(summary),
                                        new_data_part({"collection": d["collection"], "papers": [p["id"] for p in papers]})],
                                       name="literature-review")
            await updater.complete()

    async def cancel(self, context: RequestContext, event_queue: EventQueue) -> None:
        await TaskUpdater(event_queue, context.task_id, context.context_id).cancel()
handler = DefaultRequestHandler(agent_executor=ResearchAgentExecutor(), task_store=InMemoryTaskStore(), agent_card=card)
app = Starlette(routes=create_agent_card_routes(card) + create_jsonrpc_routes(handler, "/"))

3. ดูของจริงบนสาย

ก่อนใช้ client ของ SDK มาดูว่า server ส่งอะไรจริงๆ ด้วย httpx ธรรมดา (ผ่าน ASGITransport แบบ Lab 1 — ไม่ต้องเปิด port)

http = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url=URL, timeout=60)
r = await http.get("/.well-known/agent-card.json")
print(r.status_code, json.dumps(r.json(), indent=1)[:520])
200 {
 "name": "ResearchAgent",
 "description": "Searches the library's RLHF papers and summarizes them.",
 "supportedInterfaces": [
  {
   "url": "http://research-agent",
   "protocolBinding": "JSONRPC",
   "protocolVersion": "1.0"
  }
 ],
 "version": "3.0.0",
 "capabilities": {
  "streaming": false,
  "pushNotifications": false
 },
 "defaultInputModes": [
  "text/plain"
 ],
 "defaultOutputModes": [
  "text/plain",
  "application/json"
 ],
 "skills": [
  {
   "id": "literature-search",
   "name": "Literature Search",
# ✏️ TODO 4 (▶ วิดีโอ 5:09): ชื่อ method ของ JSON-RPC สำหรับส่งงาน ในสเปก 1.0
rpc = {"jsonrpc": "2.0", "id": 1, "method": ___,
       "params": {"message": {"role": "ROLE_USER", "messageId": str(uuid.uuid4()),
                              "parts": [{"text": "Book me a flight to Tokyo."}]}}}
r = await http.post("/", json=rpc, headers={"A2A-Version": "1.0"})
status = r.json()["result"]["task"]["status"]
print(status["state"], "·", status["message"]["parts"][0]["text"])
rpc = {"jsonrpc": "2.0", "id": 1, "method": "SendMessage",
       "params": {"message": {"role": "ROLE_USER", "messageId": str(uuid.uuid4()),
                              "parts": [{"text": "Book me a flight to Tokyo."}]}}}
r = await http.post("/", json=rpc, headers={"A2A-Version": "1.0"})
status = r.json()["result"]["task"]["status"]
print(status["state"], "·", status["message"]["parts"][0]["text"])
TASK_STATE_REJECTED · Outside my skills: I only search the library's papers.
old = {**rpc, "method": "message/send"}   # the method name from spec 0.3
print((await http.post("/", json=old, headers={"A2A-Version": "1.0"})).json()["error"])
Request Error (ID: 1): Code=-32601, Message='Method not found'

{'code': -32601, 'message': 'Method not found'}

4. client ของ SDK: สี่งานเดิมจาก Lab 1

create_client(URL) อ่านการ์ดเอง แล้วเลือก binding ที่ agent รองรับ — เราส่ง httpx client ของเราเข้าไป ให้วิ่งผ่าน ASGITransport

client = await create_client(URL, client_config=ClientConfig(httpx_client=http))

async def send(text, task=None):
    msg = Message(role=Role.ROLE_USER, message_id=str(uuid.uuid4()), parts=[new_text_part(text)],
                  task_id=task.id if task else "", context_id=task.context_id if task else "")
    async for event in client.send_message(SendMessageRequest(message=msg)):
        return event.task

def state(task):
    return TaskState.Name(task.status.state).removeprefix("TASK_STATE_")
t = await send("What does the literature say about RLHF for code generation?")
print(state(t), "·", MessageToDict(t.artifacts[0].parts[1])["data"])
COMPLETED · {'collection': 'code', 'papers': ['2207.01780', '2301.13816', '2307.04349']}
t = await send("Summarize the papers on RLHF.")
print(state(t), "·", get_message_text(t.status.message))
INPUT_REQUIRED · Would you like me to summarize papers focused on RLHF for chat assistants, or those focused on RLHF for code generation?
# ✏️ TODO 5 (▶ วิดีโอ 7:22): ตอบคำถามของ agent บน task เดิม
t2 = await send("Code generation, please.", task=___)
print(state(t2), "· same task:", t2.id == t.id, "·", MessageToDict(t2.artifacts[0].parts[1])["data"]["papers"])
print([(Role.Name(m.role), get_message_text(m)[:40]) for m in t2.history])
t2 = await send("Code generation, please.", task=t)
print(state(t2), "· same task:", t2.id == t.id, "·", MessageToDict(t2.artifacts[0].parts[1])["data"]["papers"])
print([(Role.Name(m.role), get_message_text(m)[:40]) for m in t2.history])
COMPLETED · same task: True · ['2207.01780', '2301.13816', '2307.04349']
[('ROLE_USER', 'Summarize the papers on RLHF.'), ('ROLE_AGENT', 'Would you like me to summarize papers fo'), ('ROLE_USER', 'Code generation, please.')]
t = await send("Book me a flight to Tokyo.")
print(state(t), "·", get_message_text(t.status.message))
try:
    await send("Please?", task=t)
except Exception as e:
    print(type(e).__name__, "·", e)
REJECTED · Outside my skills: I only search the library's papers.
UnsupportedOperationError · Task 30a3412b-c35b-4a80-b1f0-4fd1637f8686 is in terminal state: TASK_STATE_REJECTED
g = await client.get_task(GetTaskRequest(id=t2.id))
print("get_task:", state(g), "·", len(g.history), "messages")
await client.close()
print(f"cost: USD {COST['chat']:.5f}")
get_task: COMPLETED · 3 messages
cost: USD 0.00022

สรุป

เขียนเองใน Lab 1 a2a-sdk ทำให้
การ์ด dict + route /.well-known/agent.json AgentCard + create_agent_card_routes (agent-card.json)
รับงาน route /tasks/send + asyncio.create_task DefaultRequestHandler + create_jsonrpc_routes (SendMessage)
เก็บ task TASKS dict InMemoryTaskStore (หรือฐานข้อมูล)
สถานะ set_state + กฎ 409 TaskUpdater · สถานะสุดท้ายเปลี่ยนไม่ได้ · error → failed
client poll เองจนจบ create_client อ่านการ์ด เลือก binding · รอผลให้
สมอง decide + summarize ยังเป็นของเรา — AgentExecutor.execute

แบบฝึกหัด

  1. เปิด streaming=True ในการ์ด แล้วดู event ที่ client.send_message คืนมาทีละอัน (ต้องรัน server จริงด้วย uvicorn แบบ Lab 2)
  2. เพิ่ม AgentInterface แบบ HTTP+JSON ด้วย create_rest_routes — agent เดียว รับได้สองทาง
  3. ส่ง JSON-RPC โดยไม่มี header A2A-Version — server ตอบว่าอะไร และทำไม

ถัดไป: สรุปทั้ง EP16