forked from lightspeed-core/lightspeed-stack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconversations.py
More file actions
488 lines (423 loc) · 16.3 KB
/
conversations.py
File metadata and controls
488 lines (423 loc) · 16.3 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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
"""Handler for REST API calls to manage conversation history."""
import logging
from typing import Any
from llama_stack_client import APIConnectionError, NotFoundError
from fastapi import APIRouter, HTTPException, Request, status, Depends
from client import AsyncLlamaStackClientHolder
from configuration import configuration
from app.database import get_session
from models.database.conversations import UserConversation
from models.responses import (
ConversationResponse,
ConversationDeleteResponse,
ConversationsListResponse,
ConversationDetails,
UnauthorizedResponse,
)
from models.config import Action
from utils.endpoints import (
check_configuration_loaded,
delete_conversation,
get_auth_dependency_lazy,
validate_conversation_ownership,
)
from utils.suid import check_suid
logger = logging.getLogger("app.endpoints.handlers")
router = APIRouter(tags=["conversations"])
conversation_responses: dict[int | str, dict[str, Any]] = {
200: {
"conversation_id": "123e4567-e89b-12d3-a456-426614174000",
"chat_history": [
{
"messages": [
{"content": "Hi", "type": "user"},
{"content": "Hello!", "type": "assistant"},
],
"started_at": "2024-01-01T00:00:00Z",
"completed_at": "2024-01-01T00:00:05Z",
}
],
},
400: {
"description": "Missing or invalid credentials provided by client",
"model": UnauthorizedResponse,
},
401: {
"description": "Unauthorized: Invalid or missing Bearer token",
"model": UnauthorizedResponse,
},
404: {
"detail": {
"response": "Conversation not found",
"cause": "The specified conversation ID does not exist.",
}
},
503: {
"detail": {
"response": "Unable to connect to Llama Stack",
"cause": "Connection error.",
}
},
}
conversation_delete_responses: dict[int | str, dict[str, Any]] = {
200: {
"conversation_id": "123e4567-e89b-12d3-a456-426614174000",
"success": True,
"message": "Conversation deleted successfully",
},
400: {
"description": "Missing or invalid credentials provided by client",
"model": UnauthorizedResponse,
},
401: {
"description": "Unauthorized: Invalid or missing Bearer token",
"model": UnauthorizedResponse,
},
404: {
"detail": {
"response": "Conversation not found",
"cause": "The specified conversation ID does not exist.",
}
},
503: {
"detail": {
"response": "Unable to connect to Llama Stack",
"cause": "Connection error.",
}
},
}
conversations_list_responses: dict[int | str, dict[str, Any]] = {
200: {
"conversations": [
{
"conversation_id": "123e4567-e89b-12d3-a456-426614174000",
"created_at": "2024-01-01T00:00:00Z",
"last_message_at": "2024-01-01T00:05:00Z",
"last_used_model": "gemini/gemini-1.5-flash",
"last_used_provider": "gemini",
"message_count": 5,
},
{
"conversation_id": "456e7890-e12b-34d5-a678-901234567890",
"created_at": "2024-01-01T01:00:00Z",
"last_message_at": "2024-01-01T01:02:00Z",
"last_used_model": "gemini/gemini-2.0-flash",
"last_used_provider": "gemini",
"message_count": 2,
},
]
},
400: {
"description": "Missing or invalid credentials provided by client",
"model": UnauthorizedResponse,
},
401: {
"description": "Unauthorized: Invalid or missing Bearer token",
"model": UnauthorizedResponse,
},
503: {
"detail": {
"response": "Unable to connect to Llama Stack",
"cause": "Connection error.",
}
},
}
def simplify_session_data(session_data: dict) -> list[dict[str, Any]]:
"""Simplify session data to include only essential conversation information.
Args:
session_data: The full session data dict from llama-stack
Returns:
Simplified session data with only input_messages and output_message per turn
"""
# Create simplified structure
chat_history = []
# Extract only essential data from each turn
for turn in session_data.get("turns", []):
# Clean up input messages
cleaned_messages = []
for msg in turn.get("input_messages", []):
cleaned_msg = {
"content": msg.get("content"),
"type": msg.get("role"), # Rename role to type
}
cleaned_messages.append(cleaned_msg)
# Clean up output message
output_msg = turn.get("output_message", {})
cleaned_messages.append(
{
"content": output_msg.get("content"),
"type": output_msg.get("role"), # Rename role to type
}
)
simplified_turn = {
"messages": cleaned_messages,
"started_at": turn.get("started_at"),
"completed_at": turn.get("completed_at"),
}
chat_history.append(simplified_turn)
return chat_history
@router.get("/conversations", responses=conversations_list_responses)
async def get_conversations_list_endpoint_handler(
request: Request,
auth: Any = Depends(get_auth_dependency_lazy()),
) -> ConversationsListResponse:
"""Handle request to retrieve all conversations for the authenticated user."""
check_configuration_loaded(configuration)
user_id = auth[0]
# Get authorized actions safely
authorized_actions = getattr(request.state, 'authorized_actions', [])
logger.info("Retrieving conversations for user %s", user_id)
with get_session() as session:
try:
query = session.query(UserConversation)
filtered_query = (
query
if Action.LIST_OTHERS_CONVERSATIONS in authorized_actions
else query.filter_by(user_id=user_id)
)
user_conversations = filtered_query.all()
# Return conversation summaries with metadata
conversations = [
ConversationDetails(
conversation_id=conv.id,
created_at=conv.created_at.isoformat() if conv.created_at else None,
last_message_at=(
conv.last_message_at.isoformat()
if conv.last_message_at
else None
),
message_count=conv.message_count,
last_used_model=conv.last_used_model,
last_used_provider=conv.last_used_provider,
)
for conv in user_conversations
]
logger.info(
"Found %d conversations for user %s", len(conversations), user_id
)
return ConversationsListResponse(conversations=conversations)
except Exception as e:
logger.exception(
"Error retrieving conversations for user %s: %s", user_id, e
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={
"response": "Unknown error",
"cause": f"Unknown error while getting conversations for user {user_id}",
},
) from e
@router.get("/conversations/{conversation_id}", responses=conversation_responses)
async def get_conversation_endpoint_handler(
request: Request,
conversation_id: str,
auth: Any = Depends(get_auth_dependency_lazy()),
) -> ConversationResponse:
"""
Handle request to retrieve a conversation by ID.
Retrieve a conversation's chat history by its ID. Then fetches
the conversation session from the Llama Stack backend,
simplifies the session data to essential chat history, and
returns it in a structured response. Raises HTTP 400 for
invalid IDs, 404 if not found, 503 if the backend is
unavailable, and 500 for unexpected errors.
Parameters:
conversation_id (str): Unique identifier of the conversation to retrieve.
Returns:
ConversationResponse: Structured response containing the conversation
ID and simplified chat history.
"""
check_configuration_loaded(configuration)
# Validate conversation ID format
if not check_suid(conversation_id):
logger.error("Invalid conversation ID format: %s", conversation_id)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={
"response": "Invalid conversation ID format",
"cause": f"Conversation ID {conversation_id} is not a valid UUID",
},
)
user_id = auth[0]
# Get authorized actions safely
authorized_actions = getattr(request.state, 'authorized_actions', [])
user_conversation = validate_conversation_ownership(
user_id=user_id,
conversation_id=conversation_id,
others_allowed=(
Action.READ_OTHERS_CONVERSATIONS in authorized_actions
),
)
if user_conversation is None:
logger.warning(
"User %s attempted to read conversation %s they don't own",
user_id,
conversation_id,
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={
"response": "Access denied",
"cause": "You do not have permission to read this conversation",
},
)
agent_id = conversation_id
logger.info("Retrieving conversation %s", conversation_id)
try:
client = AsyncLlamaStackClientHolder().get_client()
agent_sessions = (await client.agents.session.list(agent_id=agent_id)).data
if not agent_sessions:
logger.error("No sessions found for conversation %s", conversation_id)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={
"response": "Conversation not found",
"cause": f"Conversation {conversation_id} could not be retrieved.",
},
)
session_id = str(agent_sessions[0].get("session_id"))
session_response = await client.agents.session.retrieve(
agent_id=agent_id, session_id=session_id
)
session_data = session_response.model_dump()
logger.info("Successfully retrieved conversation %s", conversation_id)
# Simplify the session data to include only essential conversation information
chat_history = simplify_session_data(session_data)
return ConversationResponse(
conversation_id=conversation_id,
chat_history=chat_history,
)
except APIConnectionError as e:
logger.error("Unable to connect to Llama Stack: %s", e)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail={
"response": "Unable to connect to Llama Stack",
"cause": str(e),
},
) from e
except NotFoundError as e:
logger.error("Conversation not found: %s", e)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={
"response": "Conversation not found",
"cause": f"Conversation {conversation_id} could not be retrieved: {str(e)}",
},
) from e
except HTTPException:
raise
except Exception as e:
# Handle case where session doesn't exist or other errors
logger.exception("Error retrieving conversation %s: %s", conversation_id, e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={
"response": "Unknown error",
"cause": f"Unknown error while getting conversation {conversation_id} : {str(e)}",
},
) from e
@router.delete(
"/conversations/{conversation_id}", responses=conversation_delete_responses
)
async def delete_conversation_endpoint_handler(
request: Request,
conversation_id: str,
auth: Any = Depends(get_auth_dependency_lazy()),
) -> ConversationDeleteResponse:
"""
Handle request to delete a conversation by ID.
Validates the conversation ID format and attempts to delete the
corresponding session from the Llama Stack backend. Raises HTTP
errors for invalid IDs, not found conversations, connection
issues, or unexpected failures.
Returns:
ConversationDeleteResponse: Response indicating the result of the deletion operation.
"""
check_configuration_loaded(configuration)
# Validate conversation ID format
if not check_suid(conversation_id):
logger.error("Invalid conversation ID format: %s", conversation_id)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail={
"response": "Invalid conversation ID format",
"cause": f"Conversation ID {conversation_id} is not a valid UUID",
},
)
user_id = auth[0]
# Get authorized actions safely
authorized_actions = getattr(request.state, 'authorized_actions', [])
user_conversation = validate_conversation_ownership(
user_id=user_id,
conversation_id=conversation_id,
others_allowed=(
Action.DELETE_OTHERS_CONVERSATIONS in authorized_actions
),
)
if user_conversation is None:
logger.warning(
"User %s attempted to delete conversation %s they don't own",
user_id,
conversation_id,
)
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={
"response": "Access denied",
"cause": "You do not have permission to delete this conversation",
},
)
agent_id = conversation_id
logger.info("Deleting conversation %s", conversation_id)
try:
# Get Llama Stack client
client = AsyncLlamaStackClientHolder().get_client()
agent_sessions = (await client.agents.session.list(agent_id=agent_id)).data
if not agent_sessions:
# If no sessions are found, do not raise an error, just return a success response
logger.info("No sessions found for conversation %s", conversation_id)
return ConversationDeleteResponse(
conversation_id=conversation_id,
success=True,
response="Conversation deleted successfully",
)
session_id = str(agent_sessions[0].get("session_id"))
await client.agents.session.delete(agent_id=agent_id, session_id=session_id)
logger.info("Successfully deleted conversation %s", conversation_id)
delete_conversation(conversation_id=conversation_id)
return ConversationDeleteResponse(
conversation_id=conversation_id,
success=True,
response="Conversation deleted successfully",
)
except APIConnectionError as e:
logger.error("Unable to connect to Llama Stack: %s", e)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail={
"response": "Unable to connect to Llama Stack",
"cause": str(e),
},
) from e
except NotFoundError as e:
logger.error("Conversation not found: %s", e)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={
"response": "Conversation not found",
"cause": f"Conversation {conversation_id} could not be deleted: {str(e)}",
},
) from e
except HTTPException:
raise
except Exception as e:
# Handle case where session doesn't exist or other errors
logger.exception("Error deleting conversation %s: %s", conversation_id, e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail={
"response": "Unknown error",
"cause": f"Unknown error while deleting conversation {conversation_id} : {str(e)}",
},
) from e