-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver (1).py
More file actions
157 lines (130 loc) · 4.49 KB
/
Copy pathserver (1).py
File metadata and controls
157 lines (130 loc) · 4.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"""Thunders AI API Server - FastAPI application.
Provides the main FastAPI application instance with CORS middleware,
lifecycle event handlers, health check endpoint, and uvicorn configuration.
"""
import logging
import time
from contextlib import asynccontextmanager
from typing import AsyncGenerator
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from api.middleware import (
RateLimitMiddleware,
LoggingMiddleware,
AuthMiddleware,
ErrorHandlingMiddleware,
)
from api.routes import router
from api.websocket import ConnectionManager
logger = logging.getLogger(__name__)
# Global connection manager for WebSocket clients
connection_manager = ConnectionManager()
@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
"""Manage application lifecycle: startup and shutdown events.
On startup, initializes the connection manager and logs server readiness.
On shutdown, gracefully disconnects all WebSocket clients and cleans up.
"""
logger.info("Thunders AI API Server starting up...")
await connection_manager.initialize()
logger.info("Connection manager initialized successfully")
yield
logger.info("Thunders AI API Server shutting down...")
await connection_manager.shutdown()
logger.info("All connections closed. Server stopped.")
def create_app() -> FastAPI:
"""Create and configure the FastAPI application instance.
Returns:
FastAPI: Fully configured application with middleware, routes,
and lifecycle handlers.
"""
application = FastAPI(
title="Thunders AI API",
description=(
"Production-grade AI API supporting chat completions, vision analysis, "
"speech processing, and robotics navigation. Compatible with OpenAI API format."
),
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
lifespan=lifespan,
)
# --- CORS Middleware ---
application.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- Custom Middleware Stack ---
application.add_middleware(ErrorHandlingMiddleware)
application.add_middleware(AuthMiddleware)
application.add_middleware(LoggingMiddleware)
application.add_middleware(RateLimitMiddleware)
# --- Include API Routes ---
application.include_router(router, prefix="/api/v1")
# --- Health Check Endpoint ---
@application.get("/health", tags=["Health"])
async def health_check() -> JSONResponse:
"""Return the health status of the API server.
Returns:
JSONResponse: Server health information including status,
version, and uptime.
"""
return JSONResponse(
status_code=200,
content={
"status": "healthy",
"version": "1.0.0",
"service": "thunders-ai-api",
"timestamp": time.time(),
},
)
# --- Root Endpoint ---
@application.get("/", tags=["Root"])
async def root() -> JSONResponse:
"""Root endpoint providing API overview and documentation links.
Returns:
JSONResponse: Welcome message with links to docs and health check.
"""
return JSONResponse(
status_code=200,
content={
"message": "Welcome to Thunders AI API",
"documentation": "/docs",
"health_check": "/health",
"api_version": "v1",
},
)
return application
# Create the default application instance
app = create_app()
def run_server(
host: str = "0.0.0.0",
port: int = 8000,
workers: int = 1,
log_level: str = "info",
reload: bool = False,
) -> None:
"""Run the API server using uvicorn.
Args:
host: Bind address for the server.
port: Port number for the server.
workers: Number of worker processes.
log_level: Logging level (debug, info, warning, error, critical).
reload: Enable auto-reload for development.
"""
logger.info("Starting Thunders AI API Server on %s:%d", host, port)
uvicorn.run(
"api.server:app",
host=host,
port=port,
workers=workers,
log_level=log_level,
reload=reload,
)
if __name__ == "__main__":
run_server(reload=True)