将 Bub Agent 与 FastAPI 集成
前面几节我们已经了解了 Bub SDK 的核心组件。本节不再引入新概念,而是把 Agent、工具、事件拦截和 Tape 存储串起来,基于 FastAPI 亲手搭一个带 SSE 流式输出和删除二次确认的 Todo Agent 应用。
完整源码位于 bub-todo-agent,你可以直接下载试跑,或者跟着下面的步骤一步步搭起来:
文件夹bub-todo-agent/
- main.py # 后端服务代码(本节重点)
- index.html # 前端演示页面
文件夹static/
- uno.global.js
- alpine.min.js
文件夹sessions/ # 运行时自动生成的 Tape 存储目录
- …
1. 初始化 Agent 与 FastAPI Lifespan
Section titled “1. 初始化 Agent 与 FastAPI Lifespan”首先,我们把应用骨架搭起来:在 FastAPI 的 lifespan 中初始化模型连接与 Agent 实例,并挂载到 app.state 上供所有请求复用:
已折叠 33 行代码
#!/usr/bin/env -S uv run --script# /// script# requires-python = ">=3.12"# dependencies = [# "bub @ git+https://github.com/bubbuild/bub@main",# "fastapi>=0.135",# "python-dotenv",# "uvicorn",# ]# ///
import asyncioimport loggingimport osfrom collections import defaultdictfrom collections.abc import AsyncIterable, Awaitable, Callablefrom contextlib import asynccontextmanager, suppressfrom itertools import countfrom pathlib import Pathfrom typing import Literalfrom uuid import uuid4
import republicfrom dotenv import load_dotenvfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.sse import EventSourceResponse, ServerSentEventfrom pydantic import BaseModel, Field
from bub.core import Agentfrom bub.core.events import ToolCallDecision, ToolCallFinished, ToolCallStartedfrom bub.core.store import FileTapeStorefrom bub.core.tools import tool
logger = logging.getLogger(__name__)BASE_DIR = Path(__file__).resolve().parent
load_dotenv()
MODEL = os.getenv("BUB_MODEL", "openai:gpt-4o-mini")BASE_URL = os.getenv("BUB_API_BASE", "https://api.openai.com/v1")API_KEY = os.getenv("BUB_API_KEY") or os.getenv("REPUBLIC_OPENAI_API_KEY")HOST = os.getenv("BUB_HOST", "127.0.0.1")PORT = int(os.getenv("BUB_PORT", "8000"))
@asynccontextmanagerasync def lifespan(app: FastAPI): async with republic.get_model(MODEL, api_base=BASE_URL, api_key=API_KEY) as model: agent = Agent( store=FileTapeStore(BASE_DIR / "sessions"), system_prompt=( "You are a personal todo assistant. Always use tools to read or change todos; " "never guess task state. If a request is ambiguous, look it up or ask the user " "first, and respect tool errors and denial reasons." ), max_steps=6, )
app.state.model = model app.state.agent = agent app.state.session_locks = defaultdict(asyncio.Lock) # request_id -> future;删除钩子在此等待用户确认,由 POST /chat/confirm 唤醒 app.state.pending_confirms = {} yield
app = FastAPI(title="Bub Todo Agent", lifespan=lifespan)- 将
Agent挂载在app.state上全局复用,避免每次请求重复初始化; max_steps=6限制单次 Run 的最大步数;FileTapeStore将会话历史持久化到本地sessions/目录。
到这一步还只是一个最基础的骨架——模型目前只能纯聊天,还干不了实事。接下来,我们给它装上真正能操作待办事项的工具。
2. 定义业务工具
Section titled “2. 定义业务工具”Agent 就位之后,接下来让它真正能干活——把待办事项的查询、新增、完成和删除操作写成普通 Python 函数,再用 @tool 封装成工具交给 Agent:
from itertools import countfrom pydantic import BaseModel, Fieldfrom bub.core.tools import tool
TASKS: dict[str, dict[str, object]] = {}TASK_IDS = count(3)
@tooldef list_tasks() -> list[dict[str, object]]: """List every todo with its task ID, title, and completion state.""" return [dict(task) for task in TASKS.values()]
class AddTaskInput(BaseModel): title: str = Field(min_length=1, max_length=100, description="Short, specific todo title")
@tool(name="add_task", model=AddTaskInput)def add_task(param: AddTaskInput) -> dict[str, object]: """Add a new incomplete todo.""" task_id = f"task-{next(TASK_IDS)}" task = {"task_id": task_id, "title": param.title, "completed": False} TASKS[task_id] = task return dict(task)
@tooldef complete_task(task_id: str) -> dict[str, object]: """Mark a todo complete by task ID. Call list_tasks first if the ID is unknown.""" if task := TASKS.get(task_id): task["completed"] = True return dict(task) return {"task_id": task_id, "error": "task_not_found"}
@tooldef delete_task(task_id: str) -> dict[str, object]: """Permanently delete a todo by task ID. The host must authorize it first.""" if task := TASKS.pop(task_id, None): return {"task_id": task_id, "status": "deleted", "title": task["title"]} return {"task_id": task_id, "error": "task_not_found"}上面这几个函数都是很基础的 Python 逻辑,这里就不逐行展开了,只需记住三点:
- 函数的 docstring 和类型标注会自动生成工具 Schema,模型全靠它们决定何时调用以及怎么传参;
- 返回值必须可 JSON 序列化,业务失败(如任务不存在)直接返回
{"error": ...},不要动辄抛异常中断整个流程; delete_task是不可逆操作,稍后我们会通过事件处理器给它加上二次确认。
现在把这组工具传给 Agent,并设置 max_tool_concurrency=2:
@asynccontextmanagerasync def lifespan(app: FastAPI): async with republic.get_model(MODEL, api_base=BASE_URL, api_key=API_KEY) as model: agent = Agent( store=FileTapeStore(BASE_DIR / "sessions"), tools=[list_tasks, add_task, complete_task, delete_task], system_prompt=( "You are a personal todo assistant. Always use tools to read or change todos; " "never guess task state. If a request is ambiguous, look it up or ask the user " "first, and respect tool errors and denial reasons." ), max_steps=6, max_tool_concurrency=2, )3. 封装 Agent 调用参数
Section titled “3. 封装 Agent 调用参数”装上工具之后,我们的 Agent 就有了「手脚」。在接入 HTTP 路由前,先写一个轻量的包装函数 run_agent,把请求参数 ChatRequest、会话 session_id 和删除确认回调 confirm_delete 传给 agent.run():
ConfirmDelete = Callable[[dict[str, object]], Awaitable[bool]]
class ChatRequest(BaseModel): session_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,64}$") prompt: str = Field(min_length=1, max_length=10_000) think_level: Literal["auto", "low", "medium", "high"] = "auto"
def run_agent(agent: Agent, model, req: ChatRequest, confirm_delete: ConfirmDelete): options = None if req.think_level == "auto" else {"reasoning_effort": req.think_level} return agent.run( req.prompt, model=model, options=options, tape=req.session_id, state={"session_id": req.session_id, "confirm_delete": confirm_delete}, )tape=req.session_id让同一session_id的请求共享多轮对话历史(通过正则限制字符范围,确保作为文件名安全);state将当前请求的确认回调传递给接下来的事件处理器。
4. 注册事件处理器(日志与删除审批)
Section titled “4. 注册事件处理器(日志与删除审批)”有了工具之后,我们还可以利用事件总线在关键节点「插一手」——比如记录工具调用日志,或者在执行删除前拦下来等用户点头。在 lifespan 中注册两个事件处理器:
ToolCallFinished:记录每次工具调用的名称、状态和耗时;ToolCallStarted:在执行delete_task前暂停并等待前端用户确认;若用户拒绝或超时,通过ToolCallDecision.deny(...)拦截删除。
@agent.events.on(ToolCallFinished) def audit_tool(event: ToolCallFinished) -> None: logger.info( "tool=%s status=%s duration_ms=%s", event.result.tool, "error" if event.result.error else "ok", event.result.duration_ms, )
@agent.events.on(ToolCallStarted) async def authorize_tool(event: ToolCallStarted) -> None: if event.call.tool != "delete_task": return confirm: ConfirmDelete | None = event.state.get("confirm_delete") if confirm is None or not await confirm(event.call.arguments): event.decision = ToolCallDecision.deny( "The user did not approve deleting this todo. Do not retry; offer to mark " "the todo complete instead." )由于 EventBus 会同步 await 异步处理器,当前 Run 会在 await confirm(...) 处暂停,直到用户在前端点击确认或取消。同时注意,deny 只会跳过这一次工具调用,不会终止整次 Run;模型会收到拒绝原因并顺势调整回复。
5. 会话锁与确认接口
Section titled “5. 会话锁与确认接口”上一节我们在删除前暂停了事件处理器,但要让「暂停等待确认」在并发 Web 服务中可靠跑起来,还需要解决两件事:同一会话的请求得排队,以及前端的确认结果得准确送回那个等待中的处理器。为此,我们在 lifespan 中维护了两个字典:
app.state.session_locks = defaultdict(asyncio.Lock)app.state.pending_confirms = {}session_locks:按session_id加锁,确保同一会话不会并发读写同一个 Tape;pending_confirms:保存request_id -> asyncio.Future,当用户在前端点击确认按钮并调用POST /chat/confirm时,唤醒正在等待的事件处理器:
class Confirmation(BaseModel): request_id: str approved: bool
@app.post("/chat/confirm")async def confirm_tool_call(req: Confirmation, request: Request): future = request.app.state.pending_confirms.pop(req.request_id, None) if future is None or future.done(): raise HTTPException(status_code=404, detail="confirmation_not_found") future.set_result(req.approved) return {"approved": req.approved}好,基础设施全部就位,现在来做最后一块拼图。
6. 通过 SSE 流式推送响应
Section titled “6. 通过 SSE 流式推送响应”锁和确认接口就位后,最后把它们串进 /chat/stream 接口:后台任务驱动 Agent 运行,并通过 asyncio.Queue 将文本增量、工具调用、确认请求和完成信号统一作为 SSE(Server-Sent Events)帧推给前端:
已折叠 8 行代码
import asynciofrom collections.abc import AsyncIterablefrom contextlib import suppressfrom uuid import uuid4
from fastapi import Requestfrom fastapi.sse import EventSourceResponse, ServerSentEvent
@app.post("/chat/stream", response_class=EventSourceResponse)async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[ServerSentEvent]: state = request.app.state lock: asyncio.Lock = state.session_locks[req.session_id] queue: asyncio.Queue[ServerSentEvent | None] = asyncio.Queue()
async def confirm_delete(arguments: dict[str, object]) -> bool: task_id = str(arguments.get("task_id", "")) request_id = uuid4().hex future = asyncio.get_running_loop().create_future() state.pending_confirms[request_id] = future queue.put_nowait( ServerSentEvent( data={ "request_id": request_id, "task_id": task_id, "title": (TASKS.get(task_id) or {}).get("title"), }, event="confirm", ) ) try: # 120 秒超时或客户端断开时默认拒绝删除 return await asyncio.wait_for(future, timeout=120) except TimeoutError: return False finally: state.pending_confirms.pop(request_id, None)
async def chat() -> None: try: async with lock, run_agent(state.agent, state.model, req, confirm_delete) as stream: async for event in stream: if event.kind == "text": queue.put_nowait( ServerSentEvent(data={"delta": event.data["delta"]}, event="message") ) elif event.kind == "tool_call": names = [call["name"] for call in event.data["tool_calls"]] queue.put_nowait(ServerSentEvent(data={"names": names}, event="tool"))
# 整个 Run 结束后发送 done(final 事件仅代表单个 Step 结束) queue.put_nowait( ServerSentEvent(data={"last_step_usage": stream.usage}, event="done") ) except asyncio.CancelledError: raise except Exception: logger.exception("Streaming agent run failed: session=%s", req.session_id) queue.put_nowait(ServerSentEvent(data={"message": "Agent run failed"}, event="error")) finally: queue.put_nowait(None)
task = asyncio.create_task(chat()) try: while (frame := await queue.get()) is not None: yield frame finally: task.cancel() with suppress(asyncio.CancelledError): await task你也可以直接在下方查看完整的 bub-todo-agent/main.py 源码(辅助函数与常规路由已默认折叠,点击即可展开):
已折叠 136 行代码
#!/usr/bin/env -S uv run --script# /// script# requires-python = ">=3.12"# dependencies = [# "bub>=0.6.0",# "fastapi>=0.135",# "python-dotenv",# "uvicorn",# ]# ///
import asyncioimport loggingimport osfrom collections import defaultdictfrom collections.abc import AsyncIterable, Awaitable, Callablefrom contextlib import asynccontextmanager, suppressfrom datetime import UTC, datetime, timedeltafrom itertools import countfrom pathlib import Pathfrom typing import Literalfrom uuid import uuid4
import republicfrom dotenv import load_dotenvfrom fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import FileResponsefrom fastapi.sse import EventSourceResponse, ServerSentEventfrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModel, Field
from bub.core import Agentfrom bub.core.events import ToolCallDecision, ToolCallFinished, ToolCallStartedfrom bub.core.store import FileTapeStorefrom bub.core.tools import tool
logger = logging.getLogger(__name__)BASE_DIR = Path(__file__).resolve().parent
load_dotenv()
# ===== App config: override via environment variables or .env, or edit the defaults here =====MODEL = os.getenv("BUB_MODEL", "openai:gpt-4.1")BASE_URL = os.getenv("BUB_API_BASE")API_KEY = os.getenv("BUB_API_KEY") or os.getenv("REPUBLIC_OPENAI_API_KEY")HOST = os.getenv("BUB_HOST", "127.0.0.1")PORT = int(os.getenv("BUB_PORT", "8000"))# ==========================================================
# Called from the ToolCallStarted hook; resolves to True only if the person approves in the UI.ConfirmDelete = Callable[[dict[str, object]], Awaitable[bool]]
def _ago(**delta: float) -> str: return (datetime.now(UTC) - timedelta(**delta)).isoformat(timespec="seconds")
def initial_tasks() -> dict[str, dict[str, object]]: return { "task-1": { "task_id": "task-1", "title": "Write the weekly report", "completed": False, "created_at": _ago(days=2), "completed_at": None, }, "task-2": { "task_id": "task-2", "title": "Read the Bub docs", "completed": True, "created_at": _ago(days=3), "completed_at": _ago(hours=5), }, }
# Demo task store (not a Tape). Each page load resets it via POST /tasks/reset.TASKS: dict[str, dict[str, object]] = initial_tasks()TASK_IDS = count(3)
def reset_tasks() -> None: global TASK_IDS TASKS.clear() TASKS.update(initial_tasks()) TASK_IDS = count(3)
def all_tasks() -> list[dict[str, object]]: return [dict(task) for task in TASKS.values()]
@tooldef list_tasks() -> list[dict[str, object]]: """List every todo with its task ID, title, and completion state.""" return all_tasks()
class AddTaskInput(BaseModel): title: str = Field(min_length=1, max_length=100, description="Short, specific todo title")
@tool(name="add_task", model=AddTaskInput)def add_task(param: AddTaskInput) -> dict[str, object]: """Add a new incomplete todo.""" task_id = f"task-{next(TASK_IDS)}" task = { "task_id": task_id, "title": param.title, "completed": False, "created_at": _ago(), "completed_at": None, } TASKS[task_id] = task return dict(task)
@tooldef complete_task(task_id: str) -> dict[str, object]: """Mark a todo complete by task ID. Call list_tasks first if the ID is unknown.""" if task := TASKS.get(task_id): task["completed"] = True task["completed_at"] = _ago() return dict(task) return {"task_id": task_id, "error": "task_not_found"}
@tooldef delete_task(task_id: str) -> dict[str, object]: """Permanently delete a todo by task ID. The host must authorize it first.""" if task := TASKS.pop(task_id, None): return {"task_id": task_id, "status": "deleted", "title": task["title"]} return {"task_id": task_id, "error": "task_not_found"}
@asynccontextmanagerasync def lifespan(app: FastAPI): async with republic.get_model(MODEL, api_base=BASE_URL, api_key=API_KEY) as model: agent = Agent( store=FileTapeStore(BASE_DIR / "sessions"), tools=[list_tasks, add_task, complete_task, delete_task], system_prompt=( "You are a personal todo assistant. Always use tools to read or change todos; " "never guess task state. If a request is ambiguous, look it up or ask the user " "first, and respect tool errors and denial reasons." ), max_steps=6, max_tool_concurrency=2, )
@agent.events.on(ToolCallStarted) async def authorize_tool(event: ToolCallStarted) -> None: # Async handlers are awaited, so this hook pauses the run until the person answers # the prompt. Denying is the safe default when nobody answers. if event.call.tool != "delete_task": return confirm: ConfirmDelete | None = event.state.get("confirm_delete") if confirm is None or not await confirm(event.call.arguments): event.decision = ToolCallDecision.deny( "The user did not approve deleting this todo. Do not retry; offer to mark " "the todo complete instead." )
@agent.events.on(ToolCallFinished) def audit_tool(event: ToolCallFinished) -> None: logger.info( "tool=%s status=%s duration_ms=%s", event.result.tool, "error" if event.result.error else "ok", event.result.duration_ms, )
app.state.model = model app.state.agent = agent app.state.session_locks = defaultdict(asyncio.Lock) # request_id -> future that the delete hook is waiting on; answered by POST /chat/confirm. app.state.pending_confirms = {} yield
app = FastAPI(title="Bub Todo Agent", lifespan=lifespan)app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static")
已折叠 75 行代码
class ChatRequest(BaseModel): # The tape name becomes a filename; namespace it per tenant/user in production. session_id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,64}$") prompt: str = Field(min_length=1, max_length=10_000) think_level: Literal["auto", "low", "medium", "high"] = "auto"
def run_agent(agent: Agent, model, req: ChatRequest, confirm_delete: ConfirmDelete): # Auto sends no reasoning options; other levels depend on the current provider. options = None if req.think_level == "auto" else {"reasoning_effort": req.think_level} return agent.run( req.prompt, model=model, options=options, tape=req.session_id, # Turn state reaches event hooks and tools; the delete hook awaits this callback. state={"session_id": req.session_id, "confirm_delete": confirm_delete}, )
@app.get("/")async def index(): return FileResponse(BASE_DIR / "index.html")
@app.get("/config")async def config(): # Only expose display-safe config; never return the API key. return {"model": MODEL, "base_url": BASE_URL, "api_key_configured": bool(API_KEY)}
@app.get("/tasks")async def tasks(): # Deterministic business query; no model call. return {"tasks": all_tasks()}
@app.post("/tasks/reset")async def reset_demo_tasks(): # Called on every page load so a refresh starts from the seed data. reset_tasks() return {"tasks": all_tasks()}
class TaskUpdate(BaseModel): completed: bool
@app.patch("/tasks/{task_id}")async def update_task(task_id: str, req: TaskUpdate): # Manual toggle from the page; shares the same TASKS store as the agent tools. task = TASKS.get(task_id) if task is None: raise HTTPException(status_code=404, detail="task_not_found") task["completed"] = req.completed task["completed_at"] = _ago() if req.completed else None return dict(task)
class Confirmation(BaseModel): request_id: str approved: bool
@app.post("/chat/confirm")async def confirm_tool_call(req: Confirmation, request: Request): # Answer the delete confirmation a running hook is awaiting; unknown means already gone. future = request.app.state.pending_confirms.pop(req.request_id, None) if future is None or future.done(): raise HTTPException(status_code=404, detail="confirmation_not_found") future.set_result(req.approved) return {"approved": req.approved}
@app.post("/chat/stream", response_class=EventSourceResponse)async def chat_stream(req: ChatRequest, request: Request) -> AsyncIterable[ServerSentEvent]: state = request.app.state lock: asyncio.Lock = state.session_locks[req.session_id] # The run is pumped in a task so a hook can push frames (the confirmation request) because # it runs inside the agent stream, where the response generator itself cannot yield. queue: asyncio.Queue[ServerSentEvent | None] = asyncio.Queue()
async def confirm_delete(arguments: dict[str, object]) -> bool: task_id = str(arguments.get("task_id", "")) request_id = uuid4().hex future = asyncio.get_running_loop().create_future() state.pending_confirms[request_id] = future queue.put_nowait( ServerSentEvent( data={ "request_id": request_id, "task_id": task_id, "title": (TASKS.get(task_id) or {}).get("title"), }, event="confirm", ) ) try: # Fail closed: no answer within two minutes, or a dropped client, means no delete. return await asyncio.wait_for(future, timeout=120) except TimeoutError: return False finally: state.pending_confirms.pop(request_id, None)
async def chat() -> None: try: async with lock, run_agent(state.agent, state.model, req, confirm_delete) as stream: async for event in stream: if event.kind == "text": queue.put_nowait(ServerSentEvent(data={"delta": event.data["delta"]}, event="message")) elif event.kind == "tool_call": names = [call["name"] for call in event.data["tool_calls"]] queue.put_nowait(ServerSentEvent(data={"names": names}, event="tool"))
# The run has ended; usage is for the last model step only. queue.put_nowait(ServerSentEvent(data={"last_step_usage": stream.usage}, event="done")) except asyncio.CancelledError: raise except Exception: logger.exception("Streaming agent run failed: session=%s", req.session_id) queue.put_nowait(ServerSentEvent(data={"message": "Agent run failed"}, event="error")) finally: queue.put_nowait(None)
task = asyncio.create_task(chat()) try: while (frame := await queue.get()) is not None: yield frame finally: task.cancel() with suppress(asyncio.CancelledError): await task
已折叠 5 行代码
if __name__ == "__main__": import uvicorn
uvicorn.run(app, host=HOST, port=PORT)交互时序总览
Section titled “交互时序总览”我们快速回顾一下本章内容,整个 Demo 中一次完整的交互路径如下:
总的来说,这个应用可以清晰地分成三部分:
- 配置与集成:在 FastAPI
lifespan中初始化 Bub Agent 与 Tape 存储; - 工具与事件定制:把待办操作封装成工具,再通过事件处理器加上审计日志与删除二次确认;
- HTTP 与流式交互:用会话锁、确认接口和 SSE 流把所有环节串成完整的前后端闭环。
到这里,我们的完整 Demo 就算大功告成了!现在你可以直接下载 bub-todo-agent 在本地启动,打开浏览器体验一下:
-
将
.env.example复制为.env并填入模型配置:.env BUB_MODEL=openai:gpt-4o-miniBUB_API_BASE=https://api.openai.com/v1BUB_API_KEY=sk-...BUB_HOST=127.0.0.1BUB_PORT=8000 -
使用
uv启动服务:终端窗口 uv run main.py -
在浏览器中访问
http://127.0.0.1:8000:$ uv run main.pyINFO: Started server process [85377]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
祝你玩得愉快!