Lab 2 — Stream, push และไฟล์
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 ฝั่งเรา poll ถามสถานะซ้ำๆ จนงานเสร็จ คลิปทฤษฎีบอกว่า A2A มีอีกสองทาง (§23.2.4–23.2.5):
| ทาง | ใช้เมื่อ |
|---|---|
| stream (SSE) | อยากได้ผลทีละส่วนตั้งแต่เนิ่นๆ ผ่านการเชื่อมต่อเดียว |
| push notification | งานยาวเป็นนาทีหรือชั่วโมง — ทิ้ง webhook ไว้ แล้วไปทำอย่างอื่น |
และข้อความหนึ่งมีได้หลาย part: ข้อความ · ไฟล์ · JSON (§23.5, ตาราง 23.2)
สิ่งที่จะได้ทำ
- part ชนิด
file(ไฟล์เป็น bytes) และ artifact ที่ต่อกันได้ (append·lastChunk) - ResearchAgent รุ่น 1.1.0: อ่าน part ทุกชนิด เขียนบททบทวนวรรณกรรมแบบ stream และคืนไฟล์
references.bib - route
/tasks/sendSubscribeที่ส่ง event แบบ SSE และ route ยกเลิก task - webhook ฝั่งเรา ที่ตรวจ token ก่อนรับ
- ลองสี่แบบ: stream · ส่งไฟล์ CSV + JSON · push · ยกเลิกกลางทาง
ข้อมูล paper เป็นข้อมูลจำลองเพื่อการสอน (เหมือน Lab 1) ส่วน output ของ model มาจากการรันจริง
อ้างอิง: Haggai Roitman, The Hitchhiker’s Guide to Agentic AI, §23.2.4–23.2.5, §23.5, §23.9 — CC BY-SA 4.0
0. เตรียมเครื่องก่อนเริ่ม
| สิ่งที่ต้องมี | รายละเอียด |
|---|---|
| Python 3.10 ขึ้นไป | หรือใช้ Google Colab ซึ่งมีให้แล้ว |
| OpenRouter API key | ตั้งค่าเหมือน Lab 1 (lab นี้ใช้ไม่ถึงหนึ่งในสิบของเซ็นต์ดอลลาร์) |
| Packages | fastapi, uvicorn, httpx, openai, python-dotenv, pydantic (ติดตั้งใน cell ถัดไป) |
ใส่ API key
- Colab: ไอคอน 🔑 Secrets → ชื่อ
OPENROUTER_API_KEY→ เปิด Notebook access - เครื่องตัวเอง: สร้างไฟล์
.envในโฟลเดอร์เดียวกับ notebook แล้วใส่บรรทัดOPENROUTER_API_KEY=sk-or-...
วิธีตั้งค่า key และเหตุผลที่เลือก model อยู่ใน Lab 1
%pip install -q "fastapi>=0.110" "uvicorn>=0.30" "httpx>=0.27" "openai>=1.50" python-dotenv "pydantic>=2"import asyncio, base64, csv, io, json, os, threading, time, uuid
from datetime import datetime, timezone
from typing import Literal
import httpx, uvicorn
from fastapi import FastAPI, Header, HTTPException, Request
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
from openai import AsyncOpenAIdef 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)1. โครงข้อมูล: ไฟล์ และ artifact ที่ต่อกันได้
Message State TaskStatus เหมือน Lab 1 ของใหม่สามอย่าง:
| ช่อง | ใช้ทำอะไร |
|---|---|
Part.bytes · Part.name |
ไฟล์ที่ส่งมาเป็น bytes (base64) พร้อมชื่อไฟล์ — คู่กับ mimeType |
Artifact.append · lastChunk |
ชิ้นนี้ต่อท้ายชิ้นก่อนไหม · เป็นชิ้นสุดท้ายหรือยัง (§23.2.4) |
Task.push |
webhook URL + token ที่ผู้ส่งฝากไว้ (§23.2.5) |
class Message(BaseModel):
role: Literal["user", "agent"]
parts: list["Part"]
State = Literal["submitted", "working", "input-required", "completed", "failed", "rejected", "canceled"]
FINAL = {"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 Part(BaseModel):
type: Literal["text", "file", "data"]
text: str | None = None
data: dict | None = None
mimeType: str | None = None
uri: str | None = None
bytes: str | None = None
name: str | None = None
class Artifact(BaseModel):
parts: list[Part]
index: int = 0
append: bool = False
lastChunk: bool = True
class PushConfig(BaseModel):
url: str
token: str
class Task(BaseModel):
id: str
status: TaskStatus
messages: list[Message] = []
artifacts: list[Artifact] = []
history: list[str] = []
push: PushConfig | None = None
Message.model_rebuild()[6]:
True
2. Agent Card รุ่น 1.1.0
ห้องสมุดเปิดความสามารถใหม่ จึงขึ้นเลข MINOR (1.0.0 → 1.1.0): เพิ่มของใหม่ แต่ client รุ่นเก่ายังใช้ได้เหมือนเดิม (semver, §23.4.4)
AGENT_CARD = {
"name": "ResearchAgent",
"url": "http://127.0.0.1:8001",
"version": "1.1.0",
"capabilities": {"streaming": True, "pushNotifications": True, "stateTransitionHistory": True},
"skills": [{"id": "literature-review", "name": "Literature Review",
"description": "Write a short literature review from the library's papers, with a BibTeX file.",
"inputModes": ["text", "data", "file"], "outputModes": ["text", "file"]}],
}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 bibtex(papers):
return "\n".join(f"@article{{{p['authors'].split()[0].lower()}{p['year']},\n title = {{{p['title']}}},\n"
f" author = {{{p['authors']}}},\n year = {{{p['year']}}},\n eprint = {{{p['id']}}},\n"
f" archivePrefix = {{arXiv}}\n}}" for p in papers)# ✏️ TODO 1 (▶ วิดีโอ 3:29): เลือก part ตามชนิด: data เป็นตัวเลือก และไฟล์ CSV เป็นรายการที่อ่านแล้ว
def read_request(msg):
text = " ".join(p.text for p in msg.parts if p.type == "text")
options = next((p.data for p in msg.parts if p.type == ___), {})
already_read = set()
for p in msg.parts:
if p.type == "file" and p.mimeType == ___:
rows = csv.DictReader(io.StringIO(base64.b64decode(p.bytes).decode()))
already_read |= {r["arxiv_id"] for r in rows}
return text, options, already_readdef read_request(msg):
text = " ".join(p.text for p in msg.parts if p.type == "text")
options = next((p.data for p in msg.parts if p.type == "data"), {})
already_read = set()
for p in msg.parts:
if p.type == "file" and p.mimeType == "text/csv":
rows = csv.DictReader(io.StringIO(base64.b64decode(p.bytes).decode()))
already_read |= {r["arxiv_id"] for r in rows}
return text, options, already_read3. server: event ไปได้สองทาง
ทุกครั้งที่ task มีอะไรใหม่ (สถานะเปลี่ยน หรือมีผลงานชิ้นใหม่) server สร้าง event หนึ่งอัน แล้วส่งไปได้สองทาง:
- ถ้ามีคนเปิด stream ค้างไว้ → ใส่ คิว ของ task นั้น ให้ route ของ stream ส่งต่อ
- ถ้าผู้ส่งฝาก webhook ไว้ → POST event สถานะไปที่ webhook พร้อม token
| route ใหม่ | ทำอะไร |
|---|---|
POST /tasks/sendSubscribe |
รับ task แล้วตอบเป็น stream ของ SSE จนถึง event ที่ final: true |
POST /tasks/{id}/cancel |
ยกเลิก task ที่ยังไม่จบ |
TASKS: dict[str, Task] = {}
QUEUES: dict[str, asyncio.Queue] = {} # task id → events waiting for an open stream
RUNNING: dict[str, asyncio.Task] = {} # task id → the background work, so it can be canceled
library = FastAPI(title="ResearchAgent A2A server v1.1")
async def emit(task, event):
if task.id in QUEUES:
await QUEUES[task.id].put(event)
if task.push and "status" in event:
async with httpx.AsyncClient() as http:
await http.post(task.push.url, json=event, headers={"X-A2A-Token": task.push.token})
async def set_state(task, state, message=None):
task.status = TaskStatus(state=state, message=message)
task.history.append(state)
await emit(task, {"id": task.id, "status": task.status.model_dump(), "final": state in FINAL})async def execute(task):
await set_state(task, "working")
try:
text, options, already_read = read_request(task.messages[0])
papers = [{"id": pid, **p} for pid, p in PAPERS.items()
if p["collection"] == options.get("collection", p["collection"])
and p["year"] >= options.get("year_from", 0) and pid not in already_read]
stream = await aclient.chat.completions.create(
model=MODEL, temperature=0, extra_body=EXTRA, stream=True, stream_options={"include_usage": True},
messages=[{"role": "system", "content": "Write a short literature review (about 250 words) with a markdown heading. "
"Cite paper ids in brackets."},
{"role": "user", "content": f"Request: {text}\nPapers: {json.dumps(papers)}"}])
# ✏️ TODO 2 (▶ วิดีโอ 5:36): ชิ้นแรกเริ่มผลงานใหม่ ชิ้นต่อไปให้ต่อท้าย
first = True
async for chunk in stream:
if chunk.usage:
COST["chat"] += chunk.usage.cost
if chunk.choices and chunk.choices[0].delta.content:
art = Artifact(parts=[Part(type="text", text=chunk.choices[0].delta.content)],
index=0, append=___, lastChunk=False)
task.artifacts.append(art)
first = False
await emit(task, {"id": task.id, "artifact": art.model_dump(), "final": False})
bib = Artifact(parts=[Part(type="file", name="references.bib", mimeType="application/x-bibtex",
bytes=base64.b64encode(bibtex(papers).encode()).decode())], index=1)
task.artifacts.append(bib)
await emit(task, {"id": task.id, "artifact": bib.model_dump(), "final": False})
await set_state(task, "completed")
except asyncio.CancelledError:
await set_state(task, "canceled", "canceled by the client")
except Exception as e:
await set_state(task, "failed", str(e))async def execute(task):
await set_state(task, "working")
try:
text, options, already_read = read_request(task.messages[0])
papers = [{"id": pid, **p} for pid, p in PAPERS.items()
if p["collection"] == options.get("collection", p["collection"])
and p["year"] >= options.get("year_from", 0) and pid not in already_read]
stream = await aclient.chat.completions.create(
model=MODEL, temperature=0, extra_body=EXTRA, stream=True, stream_options={"include_usage": True},
messages=[{"role": "system", "content": "Write a short literature review (about 250 words) with a markdown heading. "
"Cite paper ids in brackets."},
{"role": "user", "content": f"Request: {text}\nPapers: {json.dumps(papers)}"}])
first = True
async for chunk in stream:
if chunk.usage:
COST["chat"] += chunk.usage.cost
if chunk.choices and chunk.choices[0].delta.content:
art = Artifact(parts=[Part(type="text", text=chunk.choices[0].delta.content)],
index=0, append=not first, lastChunk=False)
task.artifacts.append(art)
first = False
await emit(task, {"id": task.id, "artifact": art.model_dump(), "final": False})
bib = Artifact(parts=[Part(type="file", name="references.bib", mimeType="application/x-bibtex",
bytes=base64.b64encode(bibtex(papers).encode()).decode())], index=1)
task.artifacts.append(bib)
await emit(task, {"id": task.id, "artifact": bib.model_dump(), "final": False})
await set_state(task, "completed")
except asyncio.CancelledError:
await set_state(task, "canceled", "canceled by the client")
except Exception as e:
await set_state(task, "failed", str(e))def new_task(body):
push = PushConfig(**body["pushNotification"]) if body.get("pushNotification") else None
task = Task(id=body.get("id") or str(uuid.uuid4()), status=TaskStatus(state="submitted"),
messages=[Message(**body["message"])], history=["submitted"], push=push)
TASKS[task.id] = task
return task
@library.post("/tasks/send")
async def send(request: Request):
task = new_task(await request.json())
RUNNING[task.id] = asyncio.create_task(execute(task))
return task.model_dump()
@library.post("/tasks/sendSubscribe")
async def send_subscribe(request: Request):
task = new_task(await request.json())
QUEUES[task.id] = asyncio.Queue()
RUNNING[task.id] = asyncio.create_task(execute(task))
# ✏️ TODO 3 (▶ วิดีโอ 6:45): ส่ง event ทีละอันแบบ SSE จนถึง event สุดท้าย
async def events():
yield f"data: {json.dumps({'id': task.id, 'status': {'state': 'submitted'}, 'final': False})}\n\n"
while True:
event = await QUEUES[task.id].get()
yield ___
if ___:
break
del QUEUES[task.id]
return StreamingResponse(events(), media_type="text/event-stream")
# ✏️ TODO 4 (▶ วิดีโอ 7:11): ยกเลิกงานเบื้องหลังของ task
@library.post("/tasks/{task_id}/cancel")
async def cancel(task_id: str):
if task_id not in TASKS:
raise HTTPException(404, "task not found")
if TASKS[task_id].status.state in FINAL:
raise HTTPException(409, f"task is already {TASKS[task_id].status.state}")
___
return {"id": task_id, "cancel": "requested"}
@library.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()def new_task(body):
push = PushConfig(**body["pushNotification"]) if body.get("pushNotification") else None
task = Task(id=body.get("id") or str(uuid.uuid4()), status=TaskStatus(state="submitted"),
messages=[Message(**body["message"])], history=["submitted"], push=push)
TASKS[task.id] = task
return task
@library.post("/tasks/send")
async def send(request: Request):
task = new_task(await request.json())
RUNNING[task.id] = asyncio.create_task(execute(task))
return task.model_dump()
@library.post("/tasks/sendSubscribe")
async def send_subscribe(request: Request):
task = new_task(await request.json())
QUEUES[task.id] = asyncio.Queue()
RUNNING[task.id] = asyncio.create_task(execute(task))
async def events():
yield f"data: {json.dumps({'id': task.id, 'status': {'state': 'submitted'}, 'final': False})}\n\n"
while True:
event = await QUEUES[task.id].get()
yield f"data: {json.dumps(event)}\n\n"
if event["final"]:
break
del QUEUES[task.id]
return StreamingResponse(events(), media_type="text/event-stream")
@library.post("/tasks/{task_id}/cancel")
async def cancel(task_id: str):
if task_id not in TASKS:
raise HTTPException(404, "task not found")
if TASKS[task_id].status.state in FINAL:
raise HTTPException(409, f"task is already {TASKS[task_id].status.state}")
RUNNING[task_id].cancel()
return {"id": task_id, "cancel": "requested"}
@library.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()4. ฝั่งเรา: webhook และการเปิด server
orchestrator ของเราก็ต้องมี server เล็กๆ หนึ่งตัว เพื่อรับ push: route POST /webhooks/a2a ที่ ตรวจ token ก่อน รับ event
ทำไมไม่ใช้ ASGITransport เหมือน Lab 1: มันรอให้ response จบทั้งก้อนก่อนคืนให้ client — event ทุกอันของ stream จะมาถึงพร้อมกันตอนจบ Lab นี้จึงรัน app ทั้งสองด้วย uvicorn บน 127.0.0.1 (ในเครื่องเดียวกัน ใช้บน Colab ได้) คนละ port ใน thread เบื้องหลัง
| app | ของใคร | port |
|---|---|---|
library |
ห้องสมุด (ResearchAgent) | 8001 |
orchestrator |
ฝั่งเรา (webhook) | 8002 |
# ✏️ TODO 5 (▶ วิดีโอ 7:56): รับ event เฉพาะเมื่อ token ตรงกับที่เราฝากไว้
WEBHOOK_TOKEN = "whk-" + uuid.uuid4().hex[:12] # a fresh secret for this run
INBOX = []
orchestrator = FastAPI(title="Our orchestrator")
@orchestrator.post("/webhooks/a2a")
async def webhook(event: dict, x_a2a_token: str = Header(None)):
if ___:
raise HTTPException(401, "bad token")
INBOX.append(event)
return {"ok": True}WEBHOOK_TOKEN = "whk-" + uuid.uuid4().hex[:12] # a fresh secret for this run
INBOX = []
orchestrator = FastAPI(title="Our orchestrator")
@orchestrator.post("/webhooks/a2a")
async def webhook(event: dict, x_a2a_token: str = Header(None)):
if x_a2a_token != WEBHOOK_TOKEN:
raise HTTPException(401, "bad token")
INBOX.append(event)
return {"ok": True}def start(app, port):
server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning"))
threading.Thread(target=server.run, daemon=True).start()
while not server.started:
time.sleep(0.05)
start(library, 8001)
start(orchestrator, 8002)
LIB = "http://127.0.0.1:8001"
print(httpx.get(f"{LIB}/tasks/none").status_code, "← the library answers on", LIB)404 ← the library answers on http://127.0.0.1:8001
5. client ที่ฟัง stream
stream_task เปิด POST /tasks/sendSubscribe ค้างไว้ อ่านทีละบรรทัด แล้วจัดการ event สองชนิด:
- artifact ข้อความ → พิมพ์ต่อกันทันที (ต่อท้ายเพราะ
append: true) - status → พิมพ์สถานะกับเวลา และหยุดเมื่อ
final: true
def msg(text, data=None, files=()):
parts = [{"type": "text", "text": text}]
if data:
parts.append({"type": "data", "data": data})
return {"role": "user", "parts": parts + list(files)}
async def stream_task(message, cancel_after=None):
t0, chunks, events = time.time(), 0, []
async with httpx.AsyncClient(timeout=300) as http:
async with http.stream("POST", f"{LIB}/tasks/sendSubscribe", json={"message": message}) as r:
async for line in r.aiter_lines():
if not line.startswith("data: "):
continue
e = json.loads(line[6:])
events.append(e)
if "artifact" in e and e["artifact"]["parts"][0]["type"] == "text":
chunks += 1
print(e["artifact"]["parts"][0]["text"], end="", flush=True)
if chunks == cancel_after:
print("\n>>> cancel:", (await http.post(f"{LIB}/tasks/{e['id']}/cancel")).json()["cancel"])
if "status" in e:
print(f"\n[{time.time() - t0:4.1f}s] {e['status']['state']}", "(final)" if e["final"] else "")
if e["final"]:
break
return events, chunks6. ลองสี่แบบ
- stream: บททบทวนเรื่อง RLHF สำหรับเขียนโค้ด — ดูว่าชิ้นแรกมาถึงเมื่อไร เทียบกับตอนเสร็จ
- ไฟล์ + JSON เข้า: แนบ CSV ของ paper ที่อ่านแล้ว + ตัวเลือก
{"collection": "chat", "year_from": 2022} - push: ส่งงานพร้อม webhook แล้วไปทำอย่างอื่น · ลองปลอม event ด้วย token ผิด
- ยกเลิก กลางทาง
events, chunks = await stream_task(msg("Write a short literature review on RLHF for code generation.", {"collection": "code"}))
[ 0.0s] submitted
[ 0.1s] working
# Literature Review: Reinforcement Learning from Feedback in Code Generation
The application of Reinforcement Learning from Human Feedback (RLHF) principles to code generation has shifted focus toward automated, execution-based feedback mechanisms. Unlike natural language tasks, code generation allows for objective evaluation through formal verification and execution, enabling models to optimize for functional correctness rather than mere linguistic similarity.
Early approaches in this domain, such as CodeRL [2207.01780], utilize an actor-critic framework where an actor model generates programs and a critic, trained on unit-test results, provides the reward signal. This allows the model to bridge the gap between probabilistic token prediction and the logical requirements of programming. Building on this concept, PPOCoder [2301.13816] demonstrates the efficacy of using Proximal Policy Optimization (PPO) to fine-tune code models by incorporating both compiler feedback and execution results as reward signals, ensuring that the generated syntax is both valid and functional.
Recent advancements have moved toward more granular feedback loops to improve sample efficiency and error localization. For instance, RLTF [2307.04349] introduces an online reinforcement learning approach that leverages fine-grained unit-test feedback. Rather than providing a simple binary success/failure signal, this method identifies specific points of failure within a program, guiding the model toward more precise corrections. Collectively, these studies indicate a clear trend: moving away from static datasets toward dynamic, execution-driven environments that treat code as a functional entity rather than a sequence of text.
[ 2.4s] completed (final)
arts = [e["artifact"] for e in events if "artifact" in e]
for a in arts[:3]:
print({k: a[k] for k in ("index", "append", "lastChunk")}, repr(a["parts"][0].get("text"))[:30])
print(f"... {chunks} text chunks, then:")
bib = arts[-1]["parts"][0]
print(bib["name"], bib["mimeType"])
print(base64.b64decode(bib["bytes"]).decode()[:220]){'index': 0, 'append': False, 'lastChunk': False} '#'
{'index': 0, 'append': True, 'lastChunk': False} ' Literature Review: Reinforce
{'index': 0, 'append': True, 'lastChunk': False} ' Feedback'
... 112 text chunks, then:
references.bib application/x-bibtex
@article{le2022,
title = {CodeRL: Mastering Code Generation through Pretrained Models and Deep Reinforcement Learning},
author = {Le et al.},
year = {2022},
eprint = {2207.01780},
archivePrefix = {arXiv}
}
@art
# ✏️ TODO 6 (▶ วิดีโอ 10:39): แนบไฟล์ CSV เป็น part ไฟล์ที่มี mimeType และ bytes
already_read = "arxiv_id,title\n2203.02155,InstructGPT\n2305.18290,DPO\n"
csv_part = {"type": ___, "name": "already_read.csv", "mimeType": ___,
"bytes": base64.b64encode(already_read.encode()).decode()}
events, _ = await stream_task(msg("Review the chat papers I haven't read yet.",
{"collection": "chat", "year_from": 2022}, [csv_part]))already_read = "arxiv_id,title\n2203.02155,InstructGPT\n2305.18290,DPO\n"
csv_part = {"type": "file", "name": "already_read.csv", "mimeType": "text/csv",
"bytes": base64.b64encode(already_read.encode()).decode()}
events, _ = await stream_task(msg("Review the chat papers I haven't read yet.",
{"collection": "chat", "year_from": 2022}, [csv_part]))
[ 0.0s] submitted
[ 0.0s] working
# Literature Review: Advancements in Alignment via Human and AI Feedback
Recent research in large language model (LLM) alignment has focused on balancing the dual objectives of utility and safety. A foundational approach involves using Reinforcement Learning from Human Feedback (RLHF) to fine-tune assistants. As demonstrated by Bai et al. [2204.05862], this method utilizes preference data collected through iterative human rounds to train models that are simultaneously helpful and harmless. While effective, this traditional RLHF paradigm relies heavily on continuous human intervention to provide the necessary preference labels to guide model behavior.
To address the scalability limitations of human labeling, more recent methodologies have shifted toward automated alignment processes. Bai et al. [2212.08073] introduced the concept of "Constitutional AI," a framework that replaces direct human labeling with AI feedback. In this approach, the model is guided by a predefined set of written principles—a "constitution"—to evaluate and self-correct its own outputs. This transition from human-centric feedback to AI-driven feedback guided by explicit principles represents a significant evolution in the field, potentially allowing for more scalable and transparent methods of ensuring model harmlessness without the bottleneck of manual human annotation. Together, these papers illustrate a trajectory from direct human preference modeling toward autonomous, principle-based alignment.
[ 1.6s] completed (final)
bib = base64.b64decode(events[-2]["artifact"]["parts"][0]["bytes"]).decode()
print([line.split("{")[1].rstrip("},") for line in bib.splitlines() if "eprint" in line])['2204.05862', '2212.08073']
# ✏️ TODO 7 (▶ วิดีโอ 11:20): ฝาก webhook กับ token ไว้กับห้องสมุด
async with httpx.AsyncClient() as http:
r = await http.post(f"{LIB}/tasks/send", json={
"message": msg("Write a short literature review on RLHF for chat assistants.", {"collection": "chat"}),
"pushNotification": {"url": ___, "token": ___}})
print("sent:", r.json()["status"]["state"])
for _ in range(20):
await asyncio.sleep(0.5) # our orchestrator does other work here
if any(e["final"] for e in INBOX):
break
print("inbox:", [e["status"]["state"] for e in INBOX])async with httpx.AsyncClient() as http:
r = await http.post(f"{LIB}/tasks/send", json={
"message": msg("Write a short literature review on RLHF for chat assistants.", {"collection": "chat"}),
"pushNotification": {"url": "http://127.0.0.1:8002/webhooks/a2a", "token": WEBHOOK_TOKEN}})
print("sent:", r.json()["status"]["state"])
for _ in range(20):
await asyncio.sleep(0.5) # our orchestrator does other work here
if any(e["final"] for e in INBOX):
break
print("inbox:", [e["status"]["state"] for e in INBOX])sent: submitted
inbox: ['working', 'completed']
async with httpx.AsyncClient() as http:
r = await http.post("http://127.0.0.1:8002/webhooks/a2a", headers={"X-A2A-Token": "guess"},
json={"id": "fake", "status": {"state": "completed"}, "final": True})
print(r.status_code, r.json(), "· inbox size:", len(INBOX))401 {'detail': 'bad token'} · inbox size: 2
events, chunks = await stream_task(msg("Write a long literature review on all the RLHF papers."), cancel_after=5)
print(TASKS[events[0]["id"]].history)
[ 0.0s] submitted
[ 0.0s] working
# Evolution of Reinforcement Learning from Human and Environmental Feedback
Rein
>>> cancel: requested
forcement Learning from Human Feedback (RLHF) has emerged as a cornerstone for
[ 0.7s] canceled (final)
['submitted', 'working', 'canceled']
print(f"cost: USD {COST['chat']:.5f}")cost: USD 0.00035
สรุป
| ชิ้นส่วน | ในโค้ด | ตำรา |
|---|---|---|
| stream (SSE) | /tasks/sendSubscribe + StreamingResponse · data: {...} ทีละอัน จนถึง final: true |
§23.2.4 |
| artifact ทีละชิ้น | append (ต่อท้าย) · lastChunk · index (ผลงานชิ้นที่เท่าไร) |
§23.2.4 |
| push notification | pushNotification: {url, token} → server POST event สถานะ · webhook ตรวจ token |
§23.2.5 |
| parts | text เจตนา · data ตัวเลือก · file CSV เข้า / BibTeX ออก (mimeType + bytes) |
§23.5, ตาราง 23.2 |
| ยกเลิก | POST /tasks/{id}/cancel → CancelledError → canceled |
§23.2.3 |
| semver | การ์ด 1.0.0 → 1.1.0 เพิ่มความสามารถโดยไม่ทำให้ client เก่าพัง | §23.4.4 |
แบบฝึกหัด
- ส่ง
lastChunk: Trueในชิ้นข้อความสุดท้าย (ต้องรู้ว่าชิ้นไหนสุดท้าย — ลองเก็บชิ้นไว้หนึ่งชิ้นก่อนส่ง) - ให้ webhook ได้ event ผลงานด้วย แล้วนับว่า POST มากี่ครั้ง — ทำไมตำราแนะนำให้ push เฉพาะสถานะ
- ส่งไฟล์ที่
mimeTypeเป็นapplication/pdf—read_requestทำอย่างไร ควรตอบrejectedไหม (ดูinputModesในการ์ด)
ถัดไป — Lab 3: workflow วิจัยทั้งชุด: registry, เลือก agent ตามความสามารถ, ต่อ MCP, เช็กสิทธิ์ และ audit log