Integrating a Bub Agent with FastAPI
With the basics of the Bub SDK behind us, this guide introduces no new concepts. Instead, it ties Agent, tools, event interception, and Tape storage together into a working FastAPI Todo Agent with Server-Sent Events (SSE) streaming and human-in-the-loop delete confirmation.
The complete example is available in bub-todo-agent. Download it to experiment, or build along step by step:
Directorybub-todo-agent/
- main.py # Backend service (covered in this guide)
- index.html # Frontend demo UI
Directorystatic/
- uno.global.js
- alpine.min.js
Directorysessions/ # Tape storage directory created at runtime
- …
1. Initialize the Agent in FastAPI Lifespan
Section titled “1. Initialize the Agent in FastAPI Lifespan”First, let’s build the application skeleton: create the model client and Agent inside FastAPI’s lifespan and attach them to app.state so all requests reuse a single instance:
33 collapsed lines
#!/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; delete hook awaits confirmation here, woken by POST /chat/confirm app.state.pending_confirms = {} yield
app = FastAPI(title="Bub Todo Agent", lifespan=lifespan)- Mounting
agentonapp.stateavoids re-creating the Agent on every request. max_steps=6caps the steps per Run.FileTapeStorepersists conversation history undersessions/.
So far this is just a minimal skeleton—the model can only chat and cannot act yet. Next, let’s give it tools to do real work.
2. Define business tools
Section titled “2. Define business tools”With the Agent in place, let’s make it genuinely useful by wrapping todo list, create, complete, and delete operations with @tool:
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"}The code above is straightforward Python, so we won’t walk through every line—just keep three things in mind:
- Each function’s docstring and type annotations become the tool schema the model reads before calling it.
- Return values must be JSON-serializable; return
{"error": ...}for expected business failures instead of raising exceptions. delete_taskis irreversible, so we’ll intercept it in a moment to ask for confirmation.
Now pass the tools to Agent and set 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. Wrap agent.run()
Section titled “3. Wrap agent.run()”Now that the Agent has tools — its “hands and feet” — let’s write a small helper run_agent that passes ChatRequest, session_id, and the confirm_delete callback into 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_idshares history across turns in the same session (validated by regex so it is safe as a filename).statepasses the per-request confirmation callback to the event handlers.
4. Register event handlers (logging & delete approval)
Section titled “4. Register event handlers (logging & delete approval)”With tools wired up, we can also use the event bus to step in at key moments—such as logging every tool call or pausing before a deletion to ask the user. Register two handlers in lifespan:
ToolCallFinished: logs tool name, status, and duration.ToolCallStarted: interceptsdelete_taskand awaits user confirmation; denies the call withToolCallDecision.deny(...)if rejected or timed out.
@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." )Because EventBus awaits async handlers synchronously, the Run pauses at await confirm(...) until the user responds in the UI. Note that deny skips only this tool call rather than aborting the whole Run—the model receives the denial reason and adjusts its response.
5. Session locks and confirmation endpoint
Section titled “5. Session locks and confirmation endpoint”In the previous step we paused the handler before deleting a task, but two pieces are needed for that pause to work reliably in a web service: same-session requests must queue, and the user’s answer from the browser must reach the waiting handler. Two dictionaries on app.state handle this:
app.state.session_locks = defaultdict(asyncio.Lock)app.state.pending_confirms = {}session_locks: serializes requests persession_idso two requests never mutate the same Tape concurrently.pending_confirms: mapsrequest_id -> asyncio.FuturesoPOST /chat/confirmcan wake the pausedToolCallStartedhandler:
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}With locks and confirmations in place, let’s wire up the final piece.
6. Stream responses over SSE
Section titled “6. Stream responses over SSE”Now we can bring everything together in /chat/stream: a background task drives the Agent Run and pushes text deltas, tool calls, confirmation requests, and the final completion frame onto an asyncio.Queue yielded as SSE events:
8 collapsed lines
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: # Fail closed on 120s timeout or client disconnect 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"))
# Emit done only after the full Run finishes (final marks a single 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 taskYou can also inspect the complete bub-todo-agent/main.py file directly below (helper and route boilerplate is collapsed by default—click to expand):
136 collapsed lines
#!/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 collapsed lines
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 collapsed lines
if __name__ == "__main__": import uvicorn
uvicorn.run(app, host=HOST, port=PORT)Interaction sequence
Section titled “Interaction sequence”Let’s quickly recap what we built. A complete interaction in this demo flows like this:
In summary, the demo comes together in three parts:
- Configuration and integration: initialize the Bub Agent and Tape store in FastAPI’s
lifespan. - Custom logic via tools and events: wrap todo operations as tools, then layer audit logging and delete confirmation on top with event handlers.
- HTTP and streaming: tie everything together with session locks, the confirmation endpoint, and SSE streaming.
Run the example
Section titled “Run the example”And with that, our complete demo is ready! Download bub-todo-agent and run it locally to try it out in your browser:
-
Copy
.env.exampleto.envand fill in your model settings:.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 -
Start the server with
uv:Terminal window uv run main.py -
Open
http://127.0.0.1:8000in your browser:$ 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)
Enjoy!