-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
186 lines (153 loc) · 5.5 KB
/
main.py
File metadata and controls
186 lines (153 loc) · 5.5 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""
Main FastAPI application for the LangGraph Chatbot API Service
"""
import os
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from dotenv import load_dotenv
from datetime import datetime
from session_manager import SessionManager
from chatbot_service import ChatbotService
from endpoints import router, initialize_services
from models import ErrorResponse, ErrorDetail
# Load environment variables
load_dotenv()
# Global service instances
session_manager_instance: SessionManager = None
chatbot_service_instance: ChatbotService = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifespan context manager for startup and shutdown events"""
# Startup
global session_manager_instance, chatbot_service_instance
# Initialize services
try:
# Get OpenAI API key
openai_api_key = os.getenv("OPENAI_API_KEY")
if not openai_api_key:
raise ValueError("OPENAI_API_KEY environment variable is required")
# Initialize session manager
session_timeout_hours = int(os.getenv("SESSION_TIMEOUT_HOURS", "1"))
session_manager_instance = SessionManager(session_timeout_hours=session_timeout_hours)
# Initialize chatbot service
model = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
temperature = float(os.getenv("OPENAI_TEMPERATURE", "0"))
chatbot_service_instance = ChatbotService(
openai_api_key=openai_api_key,
model=model,
temperature=temperature
)
# Initialize endpoints with service instances
initialize_services(session_manager_instance, chatbot_service_instance)
print(f"✅ Chatbot API Service initialized successfully")
print(f" - Model: {model}")
print(f" - Temperature: {temperature}")
print(f" - Session timeout: {session_timeout_hours} hours")
# Start background task for session cleanup
cleanup_task = asyncio.create_task(session_cleanup_task())
except Exception as e:
print(f"❌ Failed to initialize services: {str(e)}")
raise
yield
# Shutdown
try:
cleanup_task.cancel()
print("🛑 Chatbot API Service shutting down...")
except Exception as e:
print(f"⚠️ Error during shutdown: {str(e)}")
async def session_cleanup_task():
"""Background task to cleanup expired sessions"""
while True:
try:
if session_manager_instance:
cleaned_count = session_manager_instance.cleanup_expired_sessions()
if cleaned_count > 0:
print(f"🧹 Cleaned up {cleaned_count} expired sessions")
# Run cleanup every 30 minutes
await asyncio.sleep(1800)
except asyncio.CancelledError:
print("🛑 Session cleanup task cancelled")
break
except Exception as e:
print(f"⚠️ Error in session cleanup: {str(e)}")
await asyncio.sleep(60) # Wait 1 minute before retrying
# Create FastAPI app
app = FastAPI(
title="LangGraph Chatbot API",
description="A simple REST API service for the LangGraph chatbot using OpenAI GPT-4o-mini",
version="1.0.0",
lifespan=lifespan
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure this properly for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include API routes
app.include_router(router)
# Global exception handler
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
"""Handle HTTP exceptions and return standardized error format"""
error_response = ErrorResponse(
error=ErrorDetail(
code=f"HTTP_{exc.status_code}",
message=exc.detail,
details=None
),
timestamp=datetime.utcnow()
)
return JSONResponse(
status_code=exc.status_code,
content=error_response.model_dump(mode='json')
)
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
"""Handle general exceptions"""
error_response = ErrorResponse(
error=ErrorDetail(
code="INTERNAL_SERVER_ERROR",
message="An unexpected error occurred",
details=str(exc) if os.getenv("DEBUG", "false").lower() == "true" else None
),
timestamp=datetime.utcnow()
)
return JSONResponse(
status_code=500,
content=error_response.model_dump(mode='json')
)
# Root endpoint
@app.get("/")
async def root():
"""Root endpoint with API information"""
return {
"message": "LangGraph Chatbot API Service",
"version": "1.0.0",
"docs": "/docs",
"health": "/api/health",
"timestamp": datetime.utcnow()
}
if __name__ == "__main__":
import uvicorn
# Configuration
host = os.getenv("HOST", "0.0.0.0")
port = int(os.getenv("PORT", "8000"))
debug = os.getenv("DEBUG", "false").lower() == "true"
print(f"🚀 Starting LangGraph Chatbot API Service...")
print(f" - Host: {host}")
print(f" - Port: {port}")
print(f" - Debug: {debug}")
print(f" - Docs: http://{host}:{port}/docs")
uvicorn.run(
"main:app",
host=host,
port=port,
reload=debug,
log_level="info"
)