|
1 | 1 | """FastAPI application for agentevals REST API.""" |
2 | 2 |
|
| 3 | +from __future__ import annotations |
| 4 | + |
3 | 5 | import asyncio |
4 | 6 | import json |
5 | 7 | import logging |
6 | 8 | import os |
7 | 9 | from contextlib import asynccontextmanager |
8 | 10 | from pathlib import Path |
| 11 | +from typing import TYPE_CHECKING |
9 | 12 |
|
10 | 13 | from fastapi import FastAPI |
11 | 14 | from fastapi.middleware.cors import CORSMiddleware |
|
17 | 20 | from .debug_routes import debug_router |
18 | 21 | from .routes import router |
19 | 22 |
|
| 23 | +if TYPE_CHECKING: |
| 24 | + from ..streaming.ws_server import StreamingTraceManager |
| 25 | + |
20 | 26 | try: |
21 | 27 | from dotenv import load_dotenv |
22 | 28 |
|
|
27 | 33 | pass |
28 | 34 |
|
29 | 35 |
|
30 | | -@asynccontextmanager |
31 | | -async def lifespan(app: FastAPI): |
32 | | - log_level_str = os.getenv("AGENTEVALS_LOG_LEVEL", "INFO").upper() |
33 | | - log_level = getattr(logging, log_level_str, logging.INFO) |
34 | | - logging.basicConfig( |
35 | | - level=log_level, |
36 | | - format="%(levelname)s:%(name)s:%(message)s", |
37 | | - force=True, |
| 36 | +def _build_lifespan(): |
| 37 | + @asynccontextmanager |
| 38 | + async def lifespan(app: FastAPI): |
| 39 | + log_level_str = os.getenv("AGENTEVALS_LOG_LEVEL", "INFO").upper() |
| 40 | + log_level = getattr(logging, log_level_str, logging.INFO) |
| 41 | + logging.basicConfig( |
| 42 | + level=log_level, |
| 43 | + format="%(levelname)s:%(name)s:%(message)s", |
| 44 | + force=True, |
| 45 | + ) |
| 46 | + ae_logger = logging.getLogger("agentevals") |
| 47 | + ae_logger.setLevel(log_level) |
| 48 | + if log_buffer not in ae_logger.handlers: |
| 49 | + log_buffer.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s")) |
| 50 | + ae_logger.addHandler(log_buffer) |
| 51 | + mgr = getattr(app.state, "trace_manager", None) |
| 52 | + if mgr: |
| 53 | + mgr.start_cleanup_task() |
| 54 | + yield |
| 55 | + if mgr: |
| 56 | + await mgr.shutdown() |
| 57 | + ae_logger.removeHandler(log_buffer) |
| 58 | + |
| 59 | + return lifespan |
| 60 | + |
| 61 | + |
| 62 | +def create_app( |
| 63 | + *, |
| 64 | + trace_manager: StreamingTraceManager | None = None, |
| 65 | + enable_streaming: bool = False, |
| 66 | +) -> FastAPI: |
| 67 | + """Create the main agentevals API app.""" |
| 68 | + app = FastAPI( |
| 69 | + title="agentevals API", |
| 70 | + version=__version__, |
| 71 | + description="REST API for evaluating agent traces using ADK's scoring framework", |
| 72 | + lifespan=_build_lifespan(), |
38 | 73 | ) |
39 | | - ae_logger = logging.getLogger("agentevals") |
40 | | - ae_logger.setLevel(log_level) |
41 | | - if log_buffer not in ae_logger.handlers: |
42 | | - log_buffer.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s")) |
43 | | - ae_logger.addHandler(log_buffer) |
44 | | - mgr = getattr(app.state, "trace_manager", None) |
45 | | - if mgr: |
46 | | - mgr.start_cleanup_task() |
47 | | - yield |
48 | | - if mgr: |
49 | | - await mgr.shutdown() |
50 | | - ae_logger.removeHandler(log_buffer) |
51 | | - |
52 | | - |
53 | | -app = FastAPI( |
54 | | - title="agentevals API", |
55 | | - version=__version__, |
56 | | - description="REST API for evaluating agent traces using ADK's scoring framework", |
57 | | - lifespan=lifespan, |
58 | | -) |
59 | | - |
60 | | -app.add_middleware( |
61 | | - CORSMiddleware, |
62 | | - allow_origins=["http://localhost:5173", "http://localhost:5174"], |
63 | | - allow_credentials=True, |
64 | | - allow_methods=["*"], |
65 | | - allow_headers=["*"], |
66 | | - expose_headers=["*"], |
67 | | -) |
68 | | - |
69 | | -app.include_router(router, prefix="/api") |
70 | | -app.include_router(debug_router, prefix="/api/debug") |
71 | | - |
72 | | -_live_mode = os.getenv("AGENTEVALS_LIVE") == "1" |
73 | | - |
74 | | -if _live_mode: |
75 | | - from fastapi import Request as _Request |
76 | | - from fastapi import WebSocket |
77 | 74 |
|
78 | | - from ..streaming.ws_server import StreamingTraceManager |
79 | | - from .streaming_routes import streaming_router |
80 | | - |
81 | | - app.include_router(streaming_router, prefix="/api/streaming") |
82 | | - app.state.trace_manager = StreamingTraceManager() |
83 | | - |
84 | | - @app.websocket("/ws/traces") |
85 | | - async def websocket_endpoint(websocket: WebSocket): |
86 | | - await websocket.app.state.trace_manager.handle_connection(websocket) |
87 | | - |
88 | | - @app.get("/stream/ui-updates") |
89 | | - async def ui_updates_stream(request: _Request): |
90 | | - mgr = request.app.state.trace_manager |
91 | | - |
92 | | - async def event_generator(): |
93 | | - queue = mgr.register_sse_client() |
94 | | - try: |
95 | | - while True: |
96 | | - event = await queue.get() |
97 | | - if event is None: |
98 | | - break |
99 | | - yield f"data: {json.dumps(event)}\n\n" |
100 | | - except asyncio.CancelledError: |
101 | | - pass |
102 | | - finally: |
103 | | - mgr.unregister_sse_client(queue) |
104 | | - |
105 | | - return StreamingResponse( |
106 | | - event_generator(), |
107 | | - media_type="text/event-stream", |
108 | | - headers={ |
109 | | - "Cache-Control": "no-cache", |
110 | | - "Connection": "keep-alive", |
111 | | - }, |
112 | | - ) |
| 75 | + app.add_middleware( |
| 76 | + CORSMiddleware, |
| 77 | + allow_origins=["http://localhost:5173", "http://localhost:5174"], |
| 78 | + allow_credentials=True, |
| 79 | + allow_methods=["*"], |
| 80 | + allow_headers=["*"], |
| 81 | + expose_headers=["*"], |
| 82 | + ) |
| 83 | + |
| 84 | + app.include_router(router, prefix="/api") |
| 85 | + app.include_router(debug_router, prefix="/api/debug") |
| 86 | + |
| 87 | + if trace_manager is not None: |
| 88 | + app.state.trace_manager = trace_manager |
| 89 | + |
| 90 | + if enable_streaming: |
| 91 | + if trace_manager is None: |
| 92 | + raise ValueError("enable_streaming requires a trace_manager") |
| 93 | + |
| 94 | + from fastapi import Request as _Request |
| 95 | + from fastapi import WebSocket |
| 96 | + |
| 97 | + from .streaming_routes import streaming_router |
| 98 | + |
| 99 | + app.include_router(streaming_router, prefix="/api/streaming") |
| 100 | + |
| 101 | + @app.websocket("/ws/traces") |
| 102 | + async def websocket_endpoint(websocket: WebSocket): |
| 103 | + await websocket.app.state.trace_manager.handle_connection(websocket) |
| 104 | + |
| 105 | + @app.get("/stream/ui-updates") |
| 106 | + async def ui_updates_stream(request: _Request): |
| 107 | + mgr = request.app.state.trace_manager |
| 108 | + |
| 109 | + async def event_generator(): |
| 110 | + queue = mgr.register_sse_client() |
| 111 | + try: |
| 112 | + while True: |
| 113 | + event = await queue.get() |
| 114 | + if event is None: |
| 115 | + break |
| 116 | + yield f"data: {json.dumps(event)}\n\n" |
| 117 | + except asyncio.CancelledError: |
| 118 | + pass |
| 119 | + finally: |
| 120 | + mgr.unregister_sse_client(queue) |
| 121 | + |
| 122 | + return StreamingResponse( |
| 123 | + event_generator(), |
| 124 | + media_type="text/event-stream", |
| 125 | + headers={ |
| 126 | + "Cache-Control": "no-cache", |
| 127 | + "Connection": "keep-alive", |
| 128 | + }, |
| 129 | + ) |
| 130 | + |
| 131 | + static_dir = Path(__file__).parent.parent / "_static" |
| 132 | + has_ui = static_dir.is_dir() and (static_dir / "index.html").exists() |
| 133 | + |
| 134 | + if has_ui and not os.getenv("AGENTEVALS_HEADLESS"): |
| 135 | + from fastapi.responses import FileResponse |
| 136 | + from fastapi.staticfiles import StaticFiles |
113 | 137 |
|
| 138 | + app.mount("/assets", StaticFiles(directory=static_dir / "assets"), name="ui-assets") |
114 | 139 |
|
115 | | -_static_dir = Path(__file__).parent.parent / "_static" |
116 | | -_has_ui = _static_dir.is_dir() and (_static_dir / "index.html").exists() |
| 140 | + @app.get("/") |
| 141 | + async def root(): |
| 142 | + return FileResponse(static_dir / "index.html") |
117 | 143 |
|
118 | | -if _has_ui and not os.getenv("AGENTEVALS_HEADLESS"): |
119 | | - from fastapi.responses import FileResponse |
120 | | - from fastapi.staticfiles import StaticFiles |
| 144 | + @app.get("/{path:path}") |
| 145 | + async def spa_fallback(path: str): |
| 146 | + file_path = static_dir / path |
| 147 | + if file_path.is_file(): |
| 148 | + return FileResponse(file_path) |
| 149 | + return FileResponse(static_dir / "index.html") |
121 | 150 |
|
122 | | - app.mount("/assets", StaticFiles(directory=_static_dir / "assets"), name="ui-assets") |
| 151 | + return app |
123 | 152 |
|
124 | | - @app.get("/") |
125 | | - async def root(): |
126 | | - return FileResponse(_static_dir / "index.html") |
127 | 153 |
|
128 | | - @app.get("/{path:path}") |
129 | | - async def spa_fallback(path: str): |
130 | | - file_path = _static_dir / path |
131 | | - if file_path.is_file(): |
132 | | - return FileResponse(file_path) |
133 | | - return FileResponse(_static_dir / "index.html") |
| 154 | +app = create_app() |
0 commit comments