# -*- coding: utf-8 -*- """ FastAPI Application - REST API for EvoTraders Provides HTTP endpoints for: - Agent management - Workspace management - Tool guard operations - Health checks """ from contextlib import asynccontextmanager from pathlib import Path from typing import AsyncGenerator from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from backend.api import agents_router, workspaces_router, guard_router, runtime_router from backend.agents import AgentFactory, WorkspaceManager, get_registry # Global instances (initialized on startup) agent_factory: AgentFactory | None = None workspace_manager: WorkspaceManager | None = None @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator: """ Application lifespan manager. Initializes global services on startup and cleans up on shutdown. """ global agent_factory, workspace_manager # Startup: Initialize services project_root = Path(__file__).parent.parent # Initialize workspace manager workspace_manager = WorkspaceManager(project_root=project_root) # Initialize agent factory agent_factory = AgentFactory(project_root=project_root) # Ensure workspaces root exists agent_factory.workspaces_root.mkdir(parents=True, exist_ok=True) # Get or create global registry registry = get_registry() print(f"✓ EvoTraders API started") print(f" - Workspaces root: {agent_factory.workspaces_root}") print(f" - Registered agents: {registry.get_agent_count()}") yield # Shutdown: Cleanup print("✓ EvoTraders API shutting down") # Create FastAPI application app = FastAPI( title="EvoTraders API", description="REST API for the EvoTraders multi-agent trading system", version="0.1.0", lifespan=lifespan, ) # CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], # Configure appropriately for production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Health check endpoint @app.get("/health") async def health_check(): """Health check endpoint.""" registry = get_registry() return { "status": "healthy", "version": "0.1.0", "agents_registered": registry.get_agent_count(), "workspaces_available": len(workspace_manager.list_workspaces()) if workspace_manager else 0, } # API status endpoint @app.get("/api/status") async def api_status(): """Get API status and system information.""" registry = get_registry() stats = registry.get_stats() return { "status": "operational", "registry": stats, } # Include routers app.include_router(workspaces_router) app.include_router(agents_router) app.include_router(guard_router) app.include_router(runtime_router) # Main entry point for running with uvicorn if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)