Complete implementation: REST API, MCP server, and documentation
Implementation Summary:
- REST API with FastAPI (complete CRUD operations)
- MCP Server with Python MCP SDK (7 tools)
- Supabase migrations (pgvector setup)
- Docker Compose orchestration
- Mintlify documentation site
- Environment configuration
- Shared config module
REST API Features:
- POST /v1/memories/ - Add memory
- GET /v1/memories/search - Semantic search
- GET /v1/memories/{id} - Get memory
- GET /v1/memories/user/{user_id} - User memories
- PATCH /v1/memories/{id} - Update memory
- DELETE /v1/memories/{id} - Delete memory
- GET /v1/health - Health check
- GET /v1/stats - Statistics
- Bearer token authentication
- OpenAPI documentation
MCP Server Tools:
- add_memory - Add from messages
- search_memories - Semantic search
- get_memory - Retrieve by ID
- get_all_memories - List all
- update_memory - Update content
- delete_memory - Delete by ID
- delete_all_memories - Bulk delete
Infrastructure:
- Neo4j 5.26 with APOC/GDS
- Supabase pgvector integration
- Docker network: localai
- Health checks and monitoring
- Structured logging
Documentation:
- Introduction page
- Quickstart guide
- Architecture deep dive
- Mintlify configuration
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
158
api/main.py
Normal file
158
api/main.py
Normal file
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
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()
|
||||
)
|
||||
Reference in New Issue
Block a user