""" T6 Mem0 v2 REST API Main FastAPI application """ import logging import sys from contextlib import asynccontextmanager from fastapi import FastAPI, Request, status from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from fastapi.exceptions import RequestValidationError from api.routes import router from api.memory_service import get_memory_service from config import settings # Configure logging logging.basicConfig( level=getattr(logging, settings.log_level.upper()), format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.StreamHandler(sys.stdout) ] ) logger = logging.getLogger(__name__) @asynccontextmanager async def lifespan(app: FastAPI): """ Lifespan context manager for startup and shutdown events """ # Startup logger.info("Starting T6 Mem0 v2 REST API") logger.info(f"Environment: {settings.environment}") logger.info(f"API Host: {settings.api_host}:{settings.api_port}") try: # Initialize memory service service = get_memory_service() logger.info("Memory service initialized successfully") yield except Exception as e: logger.error(f"Failed to initialize application: {e}") raise finally: # Shutdown logger.info("Shutting down T6 Mem0 v2 REST API") # Create FastAPI application app = FastAPI( title="T6 Mem0 v2 API", description=""" Memory system for LLM applications based on mem0.ai ## Features - **Add Memory**: Store conversation memories with semantic understanding - **Search Memory**: Find relevant memories using semantic search - **Manage Memory**: Update and delete memories - **Multi-Agent**: Support for user, agent, and run-specific memories - **Graph Relationships**: Neo4j integration for memory relationships ## Authentication All endpoints (except /health) require Bearer token authentication. Include your API key in the Authorization header: ``` Authorization: Bearer YOUR_API_KEY ``` """, version="0.1.0", docs_url="/docs", redoc_url="/redoc", openapi_url="/openapi.json", lifespan=lifespan ) # CORS middleware app.add_middleware( CORSMiddleware, allow_origins=[ "http://localhost:3000", "http://localhost:8080", "http://localhost:5678", # n8n ], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # Exception handlers @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc: RequestValidationError): """Handle validation errors""" logger.warning(f"Validation error: {exc.errors()}") return JSONResponse( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content={ "status": "error", "error": "Validation failed", "detail": exc.errors() } ) @app.exception_handler(Exception) async def general_exception_handler(request: Request, exc: Exception): """Handle general exceptions""" logger.error(f"Unhandled exception: {exc}", exc_info=True) return JSONResponse( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, content={ "status": "error", "error": "Internal server error", "detail": str(exc) if settings.environment == "development" else "An error occurred" } ) # Include routers app.include_router(router) # Root endpoint @app.get( "/", summary="API Root", description="Get API information", tags=["info"] ) async def root(): """API root endpoint""" return { "name": "T6 Mem0 v2 API", "version": "0.1.0", "status": "running", "docs": "/docs", "health": "/v1/health" } # Run with uvicorn if __name__ == "__main__": import uvicorn uvicorn.run( "api.main:app", host=settings.api_host, port=settings.api_port, reload=settings.environment == "development", log_level=settings.log_level.lower() )