AgentGraph / backend /app.py
wu981526092's picture
🎯 Add Automatic Sample Data System for New Users
9e60d50
raw
history blame
3.07 kB
"""
FastAPI Application Definition
This module defines the FastAPI application and routes for the agent monitoring system.
"""
import logging
import os
from pathlib import Path
import sys
from fastapi import FastAPI, Request, status
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse, HTMLResponse
# Add server module to path if not already there
server_dir = os.path.dirname(os.path.abspath(__file__))
if server_dir not in sys.path:
sys.path.append(server_dir)
# Import from backend modules
from backend.server_config import ensure_directories
from backend.routers import (
knowledge_graphs,
traces,
tasks,
temporal_graphs,
graph_comparison,
agentgraph,
example_traces,
methods,
observability,
)
# Setup logging
logger = logging.getLogger("agent_monitoring_server")
# Create FastAPI app
app = FastAPI(title="Agent Monitoring System", version="1.0.0")
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Mount datasets directory for accessing json files
app.mount("/data", StaticFiles(directory="datasets"), name="data")
# Include routers
app.include_router(traces.router)
app.include_router(knowledge_graphs.router)
app.include_router(agentgraph.router)
app.include_router(tasks.router)
app.include_router(temporal_graphs.router)
app.include_router(graph_comparison.router)
app.include_router(example_traces.router)
app.include_router(methods.router)
app.include_router(observability.router)
# Start background scheduler for automated tasks
# scheduler_service.start()
@app.on_event("startup")
async def startup_event():
"""Start background services on app startup"""
logger.info("βœ… Backend server starting...")
# πŸ”§ Create necessary directories
ensure_directories()
logger.info("πŸ“ Directory structure created")
# πŸ—„οΈ Initialize database on startup
try:
from backend.database.init_db import init_database
init_database(reset=False, force=False)
logger.info("πŸ—„οΈ Database initialized successfully")
except Exception as e:
logger.error(f"❌ Database initialization failed: {e}")
# Don't fail startup - continue with empty database
logger.info("πŸš€ Backend API available at: http://0.0.0.0:7860")
# scheduler_service.start() # This line is now commented out
@app.on_event("shutdown")
async def shutdown_event():
"""Stop background services on app shutdown"""
logger.info("Stopping background services...")
# scheduler_service.stop() # This line is now commented out
# Root redirect to React app
@app.get("/")
async def root():
return RedirectResponse(url="/agentgraph")
# Serve React app for any unmatched routes
@app.get("/app/{path:path}")
async def serve_react_app(path: str):
"""Serve the React app for client-side routing"""
return RedirectResponse(url="/agentgraph")