|
| 1 | +# Tencent is pleased to support the open source community by making tRPC-Agent-Python available. |
| 2 | +# |
| 3 | +# Copyright (C) 2026 Tencent. All rights reserved. |
| 4 | +# |
| 5 | +# trpc-agent-python is licensed under the Apache License Version 2.0. |
| 6 | +"""AG-UI server for the Plan Mode example. |
| 7 | +
|
| 8 | +Exposes the plan_mode orchestrator (see agent/agent.py) over the AG-UI |
| 9 | +protocol and serves a small, dependency-free static HTML page |
| 10 | +(static/index.html) from the same FastAPI app so it can call the agent |
| 11 | +endpoint same-origin (no CORS setup needed). |
| 12 | +
|
| 13 | +The page lets a human watch the plan document update live and |
| 14 | +approve / reject / answer questions from the browser instead of |
| 15 | +simulating the decision in Python. |
| 16 | +
|
| 17 | +Run: |
| 18 | + cd examples/plan_mode |
| 19 | + python3 run_agent_with_agui.py |
| 20 | +
|
| 21 | +Then open http://127.0.0.1:18090/ in a browser. |
| 22 | +
|
| 23 | +Prerequisites: |
| 24 | + pip install -e '.[ag-ui]' |
| 25 | + Set TRPC_AGENT_API_KEY (and optionally TRPC_AGENT_BASE_URL / TRPC_AGENT_MODEL_NAME) |
| 26 | + in examples/plan_mode/.env |
| 27 | +""" |
| 28 | + |
| 29 | +from __future__ import annotations |
| 30 | + |
| 31 | +import argparse |
| 32 | +import os |
| 33 | +import sys |
| 34 | +from contextlib import asynccontextmanager |
| 35 | +from pathlib import Path |
| 36 | + |
| 37 | +from dotenv import load_dotenv |
| 38 | +from fastapi import FastAPI |
| 39 | +from fastapi.responses import FileResponse |
| 40 | +from pydantic import BaseModel |
| 41 | + |
| 42 | +from trpc_agent_sdk.log import logger |
| 43 | +from trpc_agent_sdk.server.ag_ui import AgUiAgent |
| 44 | +from trpc_agent_sdk.server.ag_ui import AgUiManager |
| 45 | +from trpc_agent_sdk.server.ag_ui import AgUiService |
| 46 | + |
| 47 | +_EXAMPLE_DIR = Path(__file__).resolve().parent |
| 48 | +if str(_EXAMPLE_DIR) not in sys.path: |
| 49 | + sys.path.insert(0, str(_EXAMPLE_DIR)) |
| 50 | + |
| 51 | +load_dotenv(_EXAMPLE_DIR / ".env") |
| 52 | + |
| 53 | +HOST = "127.0.0.1" |
| 54 | +PORT = 18090 |
| 55 | +APP_NAME = "plan_mode_agui_demo" |
| 56 | +AGENT_URI = "/plan_agent" |
| 57 | +STATIC_DIR = _EXAMPLE_DIR / "static" |
| 58 | +INDEX_HTML = STATIC_DIR / "index.html" |
| 59 | + |
| 60 | +agui_manager = AgUiManager() |
| 61 | + |
| 62 | + |
| 63 | +class HealthResponse(BaseModel): |
| 64 | + """Response body for GET /health.""" |
| 65 | + |
| 66 | + status: str = "ok" |
| 67 | + app_name: str |
| 68 | + agent_uri: str |
| 69 | + |
| 70 | + |
| 71 | +def _create_agui_agent() -> AgUiAgent: |
| 72 | + """Lazy factory so each worker process gets its own agent instance.""" |
| 73 | + from agent.agent import create_plan_agent |
| 74 | + |
| 75 | + return AgUiAgent(trpc_agent=create_plan_agent(), app_name=APP_NAME) |
| 76 | + |
| 77 | + |
| 78 | +@asynccontextmanager |
| 79 | +async def _lifespan(app: FastAPI): # noqa: ARG001 |
| 80 | + if not os.environ.get("TRPC_AGENT_API_KEY"): |
| 81 | + logger.warning( |
| 82 | + "TRPC_AGENT_API_KEY is not set — copy .env.example values into %s/.env", |
| 83 | + _EXAMPLE_DIR, |
| 84 | + ) |
| 85 | + if not INDEX_HTML.is_file(): |
| 86 | + raise FileNotFoundError(f"Demo page not found: {INDEX_HTML}") |
| 87 | + logger.info("Plan Mode AG-UI demo starting up.") |
| 88 | + yield |
| 89 | + logger.info("Plan Mode AG-UI demo shutting down.") |
| 90 | + await agui_manager.close() |
| 91 | + |
| 92 | + |
| 93 | +def create_app() -> FastAPI: |
| 94 | + """Build the FastAPI app: AG-UI agent endpoint + static demo page.""" |
| 95 | + app = FastAPI(title="Plan Mode AG-UI Demo", lifespan=_lifespan) |
| 96 | + |
| 97 | + @app.get("/", response_class=FileResponse) |
| 98 | + async def index() -> FileResponse: |
| 99 | + return FileResponse(INDEX_HTML) |
| 100 | + |
| 101 | + @app.get("/health", response_model=HealthResponse) |
| 102 | + async def health() -> HealthResponse: |
| 103 | + return HealthResponse(app_name=APP_NAME, agent_uri=AGENT_URI) |
| 104 | + |
| 105 | + service = AgUiService(APP_NAME, app=app) |
| 106 | + service.add_agent(AGENT_URI, _create_agui_agent) |
| 107 | + agui_manager.register_service(APP_NAME, service) |
| 108 | + agui_manager.set_app(app) |
| 109 | + return app |
| 110 | + |
| 111 | + |
| 112 | +app = create_app() |
| 113 | + |
| 114 | + |
| 115 | +def serve(host: str = HOST, port: int = PORT) -> None: |
| 116 | + """Start the FastAPI + AG-UI server.""" |
| 117 | + print(f"Plan Mode AG-UI demo: http://{host}:{port}/") |
| 118 | + print(f"Agent endpoint: http://{host}:{port}{AGENT_URI}") |
| 119 | + print(f"Health check: http://{host}:{port}/health") |
| 120 | + agui_manager.run(host, port) |
| 121 | + |
| 122 | + |
| 123 | +def _parse_args() -> argparse.Namespace: |
| 124 | + parser = argparse.ArgumentParser(description="Plan Mode AG-UI browser demo") |
| 125 | + parser.add_argument("--host", default=HOST, help=f"bind address (default: {HOST})") |
| 126 | + parser.add_argument("--port", type=int, default=PORT, help=f"listen port (default: {PORT})") |
| 127 | + return parser.parse_args() |
| 128 | + |
| 129 | + |
| 130 | +if __name__ == "__main__": |
| 131 | + args = _parse_args() |
| 132 | + serve(host=args.host, port=args.port) |
0 commit comments