The API module provides REST and WebSocket endpoints for the DeepTutor system, enabling frontend-backend communication and real-time streaming.
The API module is built on FastAPI and provides:
- REST API endpoints for standard HTTP requests
- WebSocket endpoints for real-time streaming
- Static file serving for generated artifacts
- CORS middleware for cross-origin requests
- Unified error handling and logging
api/
├── __init__.py
├── main.py # FastAPI application setup
├── run_server.py # Server startup script
├── routers/ # API route modules
│ ├── solve.py # Problem solving endpoints
│ ├── question.py # Question generation endpoints
│ ├── research.py # Research endpoints
│ ├── knowledge.py # Knowledge base endpoints
│ ├── guide.py # Guided learning endpoints
│ ├── co_writer.py # Co-Writer endpoints
│ ├── notebook.py # Notebook endpoints
│ ├── ideagen.py # Idea generation endpoints
│ ├── dashboard.py # Dashboard endpoints
│ ├── settings.py # Settings endpoints
│ └── system.py # System endpoints
└── utils/ # API utilities
├── history.py # Activity history management
├── log_interceptor.py # Log interception for streaming
├── notebook_manager.py # Notebook management
├── progress_broadcaster.py # Progress broadcasting
└── task_id_manager.py # Task ID management
FastAPI Application Setup
- Creates FastAPI app instance
- Configures CORS middleware
- Mounts static file directory for artifacts
- Includes all router modules
- Initializes user directories on startup
Key Features:
- Static file serving:
/api/outputs/serves files fromdata/user/ - CORS enabled for all origins (configurable for production)
- Lifecycle management for graceful startup/shutdown
Each router module handles endpoints for a specific feature:
WS /api/v1/solve- WebSocket endpoint for real-time problem solving
WS /api/v1/question/generate- WebSocket endpoint for question generation
WS /api/v1/research/run- WebSocket endpoint for research execution
GET /api/v1/knowledge/list- List knowledge basesGET /api/v1/knowledge/{kb_name}- Get knowledge base detailsPOST /api/v1/knowledge/create- Create knowledge basePOST /api/v1/knowledge/{kb_name}/upload- Upload documents
POST /api/v1/guide/create_session- Create learning sessionPOST /api/v1/guide/start- Start learningPOST /api/v1/guide/next- Move to next knowledge pointPOST /api/v1/guide/chat- Send chat message
POST /api/v1/co_writer/edit- Text editingPOST /api/v1/co_writer/automark- Automatic annotationPOST /api/v1/co_writer/narrate- Generate narration
GET /api/v1/notebook/list- List notebooksPOST /api/v1/notebook/create- Create notebookGET /api/v1/notebook/{id}- Get notebook detailsPUT /api/v1/notebook/{id}- Update notebookDELETE /api/v1/notebook/{id}- Delete notebook
GET /api/v1/dashboard/recent- Get recent activities
Activity History Management
Tracks user activities across modules:
- Solve activities
- Question generation activities
- Research activities
- Automatic history saving and retrieval
Log Interception for Streaming
Intercepts logs from agents and broadcasts them via WebSocket for real-time updates.
Progress Broadcasting
Broadcasts progress updates during long-running operations.
Task ID Management
Manages unique task IDs for tracking operations.
All WebSocket endpoints follow a similar pattern:
- Connection: Client connects to WebSocket endpoint
- Initial Message: Client sends initial request with parameters
- Streaming: Server streams progress updates and results
- Completion: Server sends final result and closes connection
Example (Solve):
const ws = new WebSocket('ws://localhost:8001/api/v1/solve');
ws.onopen = () => {
ws.send(JSON.stringify({
question: "Your question here",
kb_name: "ai_textbook"
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log(data);
};Standard REST API endpoints return JSON responses:
Example (Knowledge Base List):
curl http://localhost:8001/api/v1/knowledge/listThe API serves static files from data/user/ via /api/outputs/:
- URL Pattern:
/api/outputs/{module}/{path} - Physical Path:
data/user/{module}/{path}
Example:
- URL:
/api/outputs/solve/solve_20250101_120000/final_answer.md - Path:
data/user/solve/solve_20250101_120000/final_answer.md
Configured in config/main.yaml:
server:
backend_port: 8001
frontend_port: 3782Currently allows all origins. For production, update in main.py:
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"], # Specific frontend URL
...
)python src/api/run_server.pyuvicorn src.api.main:app --host 0.0.0.0 --port 8001 --reloadpython src/api/main.py- Core:
src/core/- Configuration and logging - Agents:
src/agents/- Agent implementations - Tools:
src/tools/- Tool implementations - Frontend:
web/- Next.js frontend
- Create or update router in
routers/ - Import and include in
main.py:from src.api.routers import my_router app.include_router(my_router.router, prefix="/api/v1", tags=["my_module"])
-
Create WebSocket endpoint in router:
@router.websocket("/my_endpoint") async def websocket_handler(websocket: WebSocket): await websocket.accept() # Handle messages
-
Use
LogInterceptorfor streaming logs:from src.api.utils.log_interceptor import LogInterceptor interceptor = LogInterceptor(websocket)
All endpoints should handle errors gracefully:
try:
# Operation
await websocket.send_json({"type": "success", "data": result})
except Exception as e:
logger.error(f"Error: {e}")
await websocket.send_json({"type": "error", "content": str(e)})API endpoints use the core logging system:
from src.core.logging import get_logger
logger = get_logger("MyAPI")- WebSocket Timeout: WebSocket connections may timeout for long operations
- Static Files: Ensure proper file permissions for static file serving
- CORS: Configure CORS properly for production environments
- Error Handling: Always handle WebSocket disconnections gracefully