-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpoints.py
More file actions
193 lines (164 loc) · 5.82 KB
/
endpoints.py
File metadata and controls
193 lines (164 loc) · 5.82 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
187
188
189
190
191
192
193
"""
FastAPI endpoints for the chatbot API service
"""
from datetime import datetime
from typing import List
from fastapi import APIRouter, HTTPException, Depends
from models import (
ChatRequest, ChatResponse, SessionCreateResponse,
SessionResponse, HealthResponse, ErrorResponse,
MessageRole, ChatMessage
)
from session_manager import SessionManager
from chatbot_service import ChatbotService
# Create router
router = APIRouter()
# Global instances (will be initialized in main.py)
session_manager: SessionManager = None
chatbot_service: ChatbotService = None
def get_session_manager() -> SessionManager:
"""Dependency to get session manager instance"""
if session_manager is None:
raise HTTPException(status_code=500, detail="Session manager not initialized")
return session_manager
def get_chatbot_service() -> ChatbotService:
"""Dependency to get chatbot service instance"""
if chatbot_service is None:
raise HTTPException(status_code=500, detail="Chatbot service not initialized")
return chatbot_service
@router.post("/api/chat", response_model=ChatResponse)
async def chat_endpoint(
request: ChatRequest,
session_mgr: SessionManager = Depends(get_session_manager),
chatbot: ChatbotService = Depends(get_chatbot_service)
):
"""
Send a message to the chatbot and receive a response
"""
try:
# Get or create session
session_id = request.session_id
if session_id is None:
# Create new session
session_id = session_mgr.create_session()
else:
# Validate existing session
if not session_mgr.session_exists(session_id):
raise HTTPException(
status_code=404,
detail=f"Session {session_id} not found or expired"
)
# Add user message to session
session_mgr.add_message_to_session(session_id, MessageRole.USER, request.message)
# Get conversation history
messages = session_mgr.get_session_messages(session_id)
if messages is None:
raise HTTPException(
status_code=404,
detail=f"Session {session_id} not found"
)
# Generate response from chatbot
try:
bot_response = chatbot.generate_response(messages)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to generate response: {str(e)}"
)
# Add bot response to session
session_mgr.add_message_to_session(session_id, MessageRole.ASSISTANT, bot_response)
return ChatResponse(
response=bot_response,
session_id=session_id,
timestamp=datetime.utcnow()
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Internal server error: {str(e)}"
)
@router.post("/api/sessions", response_model=SessionCreateResponse)
async def create_session_endpoint(
session_mgr: SessionManager = Depends(get_session_manager)
):
"""
Create a new chat session
"""
try:
session_id = session_mgr.create_session()
return SessionCreateResponse(
session_id=session_id,
created_at=datetime.utcnow()
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to create session: {str(e)}"
)
@router.get("/api/sessions/{session_id}", response_model=SessionResponse)
async def get_session_endpoint(
session_id: str,
session_mgr: SessionManager = Depends(get_session_manager)
):
"""
Retrieve conversation history for a specific session
"""
try:
# Validate session ID format (basic UUID validation)
if len(session_id) != 36 or session_id.count('-') != 4:
raise HTTPException(
status_code=400,
detail="Invalid session ID format"
)
session = session_mgr.get_session(session_id)
if session is None:
raise HTTPException(
status_code=404,
detail=f"Session {session_id} not found or expired"
)
return SessionResponse(
session_id=session_id,
messages=session.get_messages(),
created_at=session.created_at
)
except HTTPException:
raise
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to retrieve session: {str(e)}"
)
@router.get("/api/health", response_model=HealthResponse)
async def health_check_endpoint(
chatbot: ChatbotService = Depends(get_chatbot_service),
session_mgr: SessionManager = Depends(get_session_manager)
):
"""
API service health monitoring
"""
try:
# Perform health checks
chatbot_healthy = chatbot.health_check()
session_mgr_healthy = session_mgr is not None
if chatbot_healthy and session_mgr_healthy:
status = "healthy"
else:
status = "unhealthy"
return HealthResponse(
status=status,
timestamp=datetime.utcnow(),
version="1.0.0"
)
except Exception as e:
raise HTTPException(
status_code=503,
detail=f"Service unavailable: {str(e)}"
)
# Utility function to initialize global instances
def initialize_services(session_manager_instance: SessionManager, chatbot_service_instance: ChatbotService):
"""Initialize global service instances"""
global session_manager, chatbot_service
session_manager = session_manager_instance
chatbot_service = chatbot_service_instance