-
Notifications
You must be signed in to change notification settings - Fork 470
/
chat_history.py
510 lines (440 loc) · 19.4 KB
/
chat_history.py
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
import os
import logging
from uuid import uuid4
from dotenv import load_dotenv
from flask import request, jsonify, Blueprint
from openai import AsyncAzureOpenAI
from backend.batch.utilities.chat_history.auth_utils import (
get_authenticated_user_details,
)
from backend.batch.utilities.helpers.config.config_helper import ConfigHelper
from backend.batch.utilities.helpers.env_helper import EnvHelper
from backend.batch.utilities.chat_history.database_factory import DatabaseFactory
load_dotenv()
bp_chat_history_response = Blueprint("chat_history", __name__)
logger = logging.getLogger(__name__)
logger.setLevel(level=os.environ.get("LOGLEVEL", "INFO").upper())
env_helper: EnvHelper = EnvHelper()
def init_database_client():
try:
conversation_client = DatabaseFactory.get_conversation_client()
return conversation_client
except Exception as e:
logger.exception("Exception in database initialization: %s", e)
raise e
def init_openai_client():
try:
if env_helper.is_auth_type_keys():
azure_openai_client = AsyncAzureOpenAI(
azure_endpoint=env_helper.AZURE_OPENAI_ENDPOINT,
api_version=env_helper.AZURE_OPENAI_API_VERSION,
api_key=env_helper.AZURE_OPENAI_API_KEY,
)
else:
azure_openai_client = AsyncAzureOpenAI(
azure_endpoint=env_helper.AZURE_OPENAI_ENDPOINT,
api_version=env_helper.AZURE_OPENAI_API_VERSION,
azure_ad_token_provider=env_helper.AZURE_TOKEN_PROVIDER,
)
return azure_openai_client
except Exception as e:
logging.exception("Exception in Azure OpenAI initialization: %s", e)
raise e
@bp_chat_history_response.route("/history/list", methods=["GET"])
async def list_conversations():
config = ConfigHelper.get_active_config_or_default()
if not config.enable_chat_history:
return jsonify({"error": "Chat history is not available"}), 400
try:
offset = request.args.get("offset", 0)
authenticated_user = get_authenticated_user_details(
request_headers=request.headers
)
user_id = authenticated_user["user_principal_id"]
conversation_client = init_database_client()
if not conversation_client:
return jsonify({"error": "Database not available"}), 500
await conversation_client.connect()
try:
conversations = await conversation_client.get_conversations(
user_id, offset=offset, limit=25
)
if not isinstance(conversations, list):
return (
jsonify({"error": f"No conversations for {user_id} were found"}),
404,
)
return jsonify(conversations), 200
except Exception as e:
logger.exception(f"Error fetching conversations: {e}")
raise
finally:
await conversation_client.close()
except Exception as e:
logger.exception(f"Exception in /history/list: {e}")
return jsonify({"error": "Error while listing historical conversations"}), 500
@bp_chat_history_response.route("/history/rename", methods=["POST"])
async def rename_conversation():
config = ConfigHelper.get_active_config_or_default()
if not config.enable_chat_history:
return jsonify({"error": "Chat history is not available"}), 400
try:
authenticated_user = get_authenticated_user_details(
request_headers=request.headers
)
user_id = authenticated_user["user_principal_id"]
# check request for conversation_id
request_json = request.get_json()
conversation_id = request_json.get("conversation_id", None)
if not conversation_id:
return (jsonify({"error": "conversation_id is required"}), 400)
title = request_json.get("title", None)
if not title or title.strip() == "":
return jsonify({"error": "A non-empty title is required"}), 400
# Initialize and connect to the database client
conversation_client = init_database_client()
if not conversation_client:
return jsonify({"error": "Database not available"}), 500
await conversation_client.connect()
try:
# Retrieve conversation from database
conversation = await conversation_client.get_conversation(
user_id, conversation_id
)
if not conversation:
return (
jsonify(
{
"error": f"Conversation {conversation_id} was not found. It either does not exist or the logged in user does not have access to it."
}
),
400,
)
# Update the title and save changes
conversation["title"] = title
updated_conversation = await conversation_client.upsert_conversation(
conversation
)
return jsonify(updated_conversation), 200
except Exception as e:
logger.exception(
f"Error updating conversation: user_id={user_id}, conversation_id={conversation_id}, error={e}"
)
raise
finally:
await conversation_client.close()
except Exception as e:
logger.exception(f"Exception in /history/rename: {e}")
return jsonify({"error": "Error while renaming conversation"}), 500
@bp_chat_history_response.route("/history/read", methods=["POST"])
async def get_conversation():
config = ConfigHelper.get_active_config_or_default()
if not config.enable_chat_history:
return jsonify({"error": "Chat history is not available"}), 400
try:
authenticated_user = get_authenticated_user_details(
request_headers=request.headers
)
user_id = authenticated_user["user_principal_id"]
# check request for conversation_id
request_json = request.get_json()
conversation_id = request_json.get("conversation_id", None)
if not conversation_id:
return jsonify({"error": "conversation_id is required"}), 400
# Initialize and connect to the database client
conversation_client = init_database_client()
if not conversation_client:
return jsonify({"error": "Database not available"}), 500
await conversation_client.connect()
try:
# Retrieve conversation
conversation = await conversation_client.get_conversation(
user_id, conversation_id
)
if not conversation:
return (
jsonify(
{
"error": f"Conversation {conversation_id} was not found. It either does not exist or the logged in user does not have access to it."
}
),
400,
)
# Fetch conversation messages
conversation_messages = await conversation_client.get_messages(
user_id, conversation_id
)
messages = [
{
"id": msg["id"],
"role": msg["role"],
"content": msg["content"],
"createdAt": msg["createdAt"],
"feedback": msg.get("feedback"),
}
for msg in conversation_messages
]
# Return formatted conversation and messages
return (
jsonify({"conversation_id": conversation_id, "messages": messages}),
200,
)
except Exception as e:
logger.exception(
f"Error fetching conversation or messages: user_id={user_id}, conversation_id={conversation_id}, error={e}"
)
raise
finally:
await conversation_client.close()
except Exception as e:
logger.exception(f"Exception in /history/read: {e}")
return jsonify({"error": "Error while fetching conversation history"}), 500
@bp_chat_history_response.route("/history/delete", methods=["DELETE"])
async def delete_conversation():
config = ConfigHelper.get_active_config_or_default()
if not config.enable_chat_history:
return jsonify({"error": "Chat history is not available"}), 400
try:
# Get the user ID from the request headers
authenticated_user = get_authenticated_user_details(
request_headers=request.headers
)
user_id = authenticated_user["user_principal_id"]
# check request for conversation_id
request_json = request.get_json()
conversation_id = request_json.get("conversation_id", None)
if not conversation_id:
return (
jsonify(
{
"error": f"Conversation {conversation_id} was not found. It either does not exist or the logged in user does not have access to it."
}
),
400,
)
# Initialize and connect to the database client
conversation_client = init_database_client()
if not conversation_client:
return jsonify({"error": "Database not available"}), 500
await conversation_client.connect()
try:
# Delete conversation messages from database
await conversation_client.delete_messages(conversation_id, user_id)
# Delete the conversation itself
await conversation_client.delete_conversation(user_id, conversation_id)
return (
jsonify(
{
"message": "Successfully deleted conversation and messages",
"conversation_id": conversation_id,
}
),
200,
)
except Exception as e:
logger.exception(
f"Error deleting conversation: user_id={user_id}, conversation_id={conversation_id}, error={e}"
)
raise
finally:
await conversation_client.close()
except Exception as e:
logger.exception(f"Exception in /history/delete: {e}")
return jsonify({"error": "Error while deleting conversation history"}), 500
@bp_chat_history_response.route("/history/delete_all", methods=["DELETE"])
async def delete_all_conversations():
config = ConfigHelper.get_active_config_or_default()
# Check if chat history is available
if not config.enable_chat_history:
return jsonify({"error": "Chat history is not available"}), 400
try:
# Get the user ID from the request headers (ensure authentication is successful)
authenticated_user = get_authenticated_user_details(
request_headers=request.headers
)
user_id = authenticated_user["user_principal_id"]
# Initialize the database client
conversation_client = init_database_client()
if not conversation_client:
return jsonify({"error": "Database not available"}), 500
await conversation_client.connect()
try:
# Get all conversations for the user
conversations = await conversation_client.get_conversations(
user_id, offset=0, limit=None
)
if not conversations:
return (
jsonify({"error": f"No conversations found for user {user_id}"}),
400,
)
# Delete each conversation and its associated messages
for conversation in conversations:
try:
# Delete messages associated with the conversation
await conversation_client.delete_messages(
conversation["id"], user_id
)
# Delete the conversation itself
await conversation_client.delete_conversation(
user_id, conversation["id"]
)
except Exception as e:
# Log and continue with the next conversation if one fails
logger.exception(
f"Error deleting conversation {conversation['id']} for user {user_id}: {e}"
)
continue
return (
jsonify(
{
"message": f"Successfully deleted all conversations and messages for user {user_id}"
}
),
200,
)
except Exception as e:
logger.exception(
f"Error deleting all conversations for user {user_id}: {e}"
)
raise
finally:
await conversation_client.close()
except Exception as e:
logger.exception(f"Exception in /history/delete_all: {e}")
return jsonify({"error": "Error while deleting all conversation history"}), 500
@bp_chat_history_response.route("/history/update", methods=["POST"])
async def update_conversation():
config = ConfigHelper.get_active_config_or_default()
if not config.enable_chat_history:
return jsonify({"error": "Chat history is not available"}), 400
try:
# Get user details from request headers
authenticated_user = get_authenticated_user_details(
request_headers=request.headers
)
user_id = authenticated_user["user_principal_id"]
request_json = request.get_json()
conversation_id = request_json.get("conversation_id", None)
if not conversation_id:
return jsonify({"error": "conversation_id is required"}), 400
messages = request_json["messages"]
if not messages or len(messages) == 0:
return jsonify({"error": "Messages are required"}), 400
# Initialize conversation client
conversation_client = init_database_client()
if not conversation_client:
return jsonify({"error": "Database not available"}), 500
await conversation_client.connect()
try:
# Get or create the conversation
conversation = await conversation_client.get_conversation(
user_id, conversation_id
)
if not conversation:
title = await generate_title(messages)
conversation = await conversation_client.create_conversation(
user_id=user_id, conversation_id=conversation_id, title=title
)
# Process and save user and assistant messages
# Process user message
if messages[0]["role"] == "user":
user_message = next(
(msg for msg in reversed(messages) if msg["role"] == "user"), None
)
if not user_message:
return jsonify({"error": "User message not found"}), 400
created_message = await conversation_client.create_message(
uuid=str(uuid4()),
conversation_id=conversation_id,
user_id=user_id,
input_message=user_message,
)
if created_message == "Conversation not found":
return jsonify({"error": "Conversation not found"}), 400
# Process assistant and tool messages if available
if messages[-1]["role"] == "assistant":
if len(messages) > 1 and messages[-2].get("role") == "tool":
# Write the tool message first if it exists
await conversation_client.create_message(
uuid=str(uuid4()),
conversation_id=conversation_id,
user_id=user_id,
input_message=messages[-2],
)
# Write the assistant message
await conversation_client.create_message(
uuid=str(uuid4()),
conversation_id=conversation_id,
user_id=user_id,
input_message=messages[-1],
)
else:
return jsonify({"error": "No assistant message found"}), 400
return (
jsonify(
{
"success": True,
"data": {
"title": conversation["title"],
"date": conversation["updatedAt"],
"conversation_id": conversation["id"],
},
}
),
200,
)
except Exception as e:
logger.exception(
f"Error updating conversation or messages: user_id={user_id}, conversation_id={conversation_id}, error={e}"
)
raise
finally:
await conversation_client.close()
except Exception as e:
logger.exception(f"Exception in /history/update: {e}")
return jsonify({"error": "Error while updating the conversation history"}), 500
@bp_chat_history_response.route("/history/frontend_settings", methods=["GET"])
def get_frontend_settings():
try:
# Clear the cache for the config helper method
ConfigHelper.get_active_config_or_default.cache_clear()
# Retrieve active config
config = ConfigHelper.get_active_config_or_default()
# Ensure `enable_chat_history` is processed correctly
if isinstance(config.enable_chat_history, str):
chat_history_enabled = config.enable_chat_history.strip().lower() == "true"
else:
chat_history_enabled = bool(config.enable_chat_history)
return jsonify({"CHAT_HISTORY_ENABLED": chat_history_enabled}), 200
except Exception as e:
logger.exception(f"Exception in /history/frontend_settings: {e}")
return jsonify({"error": "Error while getting frontend settings"}), 500
async def generate_title(conversation_messages):
title_prompt = "Summarize the conversation so far into a 4-word or less title. Do not use any quotation marks or punctuation. Do not include any other commentary or description."
# Filter only the user messages, but consider including system or assistant context if necessary
messages = [
{"role": msg["role"], "content": msg["content"]}
for msg in conversation_messages
if msg["role"] == "user"
]
messages.append({"role": "user", "content": title_prompt})
try:
azure_openai_client = init_openai_client()
# Create a chat completion with the Azure OpenAI client
response = await azure_openai_client.chat.completions.create(
model=env_helper.AZURE_OPENAI_MODEL,
messages=messages,
temperature=1,
max_tokens=64,
)
# Ensure response contains valid choices and content
if response and response.choices and len(response.choices) > 0:
title = response.choices[0].message.content.strip()
return title
else:
raise ValueError("No valid choices in response")
except Exception as e:
logger.exception(f"Error generating title: {str(e)}")
# Fallback: return the content of the second to last message if something goes wrong
return messages[-2]["content"] if len(messages) > 1 else "Untitled"