-
-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathchatbot.py
More file actions
353 lines (301 loc) · 9.76 KB
/
chatbot.py
File metadata and controls
353 lines (301 loc) · 9.76 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
"""
API router for chatbot interactions.
Defines the RESTful endpoints.
This module acts as a controller connecting the HTTP layer
to the chat service logic.
"""
# =========================
# Standard library imports
# =========================
import json
import logging
import asyncio
# =========================
# Third-party imports
# =========================
from typing import List, Optional
from fastapi import (
APIRouter,
HTTPException,
Response,
WebSocket,
WebSocketDisconnect,
status,
UploadFile,
File,
Form,
BackgroundTasks
)
# =========================
# Local application imports
# =========================
from api.models.schemas import (
ChatResponse,
DeleteResponse,
MessageHistoryResponse,
SessionResponse,
FileAttachment,
SupportedExtensionsResponse,
)
from api.services.chat_service import (
get_chatbot_reply,
get_chatbot_reply_stream,
)
from api.services.memory import (
delete_session,
get_session,
session_exists,
persist_session,
init_session,
)
from api.services.file_service import (
process_uploaded_file,
get_supported_extensions,
FileProcessingError,
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# --- Optional dependency checks (feature flags) ---
LLM_AVAILABLE = False # pylint: disable=invalid-name
try:
import llama_cpp # noqa: F401 # pylint: disable=unused-import
LLM_AVAILABLE = True # pylint: disable=invalid-name
except ImportError:
logger.warning("LLM not available - running in API-only mode")
RETRIEVAL_AVAILABLE = False # pylint: disable=invalid-name
try:
import retriv # noqa: F401 # pylint: disable=unused-import
RETRIEVAL_AVAILABLE = True # pylint: disable=invalid-name
except ImportError:
logger.warning("Retrieval not available - limited functionality")
router = APIRouter()
# =========================
# WebSocket Endpoints
# =========================
@router.websocket("/sessions/{session_id}/stream")
async def chatbot_stream(websocket: WebSocket, session_id: str):
"""
WebSocket endpoint for real-time token streaming.
Accepts WebSocket connections and streams chatbot responses
token-by-token for a more interactive user experience.
"""
logger.info("WebSocket connection attempt for session: %s", session_id)
await websocket.accept()
logger.info("WebSocket accepted for session: %s", session_id)
if not session_exists(session_id):
await websocket.send_text(
json.dumps({"error": "Session not found"})
)
await websocket.close()
return
try:
while True:
data = await websocket.receive_text()
message_data = json.loads(data)
user_message = message_data.get("message", "")
if not user_message:
continue
async for token in get_chatbot_reply_stream(
session_id,
user_message,
):
await websocket.send_text(
json.dumps({"token": token})
)
await websocket.send_text(
json.dumps({"end": True})
)
except WebSocketDisconnect:
logger.info(
"WebSocket disconnected for session %s",
session_id,
)
except Exception as exc: # pylint: disable=broad-exception-caught
logger.error(
"WebSocket error for session %s: %s",
session_id,
exc,
exc_info=True,
)
try:
await websocket.send_text(
json.dumps(
{"error": "An unexpected error occurred."}
)
)
except Exception: # pylint: disable=broad-exception-caught
# Connection already closed
pass
# =========================
# Session Management
# =========================
@router.post(
"/sessions",
response_model=SessionResponse,
status_code=status.HTTP_201_CREATED,
)
def start_chat(response: Response):
"""
Create a new chat session.
Returns a unique session ID that can be used for subsequent
chatbot interactions.
"""
session_id = init_session()
response.headers["Location"] = (
f"/sessions/{session_id}/message"
)
return SessionResponse(session_id=session_id)
@router.delete(
"/sessions/{session_id}",
response_model=DeleteResponse,
)
def delete_chat(session_id: str):
"""
Delete an existing chat session.
Removes all conversation history and resources associated
with the specified session.
"""
if not delete_session(session_id):
raise HTTPException(
status_code=404,
detail="Session not found.",
)
return DeleteResponse(
message=f"Session {session_id} deleted."
)
@router.get(
"/sessions/{session_id}/message",
response_model=MessageHistoryResponse,
)
def get_chat_history(session_id: str):
"""
Retrieve the conversation history for a session.
Returns the ordered list of messages exchanged in the
given session. Restores persisted sessions from disk
if they are not currently in memory.
Args:
session_id (str): The session identifier.
Returns:
MessageHistoryResponse: The session ID and message list.
"""
session = get_session(session_id)
if not session:
raise HTTPException(
status_code=404,
detail="Session not found.",
)
messages = [
{"role": msg.type, "content": msg.content}
for msg in session.chat_memory.messages
]
return MessageHistoryResponse(
session_id=session_id,
messages=messages,
)
async def _process_one_file(upload_file: UploadFile) -> FileAttachment:
"""
Asynchronously read and process a single uploaded file.
Ensures the file is closed after processing. Runs the potentially
blocking `process_uploaded_file` in a separate thread.
"""
try:
content = await upload_file.read()
processed = await asyncio.to_thread(
process_uploaded_file, content, upload_file.filename or "unknown"
)
return FileAttachment(**processed)
finally:
await upload_file.close()
@router.post(
"/sessions/{session_id}/message",
response_model=ChatResponse,
)
async def chatbot_reply(
session_id: str,
background_tasks: BackgroundTasks,
message: Optional[str] = Form(None),
files: Optional[List[UploadFile]] = File(None),
):
"""
POST endpoint to handle chatbot replies, with optional file uploads.
Receives a user message with optional file attachments and returns
the assistant's reply. This endpoint handles both standard messages
and messages with files using multipart/form-data.
If only files are provided, a default message will be used.
Supported file types:
- Text files: .txt, .log, .md, .json, .xml, .yaml, .yml, code files
- Image files: .png, .jpg, .jpeg, .gif, .webp, .bmp
Args:
session_id (str): The ID of the session from the URL path.
background_tasks (BackgroundTasks): FastAPI background tasks.
message (Optional[str]): The user's message (form field).
files (Optional[List[UploadFile]]): Optional list of uploaded files.
Returns:
ChatResponse: The chatbot's generated reply.
Raises:
HTTPException: 404 if session not found, 400 if file processing fails,
422 if neither message nor files are provided.
"""
if not session_exists(session_id):
raise HTTPException(status_code=404, detail="Session not found.")
# Validate that at least message or files are provided
has_message = message and message.strip()
has_files = files is not None and len(files) > 0
if not has_message and not has_files:
raise HTTPException(
status_code=422,
detail="Either a message or at least one file must be provided.",
)
# Process uploaded files
processed_files: List[FileAttachment] = []
if files:
tasks = [_process_one_file(f) for f in files]
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, Exception):
if isinstance(result, FileProcessingError):
raise HTTPException(status_code=400, detail=str(result)) from result
logger.error(
"Unexpected error processing file for session %s: %s",
session_id,
result,
exc_info=True,
)
raise HTTPException(
status_code=500,
detail=f"Failed to process file: {type(result).__name__}",
) from result
processed_files.append(result)
# Use default message if only files provided
final_message = (
message.strip()
if has_message
else "Please analyze the attached file(s)."
)
reply = await asyncio.to_thread(
get_chatbot_reply,
session_id,
final_message,
processed_files if processed_files else None
)
background_tasks.add_task(
persist_session,
session_id,
)
return reply
# =========================
# Utility Endpoints
# =========================
@router.get(
"/files/supported-extensions",
response_model=SupportedExtensionsResponse,
)
def get_supported_file_extensions():
"""
GET endpoint to retrieve supported file extensions for upload.
Returns:
SupportedExtensionsResponse: Lists of supported text and image extensions,
along with size limits.
"""
extensions = get_supported_extensions()
return SupportedExtensionsResponse(**extensions)