-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathhistory.py
More file actions
1216 lines (1038 loc) · 46.5 KB
/
Copy pathhistory.py
File metadata and controls
1216 lines (1038 loc) · 46.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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from datetime import datetime
import logging
import os
import uuid
from typing import Optional
from azure.ai.projects.aio import AIProjectClient
from azure.core.exceptions import HttpResponseError
from azure.cosmos import exceptions
from azure.cosmos.aio import CosmosClient
from fastapi import APIRouter, HTTPException, Query, Request, status
from fastapi.responses import JSONResponse
from opentelemetry import trace
from opentelemetry.trace import Status, StatusCode
# from chat import adjust_processed_data_dates
from auth.auth_utils import get_authenticated_user_details
from auth.azure_credential_utils import get_azure_credential_async
# Token usage telemetry helpers (modular, reusable)
from token_usage import track_event_if_configured, UsageAccumulator
router = APIRouter()
logger = logging.getLogger(__name__)
# Configuration variables
USE_CHAT_HISTORY_ENABLED = os.getenv("USE_CHAT_HISTORY_ENABLED", "false").strip().lower() == "true"
AZURE_COSMOSDB_DATABASE = os.getenv("AZURE_COSMOSDB_DATABASE")
AZURE_COSMOSDB_ACCOUNT = os.getenv("AZURE_COSMOSDB_ACCOUNT")
AZURE_COSMOSDB_CONVERSATIONS_CONTAINER = os.getenv("AZURE_COSMOSDB_CONVERSATIONS_CONTAINER")
AZURE_COSMOSDB_ENABLE_FEEDBACK = os.getenv("AZURE_COSMOSDB_ENABLE_FEEDBACK", "false").lower() == "true"
CHAT_HISTORY_ENABLED = (
USE_CHAT_HISTORY_ENABLED
and AZURE_COSMOSDB_ACCOUNT
and AZURE_COSMOSDB_DATABASE
and AZURE_COSMOSDB_CONVERSATIONS_CONTAINER
)
AZURE_AI_AGENT_ENDPOINT = os.getenv("AZURE_AI_AGENT_ENDPOINT")
AGENT_NAME_TITLE = os.getenv("AGENT_NAME_TITLE")
class CosmosConversationClient:
"""Client for managing conversations and messages in CosmosDB."""
def __init__(
self,
cosmosdb_endpoint: str,
credential: any,
database_name: str,
container_name: str,
enable_message_feedback: bool = False,
):
"""Initialize CosmosDB conversation client."""
self.cosmosdb_endpoint = cosmosdb_endpoint
self.credential = credential
self.database_name = database_name
self.container_name = container_name
self.enable_message_feedback = enable_message_feedback
try:
self.cosmosdb_client = CosmosClient(
self.cosmosdb_endpoint, credential=credential
)
except exceptions.CosmosHttpResponseError as e:
if e.status_code == 401:
raise ValueError("Invalid credentials") from e
else:
raise ValueError("Invalid CosmosDB endpoint") from e
try:
self.database_client = self.cosmosdb_client.get_database_client(
database_name
)
except exceptions.CosmosResourceNotFoundError:
raise ValueError("Invalid CosmosDB database name")
try:
self.container_client = self.database_client.get_container_client(
container_name
)
except exceptions.CosmosResourceNotFoundError:
raise ValueError("Invalid CosmosDB container name")
async def ensure(self):
"""Ensure CosmosDB client is properly initialized and accessible."""
if (
not self.cosmosdb_client
or not self.database_client
or not self.container_client
):
return False, "CosmosDB client not initialized correctly"
try:
await self.database_client.read()
except Exception:
return (
False,
f"CosmosDB database {self.database_name} on account {self.cosmosdb_endpoint} not found",
)
try:
await self.container_client.read()
except Exception:
return False, f"CosmosDB container {self.container_name} not found"
return True, "CosmosDB client initialized successfully"
async def create_conversation(
self, user_id, conversation_id=str(uuid.uuid4()), title=""
):
"""Create a new conversation in CosmosDB."""
conversation = {
"id": conversation_id,
"type": "conversation",
"createdAt": datetime.utcnow().isoformat(),
"updatedAt": datetime.utcnow().isoformat(),
"userId": user_id,
"title": title,
"conversation_id": conversation_id,
}
# TODO: add some error handling based on the output of the upsert_item call
resp = await self.container_client.upsert_item(conversation)
if resp:
return resp
else:
return False
async def upsert_conversation(self, conversation):
"""Update or insert a conversation in CosmosDB."""
resp = await self.container_client.upsert_item(conversation)
if resp:
return resp
else:
return False
async def delete_conversation(self, user_id, conversation_id):
"""Delete a conversation from CosmosDB."""
conversation = await self.container_client.read_item(
item=conversation_id, partition_key=user_id
)
if conversation:
resp = await self.container_client.delete_item(
item=conversation_id, partition_key=user_id
)
return resp
else:
return True
async def delete_messages(self, conversation_id, user_id):
"""Delete all messages for a conversation."""
# get a list of all the messages in the conversation
messages = await self.get_messages(user_id, conversation_id)
response_list = []
if messages:
for message in messages:
resp = await self.container_client.delete_item(
item=message["id"], partition_key=user_id
)
response_list.append(resp)
return response_list
async def get_conversations(self, user_id, limit, sort_order="DESC", offset=0):
"""Get list of conversations for a user with pagination."""
parameters = [{"name": "@userId", "value": user_id}]
query = f"SELECT * FROM c where c.userId = @userId and c.type='conversation' order by c.updatedAt {sort_order}"
if limit is not None:
query += f" offset {offset} limit {limit}"
conversations = []
async for item in self.container_client.query_items(
query=query, parameters=parameters
):
conversations.append(item)
return conversations
async def get_conversation(self, user_id, conversation_id):
"""Get a specific conversation by ID for a user."""
parameters = [
{"name": "@conversationId", "value": conversation_id},
{"name": "@userId", "value": user_id},
]
query = "SELECT * FROM c where c.id = @conversationId and c.type='conversation' and c.userId = @userId"
conversations = []
async for item in self.container_client.query_items(
query=query, parameters=parameters
):
conversations.append(item)
# if no conversations are found, return None
if len(conversations) == 0:
return None
else:
return conversations[0]
async def create_message(self, uuid, conversation_id, user_id, input_message: dict):
"""Create a new message in a conversation."""
message = {
"id": uuid,
"type": "message",
"userId": user_id,
"createdAt": datetime.utcnow().isoformat(),
"updatedAt": datetime.utcnow().isoformat(),
"conversationId": conversation_id,
"role": input_message["role"],
"content": input_message,
}
if AZURE_COSMOSDB_ENABLE_FEEDBACK:
message["feedback"] = ""
resp = await self.container_client.upsert_item(message)
if resp:
# update the parent conversations's updatedAt field with the current message's createdAt datetime value
conversation = await self.get_conversation(user_id, conversation_id)
if not conversation:
return "Conversation not found"
conversation["updatedAt"] = message["createdAt"]
await self.upsert_conversation(conversation)
return resp
else:
return False
async def update_message_feedback(self, user_id, message_id, feedback):
"""Update feedback for a specific message."""
message = await self.container_client.read_item(
item=message_id, partition_key=user_id
)
if message:
message["feedback"] = feedback
resp = await self.container_client.upsert_item(message)
return resp
else:
return False
async def get_messages(self, user_id, conversation_id):
"""Get all messages for a conversation."""
parameters = [
{"name": "@conversationId", "value": conversation_id},
{"name": "@userId", "value": user_id},
]
query = "SELECT * FROM c WHERE c.conversationId = @conversationId AND c.type='message' AND c.userId = @userId ORDER BY c.timestamp ASC"
messages = []
async for item in self.container_client.query_items(
query=query, parameters=parameters
):
messages.append(item)
return messages
# Helper functions that were previously in HistoryService
async def init_cosmosdb_client():
"""Initialize and return a CosmosDB client."""
if not CHAT_HISTORY_ENABLED:
logger.debug("CosmosDB is not enabled in configuration")
return None
try:
cosmos_endpoint = f"https://{AZURE_COSMOSDB_ACCOUNT}.documents.azure.com:443/"
return CosmosConversationClient(
cosmosdb_endpoint=cosmos_endpoint,
credential=await get_azure_credential_async(),
database_name=AZURE_COSMOSDB_DATABASE,
container_name=AZURE_COSMOSDB_CONVERSATIONS_CONTAINER,
enable_message_feedback=AZURE_COSMOSDB_ENABLE_FEEDBACK,
)
except Exception:
logger.exception("Failed to initialize CosmosDB client")
raise
async def generate_title(conversation_messages, user_id: str = "", conversation_id: str = ""):
"""Generate a title for a conversation using Azure AI Foundry agent."""
try:
user_messages = [msg for msg in conversation_messages if msg["role"] == "user"]
if not user_messages:
logger.debug("No user messages found, returning default title")
return generate_fallback_title(conversation_messages)
combined_content = "\n".join([str(msg["content"]) for msg in user_messages])
final_prompt = f"Generate a 4-word or less title for this request:\n{combined_content}"
if not AZURE_AI_AGENT_ENDPOINT:
logger.warning("Azure AI Agent endpoint not configured, using fallback title generation")
return generate_fallback_title(conversation_messages)
if not AGENT_NAME_TITLE:
logger.warning("Agent title name not configured, using fallback title generation")
return generate_fallback_title(conversation_messages)
credential = await get_azure_credential_async()
try:
async with AIProjectClient(
endpoint=AZURE_AI_AGENT_ENDPOINT,
credential=credential
) as project_client:
openai_client = project_client.get_openai_client()
conversation = await openai_client.conversations.create()
response = await openai_client.responses.create(
conversation=conversation.id,
input=final_prompt,
extra_body={"agent_reference": {"name": AGENT_NAME_TITLE, "type": "agent_reference"}}
)
_title_usage = UsageAccumulator()
_title_usage.add_from_response(response)
_title_usage.emit(
agent_name=AGENT_NAME_TITLE or "",
model_deployment_name=os.getenv("AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME", "") or "",
user_id=user_id or "",
conversation_id=conversation_id or "",
)
result_text = ""
for item in response.output:
if getattr(item, 'type', None) == 'message':
if hasattr(item, 'content') and item.content is not None:
for content in item.content:
if hasattr(content, 'text'):
result_text += content.text
return result_text.strip() if result_text else generate_fallback_title(conversation_messages)
finally:
await credential.close()
except HttpResponseError as sre:
logger.warning("HttpResponseError generating title with Azure AI Foundry agent: %s", sre)
return generate_fallback_title(conversation_messages)
except Exception as e:
logger.warning("Error generating title with Azure AI Foundry agent: %s", e)
return generate_fallback_title(conversation_messages)
def generate_fallback_title(conversation_messages):
"""Generate a fallback title from conversation messages when AI generation fails."""
user_messages = [msg for msg in conversation_messages if msg["role"] == "user"]
if user_messages:
first_message = user_messages[0]["content"]
if isinstance(first_message, dict):
first_message = str(first_message)
if first_message:
words = str(first_message).split()[:4]
title = " ".join(words) if words else "New Conversation"
return title if title.strip() else "New Conversation"
return "New Conversation"
async def add_conversation(user_id: str, request_json: dict):
"""Add a new conversation with initial message."""
try:
conversation_id = request_json.get("conversation_id")
messages = request_json.get("messages", [])
history_metadata = {}
# make sure cosmos is configured
cosmos_conversation_client = await init_cosmosdb_client()
if not cosmos_conversation_client:
raise ValueError("CosmosDB is not configured or unavailable")
if not conversation_id:
title = await generate_title(messages, user_id=user_id)
conversation_dict = await cosmos_conversation_client.create_conversation(user_id, title)
conversation_id = conversation_dict["id"]
history_metadata["title"] = title
history_metadata["date"] = conversation_dict["createdAt"]
if messages and messages[-1]["role"] == "user":
created_message = await cosmos_conversation_client.create_message(str(uuid.uuid4()), conversation_id, user_id, messages[-1])
if created_message == "Conversation not found":
raise ValueError(
f"Conversation not found for ID: {conversation_id}")
else:
raise ValueError("No user message found")
# request_body = {
# "messages": messages, "history_metadata": {
# "conversation_id": conversation_id}}
# return await complete_chat_request(request_body)
return True
except Exception:
logger.exception("Error in add_conversation")
raise
async def update_conversation(user_id: str, request_json: dict):
"""Update a conversation with new messages."""
conversation_id = request_json.get("conversation_id")
messages = request_json.get("messages", [])
if not conversation_id:
raise ValueError("No conversation_id found")
cosmos_conversation_client = await init_cosmosdb_client()
# Retrieve or create conversation
conversation = await cosmos_conversation_client.get_conversation(user_id, conversation_id)
if not conversation:
title = await generate_title(messages, user_id=user_id, conversation_id=conversation_id)
conversation = await cosmos_conversation_client.create_conversation(
user_id=user_id, conversation_id=conversation_id, title=title
)
conversation_id = conversation["id"]
# Format the incoming message object in the "chat/completions" messages format then write it to the
# conversation history in cosmos
messages = request_json["messages"]
if len(messages) > 0 and messages[0]["role"] == "user":
user_message = next(
(
message
for message in reversed(messages)
if message["role"] == "user"
),
None,
)
createdMessageValue = await cosmos_conversation_client.create_message(
uuid=str(uuid.uuid4()),
conversation_id=conversation_id,
user_id=user_id,
input_message=user_message,
)
if createdMessageValue == "Conversation not found":
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Conversation not found")
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="User message not found")
# Format the incoming message object in the "chat/completions" messages format
# then write it to the conversation history in cosmos
messages = request_json["messages"]
if len(messages) > 0 and messages[-1]["role"] in ("assistant", "error"):
if len(messages) > 1 and messages[-2].get("role", None) == "tool":
# write the tool message first
await cosmos_conversation_client.create_message(
uuid=str(uuid.uuid4()),
conversation_id=conversation_id,
user_id=user_id,
input_message=messages[-2],
)
# write the assistant message
await cosmos_conversation_client.create_message(
uuid=messages[-1]["id"],
conversation_id=conversation_id,
user_id=user_id,
input_message=messages[-1],
)
else:
await cosmos_conversation_client.cosmosdb_client.close()
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="No assistant message found")
await cosmos_conversation_client.cosmosdb_client.close()
return {
"id": conversation["id"],
"title": conversation["title"],
"updatedAt": conversation.get("updatedAt")}
async def rename_conversation(user_id: str, conversation_id, title):
"""Rename a conversation."""
if not conversation_id:
raise ValueError("No conversation_id found")
cosmos_conversation_client = await init_cosmosdb_client()
conversation = await cosmos_conversation_client.get_conversation(user_id, conversation_id)
if not conversation:
raise HTTPException(
status_code=404,
detail=f"Conversation {conversation_id} was not found. It either does not exist or the logged-in user does not have access to it.")
conversation["title"] = title
updated_conversation = await cosmos_conversation_client.upsert_conversation(
conversation
)
return updated_conversation
async def update_message_feedback(
user_id: str,
message_id: str,
message_feedback: str) -> Optional[dict]:
"""Update feedback for a specific message."""
try:
logger.info(
f"Updating feedback for message_id: {message_id} by user: {user_id}")
cosmos_conversation_client = await init_cosmosdb_client()
updated_message = await cosmos_conversation_client.update_message_feedback(user_id, message_id, message_feedback)
if updated_message:
logger.info(
f"Successfully updated message_id: {message_id} with feedback: {message_feedback}")
return updated_message
else:
logger.warning(f"Message ID {message_id} not found or access denied")
return None
except Exception:
logger.exception(
f"Error updating message feedback for message_id: {message_id}")
raise
async def delete_conversation(user_id: str, conversation_id: str) -> bool:
"""
Deletes a conversation and its messages from the database if the user has access.
Args:
user_id (str): The ID of the authenticated user.
conversation_id (str): The ID of the conversation to delete.
Returns:
bool: True if the conversation was deleted successfully, False otherwise.
"""
try:
cosmos_conversation_client = await init_cosmosdb_client()
# Fetch conversation to ensure it exists and belongs to the user
conversation = await cosmos_conversation_client.get_conversation(user_id, conversation_id)
if not conversation:
logger.warning(f"Conversation {conversation_id} not found.")
return False
if conversation["userId"] != user_id:
logger.warning(
f"User {user_id} does not have permission to delete {conversation_id}.")
return False
# Delete associated messages first (if applicable)
await cosmos_conversation_client.delete_messages(conversation_id, user_id)
# Delete the conversation itself
await cosmos_conversation_client.delete_conversation(user_id, conversation_id)
logger.info(f"Successfully deleted conversation {conversation_id}.")
return True
except Exception as e:
logger.exception(f"Error deleting conversation {conversation_id}: {e}")
return False
async def get_conversations(user_id: str, offset: int, limit: Optional[int]):
"""
Retrieves a list of conversations for a given user.
Args:
user_id (str): The ID of the authenticated user.
Returns:
list: A list of conversation objects or an empty list if none exist.
"""
try:
cosmos_conversation_client = await init_cosmosdb_client()
if not cosmos_conversation_client:
raise ValueError("CosmosDB is not configured or unavailable")
conversations = await cosmos_conversation_client.get_conversations(user_id, offset=offset, limit=limit)
return conversations or []
except Exception:
logger.exception(f"Error retrieving conversations for user {user_id}")
return []
async def get_messages(user_id: str, conversation_id: str):
"""
Retrieves all messages for a given conversation ID if the user has access.
Args:
user_id (str): The ID of the authenticated user.
conversation_id (str): The ID of the conversation.
Returns:
list: A list of messages in the conversation.
"""
try:
cosmos_conversation_client = await init_cosmosdb_client()
if not cosmos_conversation_client:
raise ValueError("CosmosDB is not configured or unavailable")
# Fetch conversation to ensure it exists and belongs to the user
conversation = await cosmos_conversation_client.get_conversation(user_id, conversation_id)
if not conversation:
logger.warning(f"Conversation {conversation_id} not found.")
return []
# Fetch messages associated with the conversation
messages = await cosmos_conversation_client.get_messages(user_id, conversation_id)
return messages
except Exception as e:
logger.exception(
f"Error retrieving messages for conversation {conversation_id}: {e}")
return []
async def get_conversation_messages(user_id: str, conversation_id: str):
"""
Retrieves a single conversation and its messages for a given user.
Args:
user_id (str): The ID of the authenticated user.
conversation_id (str): The ID of the conversation to retrieve.
Returns:
dict: The conversation object with messages or None if not found.
"""
try:
cosmos_conversation_client = await init_cosmosdb_client()
if not cosmos_conversation_client:
raise ValueError("CosmosDB is not configured or unavailable")
# Fetch the conversation details
conversation = await cosmos_conversation_client.get_conversation(user_id, conversation_id)
if not conversation:
logger.warning(
f"Conversation {conversation_id} not found for user {user_id}.")
return None
# Get messages related to the conversation
conversation_messages = await cosmos_conversation_client.get_messages(user_id, conversation_id)
# Format messages for the frontend
messages = []
for msg in conversation_messages:
# Extract content - handle both string and object formats
content = msg.get("content", "")
if isinstance(content, dict):
message_content = content.get("content", "")
citations = content.get("citations", "")
else:
message_content = content
citations = ""
messages.append({
"id": msg["id"],
"role": msg["role"],
"content": message_content,
"createdAt": msg["createdAt"],
"feedback": msg.get("feedback"),
"citations": citations,
})
return messages
except Exception:
logger.exception(
f"Error retrieving conversation {conversation_id} for user {user_id}")
return None
async def clear_messages(user_id: str, conversation_id: str) -> bool:
"""
Clears all messages in a conversation while keeping the conversation itself.
Args:
user_id (str): The ID of the authenticated user.
conversation_id (str): The ID of the conversation.
Returns:
bool: True if messages were cleared successfully, False otherwise.
"""
try:
cosmos_conversation_client = await init_cosmosdb_client()
if not cosmos_conversation_client:
raise ValueError("CosmosDB is not configured or unavailable")
# Ensure the conversation exists and belongs to the user
conversation = await cosmos_conversation_client.get_conversation(user_id, conversation_id)
if not conversation:
logger.warning(f"Conversation {conversation_id} not found.")
return False
if conversation["user_id"] != user_id:
logger.warning(
f"User {user_id} does not have permission to clear messages in {conversation_id}.")
return False
# Delete all messages associated with the conversation
await cosmos_conversation_client.delete_messages(conversation_id, user_id)
logger.info(
f"Successfully cleared messages in conversation {conversation_id}.")
return True
except Exception as e:
logger.exception(
f"Error clearing messages for conversation {conversation_id}: {e}")
return False
async def ensure_cosmos():
"""Ensure CosmosDB is properly configured and accessible."""
try:
cosmos_conversation_client = await init_cosmosdb_client()
success, err = await cosmos_conversation_client.ensure()
return success, err
except Exception as e:
logger.exception(f"Error ensuring CosmosDB configuration: {e}")
return False, str(e)
# Route handlers
@router.post("/generate")
async def add_conversation_route(request: Request):
"""Route handler for adding a new conversation."""
try:
authenticated_user = get_authenticated_user_details(
request_headers=request.headers)
user_id = authenticated_user["user_principal_id"]
# Parse request body
request_json = await request.json()
response = await add_conversation(user_id, request_json)
track_event_if_configured("ConversationCreated", {
"user_id": user_id,
"request": request_json,
})
return response
except Exception as e:
logger.exception("Exception in /generate: %s", str(e))
track_event_if_configured("GenerateConversationError", {
"user_id": locals().get("user_id", ""),
"error": str(e),
"error_type": type(e).__name__
})
span = trace.get_current_span()
if span is not None:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
return JSONResponse(content={"error": "An internal error has occurred!"}, status_code=500)
@router.post("/update")
async def update_conversation_route(request: Request):
"""Route handler for updating a conversation."""
try:
authenticated_user = get_authenticated_user_details(
request_headers=request.headers)
user_id = authenticated_user["user_principal_id"]
# Parse request body
request_json = await request.json()
conversation_id = request_json.get("conversation_id")
if not conversation_id:
raise HTTPException(status_code=400, detail="No conversation_id found")
# Call update_conversation function
update_response = await update_conversation(user_id, request_json)
if not update_response:
raise HTTPException(status_code=500, detail="Failed to update conversation")
track_event_if_configured("ConversationUpdated", {
"user_id": user_id,
"conversation_id": conversation_id,
"title": update_response["title"]
})
return JSONResponse(
content={
"success": True,
"data": {
"title": update_response["title"],
"date": update_response["updatedAt"],
"conversation_id": update_response["id"],
},
},
status_code=200,
)
except Exception as e:
logger.exception("Exception in /history/update: %s", str(e))
track_event_if_configured("UpdateConversationError", {
"user_id": locals().get("user_id", ""),
"conversation_id": locals().get("conversation_id", ""),
"error": str(e),
"error_type": type(e).__name__
})
span = trace.get_current_span()
if span is not None:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
return JSONResponse(content={"error": "An internal error has occurred!"}, status_code=500)
@router.post("/message_feedback")
async def update_message_feedback_route(request: Request):
"""Route handler for updating message feedback."""
try:
authenticated_user = get_authenticated_user_details(
request_headers=request.headers)
user_id = authenticated_user["user_principal_id"]
# Parse request body
request_json = await request.json()
message_id = request_json.get("message_id")
message_feedback = request_json.get("message_feedback")
if not message_id:
track_event_if_configured("MessageFeedbackValidationError", {
"error": "message_id is missing",
"user_id": user_id
})
raise HTTPException(status_code=400, detail="message_id is required")
if not message_feedback:
track_event_if_configured("MessageFeedbackValidationError", {
"error": "message_feedback is missing",
"user_id": user_id
})
raise HTTPException(status_code=400, detail="message_feedback is required")
# Call update_message_feedback function
updated_message = await update_message_feedback(user_id, message_id, message_feedback)
if updated_message:
track_event_if_configured("MessageFeedbackUpdated", {
"user_id": user_id,
"message_id": message_id,
"feedback": message_feedback
})
return JSONResponse(
content={
"message": f"Successfully updated message with feedback {message_feedback}",
"message_id": message_id,
},
status_code=200,
)
else:
track_event_if_configured("MessageFeedbackNotFound", {
"user_id": user_id,
"message_id": message_id
})
raise HTTPException(
status_code=404,
detail=f"Unable to update message {message_id}. It either does not exist or the user does not have access to it."
)
except Exception as e:
logger.exception("Exception in /history/message_feedback: %s", str(e))
track_event_if_configured("MessageFeedbackError", {
"user_id": locals().get("user_id", ""),
"error": str(e),
"error_type": type(e).__name__
})
span = trace.get_current_span()
if span is not None:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
return JSONResponse(content={"error": "An internal error has occurred!"}, status_code=500)
@router.delete("/delete")
async def delete_conversation_route(request: Request, id: str = Query(...)):
"""Route handler for deleting a conversation."""
try:
# Get the user ID from request headers
authenticated_user = get_authenticated_user_details(
request_headers=request.headers)
user_id = authenticated_user["user_principal_id"]
conversation_id = id
if not conversation_id:
track_event_if_configured("DeleteConversationValidationError", {
"error": "conversation_id is missing",
"user_id": user_id
})
raise HTTPException(status_code=400, detail="conversation_id is required")
# Delete conversation using delete_conversation function
deleted = await delete_conversation(user_id, conversation_id)
if deleted:
track_event_if_configured("ConversationDeleted", {
"user_id": user_id,
"conversation_id": conversation_id
})
return JSONResponse(
content={
"message": "Successfully deleted conversation and messages",
"conversation_id": conversation_id},
status_code=200,
)
else:
track_event_if_configured("DeleteConversationNotFound", {
"user_id": user_id,
"conversation_id": conversation_id
})
raise HTTPException(
status_code=404,
detail=f"Conversation {conversation_id} not found or user does not have permission.")
except Exception as e:
logger.exception("Exception in /history/delete: %s", str(e))
track_event_if_configured("DeleteConversationError", {
"user_id": locals().get("user_id", ""),
"conversation_id": locals().get("conversation_id", ""),
"error": str(e),
"error_type": type(e).__name__
})
span = trace.get_current_span()
if span is not None:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
return JSONResponse(content={"error": "An internal error has occurred!"}, status_code=500)
@router.get("/list")
async def list_conversations(
request: Request,
offset: int = Query(0, alias="offset"),
limit: int = Query(25, alias="limit")
):
"""Route handler for listing conversations."""
try:
# await adjust_processed_data_dates()
authenticated_user = get_authenticated_user_details(
request_headers=request.headers)
user_id = authenticated_user["user_principal_id"]
logger.info(f"user_id: {user_id}, offset: {offset}, limit: {limit}")
# Get conversations
conversations = await get_conversations(user_id, offset=offset, limit=limit)
if not isinstance(conversations, list):
track_event_if_configured("ListConversationsNotFound", {
"user_id": user_id,
"offset": offset,
"limit": limit
})
return JSONResponse(
content={
"error": f"No conversations for {user_id} were found"},
status_code=404)
track_event_if_configured("ConversationsListed", {
"user_id": user_id,
"offset": offset,
"limit": limit,
"conversation_count": len(conversations)
})
return JSONResponse(content=conversations, status_code=200)
except Exception as e:
logger.exception("Exception in /history/list: %s", str(e))
track_event_if_configured("ListConversationsError", {
"user_id": locals().get("user_id", ""),
"error": str(e),
"error_type": type(e).__name__
})
span = trace.get_current_span()
if span is not None:
span.record_exception(e)
span.set_status(Status(StatusCode.ERROR, str(e)))
return JSONResponse(content={"error": "An internal error has occurred!"}, status_code=500)
@router.get("/read")
async def get_conversation_messages_route(request: Request, id: str = Query(...)):
"""Route handler for reading conversation messages."""
try:
authenticated_user = get_authenticated_user_details(
request_headers=request.headers)
user_id = authenticated_user["user_principal_id"]
conversation_id = id
if not conversation_id:
track_event_if_configured("ReadConversationValidationError", {
"error": "conversation_id is required",
"user_id": user_id
})
raise HTTPException(status_code=400, detail="conversation_id is required")
# Get conversation details
conversationMessages = await get_conversation_messages(user_id, conversation_id)
if not conversationMessages:
track_event_if_configured("ReadConversationNotFound", {
"user_id": user_id,
"conversation_id": conversation_id
})
raise HTTPException(
status_code=404,
detail=f"Conversation {conversation_id} was not found. It either does not exist or the user does not have access to it."
)
track_event_if_configured("ConversationRead", {
"user_id": user_id,
"conversation_id": conversation_id,
"message_count": len(conversationMessages)
})
return JSONResponse(