-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathroutes.py
1483 lines (1347 loc) · 55.7 KB
/
routes.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
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
import json
import os
import shutil
import signal
import tempfile
import urllib.parse
import zipfile
from datetime import datetime
from typing import List, Optional
from agentmemory.helpers import chroma_collection_to_list
from agentmemory.main import search_memory
import llmcalls
import logs
from fastapi import (
APIRouter,
HTTPException,
File,
Request,
UploadFile,
WebSocket,
WebSocketDisconnect,
Form,
Depends,
)
from fastapi.responses import (
FileResponse,
HTMLResponse,
RedirectResponse,
Response,
JSONResponse,
)
from fastapi.security import HTTPBearer
from fastapi.security.api_key import APIKeyCookie
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from google.auth.transport import requests
from google.oauth2 import id_token
from authentication import Authentication
from chat_tabs.dao import ChatTabsDAO
from classes import (
CreateChat,
UserName,
editSettings,
setActiveChat,
userMessage,
noTokenMessage,
UserGoogle,
generateAudioMessage,
regenerateMessage,
emailMessage,
TimeTravelMessage,
)
from database import Database
from memory import (
export_memory_to_file,
import_file_to_memory,
get_last_message,
get_memories,
update_memory,
delete_memory,
MemoryManager,
)
from simple_utils import get_root, convert_name
from user_management.dao import UsersDAO, AdminControlsDAO
from user_management.routes import set_login_cookies
from utils import (
process_message,
AudioProcessor,
AddonManager,
SettingsManager,
BrainProcessor,
MessageParser,
queryRewrite,
get_available_models,
)
logger = logs.Log("routes", "routes.log").get_logger()
from config import (
api_keys,
STATIC,
LOGIN_REQUIRED,
PRODUCTION,
ADMIN_REQUIRED,
USERS_DIR,
)
def format_timestamp(value, format="%Y-%m-%d %H:%M:%S"):
return datetime.fromtimestamp(value).strftime(format)
def trim_leading_zeros(value):
return value.lstrip("0")
def round_number(value, decimals=2):
if value is None:
return "N/A"
return round(value, decimals)
router = APIRouter()
templates = Jinja2Templates(directory=get_root(STATIC))
# Register a custom filter with Jinja2 environment
templates.env.filters["format_timestamp"] = format_timestamp
templates.env.filters["trim_leading_zeros"] = trim_leading_zeros
templates.env.filters["round"] = round_number
connections = {}
@router.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
version = SettingsManager.get_version()
with AdminControlsDAO() as db:
daily_limit = db.get_daily_limit()
template_name = (
"maintenance.html" if db.get_maintenance_mode() else "index.html"
)
context = {
"request": request,
"version": version,
"daily_limit": daily_limit,
"production": PRODUCTION,
}
return templates.TemplateResponse(template_name, context)
@router.get("/styles.css")
async def read_root():
try:
return FileResponse("static/styles.css")
except FileNotFoundError:
raise HTTPException(status_code=404, detail="Item not found")
@router.get(
"/memory_explorer/{category}", response_class=HTMLResponse, tags=[LOGIN_REQUIRED]
)
async def get_memory_explorer(request: Request, category: str):
with UsersDAO() as dao:
username = request.state.user.username
memories = get_memories(category, username=username)
return templates.TemplateResponse(
"memory_explorer.html",
{"request": request, "category": category, "memories": memories},
)
async def send_debug_message(username: str, message: str):
connection = connections.get(username)
# logger.info(f"connection length: {len(connections)}")
if connection:
try:
await connection.send_text(message)
except Exception as e:
logger.error(
f"An error occurred when sending a message to user {username}: {e}"
)
else:
logger.error(f"No active websocket connection for user {username}")
@router.websocket("/ws/{username}")
async def websocket_endpoint(websocket: WebSocket, username: str):
await websocket.accept()
connections[username] = websocket
try:
while True:
data = await websocket.receive_text()
if data == '{"type":"ping"}':
await websocket.send_text(json.dumps({"type": "pong"}))
else:
await websocket.send_text(
json.dumps({"type": "message", "content": f"Received: {data}"})
)
except WebSocketDisconnect:
# Handle client disconnection
if username in connections:
del connections[username]
logger.debug(f"User {username} disconnected due to WebSocketDisconnect")
except ConnectionResetError:
# Handle client disconnection
if username in connections:
del connections[username]
logger.debug(f"User {username} disconnected due to ConnectionResetError")
except Exception as e:
# Handle any other exceptions
if username in connections:
del connections[username]
logger.error(f"An error occurred with user {username}: {e}")
# load settings route
@router.post(
"/load_settings/",
tags=["Settings", LOGIN_REQUIRED],
summary="Load settings",
description="This endpoint allows you to load the user's settings by providing a username and session token. If the token is valid, the settings will be returned. If the token is invalid, an HTTP 401 error will be returned.",
response_description="Returns the user's settings if the token is valid, else returns an HTTPException with status code 401.",
responses={
200: {
"description": "Settings loaded successfully",
"content": {
"application/json": {
"example": {
"message": "Settings loaded successfully",
"settings": {"category": {"setting": "value"}},
}
}
},
},
401: {
"description": "Token is invalid",
"content": {
"application/json": {"example": {"detail": "Token is invalid"}}
},
},
},
)
async def handle_get_settings(request: Request):
username = request.state.user.username
await AddonManager.load_addons(username, USERS_DIR)
with open(os.path.join(USERS_DIR, username, "settings.json"), "r") as f:
settings = json.load(f)
logger.debug(f"Loaded settings for user {username}")
logger.debug(settings)
total_tokens_used, total_cost = 0, 0
with Database() as db, UsersDAO() as dao:
total_tokens_used, total_cost = db.get_token_usage(username)
total_daily_tokens_used, total_daily_cost = db.get_token_usage(username, True)
display_name = dao.get_display_name(username)
settings["usage"] = {"total_tokens": total_tokens_used, "total_cost": total_cost}
settings["daily_usage"] = {"daily_cost": total_daily_cost}
settings["display_name"] = display_name
settings["available_models"] = get_available_models()
# check if the google_client_secret.json exists in the users directory
if os.path.exists(os.path.join(USERS_DIR, "google_client_secret.json")):
from gworkspace.google_auth import onEnable
result = await onEnable(username, USERS_DIR)
if isinstance(result, dict) and "auth_uri" in result:
settings["auth_uri"] = result["auth_uri"]
elif isinstance(result, dict) and "error" in result:
settings["error"] = result["error"]
return settings
def count_tokens(message):
return MessageParser.num_tokens_from_string(message)
# update settings route
@router.post(
"/update_settings/",
tags=["Settings", LOGIN_REQUIRED],
summary="Update settings",
description="This endpoint allows you to update the user's settings by providing a username, session token, category, setting, and value. If the token is valid, the settings will be updated. If the token is invalid, an HTTP 401 error will be returned.",
response_description="Returns the user's updated settings if the token is valid, else returns an HTTPException with status code 401.",
responses={
200: {
"description": "Settings updated successfully",
"content": {
"application/json": {
"example": {
"message": "Settings updated successfully",
"settings": {"category": {"setting": "value"}},
}
}
},
},
400: {
"description": "Category or setting not found",
"content": {
"application/json": {
"example": {"detail": "Category or setting not found"}
}
},
},
401: {
"description": "Token is invalid",
"content": {
"application/json": {"example": {"detail": "Token is invalid"}}
},
},
},
)
async def handle_update_settings(request: Request, user: editSettings):
username = request.state.user.username
# create the directory if it doesn't exist
user_dir = os.path.join(USERS_DIR, username)
if not os.path.exists(user_dir):
os.makedirs(user_dir)
# check if the settings file exists
settings_file = os.path.join(user_dir, "settings.json")
if not os.path.exists(settings_file):
# create the settings file
with open(settings_file, "w") as f:
json.dump({}, f)
with open(settings_file, "r") as f:
settings = json.load(f)
if user.category in settings:
if isinstance(user.setting, dict):
# iterate over the dictionary
for key, value in user.setting.items():
# update the settings
settings[user.category][key] = value
elif user.setting in settings[user.category]:
if str(user.value).lower() == "true":
settings[user.category][user.setting] = True
elif str(user.value).lower() == "false":
settings[user.category][user.setting] = False
elif user.value.isdigit():
settings[user.category][user.setting] = int(user.value)
else:
settings[user.category][user.setting] = user.value
else:
raise HTTPException(status_code=400, detail="Setting not found")
elif user.category == "db":
with UsersDAO() as db:
if user.setting == "display_name":
db.update_display_name(username, user.value)
else:
raise HTTPException(status_code=400, detail="Setting not found")
else:
raise HTTPException(status_code=400, detail="Category not found")
with open(settings_file, "w") as f:
json.dump(settings, f)
with Database() as db, UsersDAO() as dao:
total_tokens_used, total_cost = db.get_token_usage(username)
total_daily_tokens_used, total_daily_cost = db.get_token_usage(username, True)
display_name = dao.get_display_name(username)
settings["usage"] = {"total_tokens": total_tokens_used, "total_cost": total_cost}
settings["daily_usage"] = {"daily_cost": total_daily_cost}
settings["display_name"] = display_name
settings["available_models"] = get_available_models()
# check if the calendar_addon or gmail_addon is enabled
if (
"calendar_addon" in settings["addons"]
and settings["addons"]["calendar_addon"]
or "gmail_addon" in settings["addons"]
and settings["addons"]["gmail_addon"]
):
from gworkspace.google_auth import onEnable
auth_uri = await onEnable(username, USERS_DIR)
if isinstance(auth_uri, dict) and "error" in auth_uri:
settings["error"] = auth_uri["error"]
settings["auth_uri"] = None
# TODO: redirect to the configuration page
settings["addons"]["calendar_addon"] = False
settings["addons"]["gmail_addon"] = False
else:
settings["auth_uri"] = auth_uri
return settings
# openAI response route
@router.post(
"/message/",
tags=["Messaging", LOGIN_REQUIRED],
summary="Send a message to the AI",
description="This endpoint allows you to send a message to the AI by providing a username, session token, and prompt. If the token is valid, the AI will respond to the prompt. If the token is invalid, an HTTP 401 error will be returned.",
response_description="Returns the AI's response if the token is valid, else returns an HTTPException with status code 401.",
responses={
200: {
"description": "AI responded successfully",
"content": {
"application/json": {
"example": {"message": "AI responded successfully"}
}
},
},
401: {
"description": "Token is invalid",
"content": {
"application/json": {"example": {"detail": "Token is invalid"}}
},
},
},
)
async def handle_message(request: Request, message: userMessage):
user = request.state.user
settings = await SettingsManager.load_settings(USERS_DIR, user.username)
if count_tokens(message.prompt) > settings["memory"]["input"]:
raise HTTPException(status_code=400, detail="Prompt is too long")
(
total_tokens_used,
total_cost,
daily_limit,
total_daily_tokens_used,
total_daily_cost,
display_name,
) = (0, 0, 0, 0, 0, "")
with Database() as db, UsersDAO() as dao, ChatTabsDAO() as chat_tabs_dao, AdminControlsDAO() as admin_controls_dao:
total_tokens_used, total_cost = db.get_token_usage(user.username)
total_daily_tokens_used, total_daily_cost = db.get_token_usage(
user.username, True
)
display_name = dao.get_display_name(user.username)
daily_limit = admin_controls_dao.get_daily_limit()
has_access = dao.get_user_access(user.username)
user_id = dao.get_user_id(user.username)
tab_data = chat_tabs_dao.get_tab_data(user_id)
active_tab_data = chat_tabs_dao.get_active_tab_data(user_id)
# if no active tab, set chat_id to 0
if message.chat_id is None and active_tab_data is None:
message.chat_id = "0"
# put the data in the database
chat_tabs_dao.insert_tab_data(
user_id, message.chat_id, "new chat", message.chat_id, True
)
# if there is an active tab, set chat_id to the active tab's chat_id
# this logic is a bit weird when used as API
else:
chat_tabs_dao.update_created_at(user_id, message.chat_id)
if active_tab_data is not None:
message.chat_id = active_tab_data.chat_id
if not has_access or has_access == "false" or has_access == "False":
logger.info(f"user {user.username} does not have access")
raise HTTPException(
status_code=400,
detail="You do not have access yet, ask permission from the administrator or wait for your trial to start",
)
if total_daily_cost >= daily_limit:
logger.info(f"user {user.username} reached daily limit")
raise HTTPException(
status_code=400,
detail="You reached your daily limit. Please wait until tomorrow to continue using the service.",
)
return await process_message(
message.prompt,
user.username,
USERS_DIR,
message.display_name,
chat_id=message.chat_id,
)
@router.post("/create_chat_tab/", tags=[LOGIN_REQUIRED])
async def create_chat_tab(request: Request, message: CreateChat):
user = request.state.user
with ChatTabsDAO() as chat_tabs_dao:
user_id = user.id
chat_tabs_dao.insert_tab_data(
user_id, message.chat_id, message.chat_name, message.chat_id, False
)
return {"message": "Chat tab created successfully"}
@router.post("/set_active_tab/", tags=[LOGIN_REQUIRED])
async def set_active_tab(request: Request, message: setActiveChat):
user = request.state.user
with ChatTabsDAO() as chat_tabs_dao:
user_id = user.id
chat_tabs_dao.set_active_tab(user_id, message.chat_id)
return {"message": "Active tab set successfully"}
@router.post("/regenerate_response/", tags=[LOGIN_REQUIRED])
async def regenerate_response(request: Request, message: regenerateMessage):
user = request.state.user
settings = await SettingsManager.load_settings(USERS_DIR, user.username)
(
total_tokens_used,
total_cost,
daily_limit,
total_daily_tokens_used,
total_daily_cost,
display_name,
) = (0, 0, 0, 0, 0, "")
print(
f"getting user data for {user.username} to regenerate response with uuid {message.uuid} and chat_id {message.chat_id}"
)
with Database() as db, UsersDAO() as dao, ChatTabsDAO() as chat_tabs_dao, AdminControlsDAO() as admin_controls_dao:
total_tokens_used, total_cost = db.get_token_usage(user.username)
total_daily_tokens_used, total_daily_cost = db.get_token_usage(
user.username, True
)
display_name = dao.get_display_name(user.username)
daily_limit = admin_controls_dao.get_daily_limit()
has_access = dao.get_user_access(user.username)
user_id = dao.get_user_id(user.username)
tab_data = chat_tabs_dao.get_tab_data(user_id)
active_tab_data = chat_tabs_dao.get_active_tab_data(user_id)
last_message = get_last_message(
"active_brain", message.chat_id, user.username, message.uuid
)
# if no active tab, set chat_id to 0
if active_tab_data is None:
message.chat_id = "0"
# put the data in the database
chat_tabs_dao.insert_tab_data(
user_id, message.chat_id, "new chat", message.chat_id, True
)
# if there is an active tab, set chat_id to the active tab's chat_id
else:
chat_tabs_dao.update_created_at(user_id, message.chat_id)
message.chat_id = active_tab_data.chat_id
if not has_access or has_access == "false" or has_access == "False":
logger.info(f"user {user.username} does not have access")
raise HTTPException(
status_code=400,
detail="You do not have access yet, ask permission from the administrator or wait for your trial to start",
)
if total_daily_cost >= daily_limit:
logger.info(f"user {user.username} reached daily limit")
raise HTTPException(
status_code=400,
detail="You reached your daily limit. Please wait until tomorrow to continue using the service.",
)
return await process_message(
last_message,
user.username,
USERS_DIR,
display_name,
chat_id=message.chat_id,
regenerate=True,
uuid=message.uuid,
)
@router.post("/stop_streaming/", tags=[LOGIN_REQUIRED])
async def stop_streaming(request: Request, user: UserName):
llmcalls.user_pressed_stop(user.username)
return {"message": "Streaming stopped successfully"}
@router.post("/message_with_image/", tags=["Messaging", LOGIN_REQUIRED])
async def handle_message_image(
request: Request,
image_file: UploadFile,
prompt: str = Form(...),
chat_id: str = Form(...),
):
user = request.state.user
username = user.username
settings = await SettingsManager.load_settings(USERS_DIR, username)
if count_tokens(prompt) > settings["memory"]["input"]:
raise HTTPException(status_code=400, detail="Prompt is too long")
with Database() as db, UsersDAO() as dao, ChatTabsDAO() as chat_tabs_dao, AdminControlsDAO() as admin_controls_dao:
total_tokens_used, total_cost = db.get_token_usage(user.username)
total_daily_tokens_used, total_daily_cost = db.get_token_usage(
user.username, True
)
display_name = dao.get_display_name(user.username)
daily_limit = admin_controls_dao.get_daily_limit()
has_access = dao.get_user_access(user.username)
user_id = dao.get_user_id(user.username)
tab_data = chat_tabs_dao.get_tab_data(user_id)
active_tab_data = chat_tabs_dao.get_active_tab_data(user_id)
# if no active tab, set chat_id to 0
if active_tab_data is None:
chat_id = "0"
# put the data in the database
chat_tabs_dao.insert_tab_data(user_id, chat_id, "new chat", chat_id, True)
# if there is an active tab, set chat_id to the active tab's chat_id
else:
chat_tabs_dao.update_created_at(user_id, chat_id)
chat_id = active_tab_data.chat_id
if not has_access or has_access == "false" or has_access == "False":
logger.info(f"user {username} does not have access")
raise HTTPException(
status_code=400,
detail="You do not have access yet, ask permission from the administrator or wait for your trial to start",
)
if total_daily_cost >= daily_limit:
logger.info(f"user {username} reached daily limit")
raise HTTPException(
status_code=400,
detail="You reached your daily limit. Please wait until tomorrow to continue using the service.",
)
# check the size of the image, if it's too big +5mb, return an error
if image_file.size > 20000000:
raise HTTPException(
status_code=400,
detail="Image is too big, please use an image that is less than 20mb",
)
# save the image to the user's directory
converted_name = convert_name(username)
user_dir = os.path.join(USERS_DIR, converted_name, "data")
if not os.path.exists(user_dir):
os.makedirs(user_dir)
image_path = os.path.join(user_dir, image_file.filename)
with open(image_path, "wb") as f:
f.write(image_file.file.read())
# get the image description
# add the image as markdown to the prompt
url_encoded_image = urllib.parse.quote(image_file.filename)
prompt = "<p>' + prompt + "</p>"
result = await MessageParser.start_image_description(
image_path, prompt, image_file.filename, username
)
return await process_message(
prompt, username, "users", display_name, result, chat_id
)
@router.post("/message_with_files/", tags=["Messaging", LOGIN_REQUIRED])
async def handle_message_files(
request: Request,
files: List[UploadFile] = File(...),
prompt: str = Form(...),
chat_id: str = Form(...),
):
file_details = ""
user = request.state.user
username = user.username
settings = await SettingsManager.load_settings(USERS_DIR, username)
if count_tokens(prompt) > settings["memory"]["input"]:
raise HTTPException(status_code=400, detail="Prompt is too long")
with Database() as db, UsersDAO() as dao, ChatTabsDAO() as chat_tabs_dao, AdminControlsDAO() as admin_controls_dao:
total_tokens_used, total_cost = db.get_token_usage(user.username)
total_daily_tokens_used, total_daily_cost = db.get_token_usage(
user.username, True
)
display_name = dao.get_display_name(user.username)
daily_limit = admin_controls_dao.get_daily_limit()
has_access = dao.get_user_access(user.username)
user_id = dao.get_user_id(user.username)
tab_data = chat_tabs_dao.get_tab_data(user_id)
active_tab_data = chat_tabs_dao.get_active_tab_data(user_id)
# if no active tab, set chat_id to 0
if active_tab_data is None:
chat_id = "0"
# put the data in the database
chat_tabs_dao.insert_tab_data(user_id, chat_id, "new chat", chat_id, True)
# if there is an active tab, set chat_id to the active tab's chat_id
else:
chat_tabs_dao.update_created_at(user_id, chat_id)
chat_id = active_tab_data.chat_id
if not has_access or has_access == "false" or has_access == "False":
logger.info(f"user {username} does not have access")
raise HTTPException(
status_code=400,
detail="You do not have access yet, ask permission from the administrator or wait for your trial to start",
)
if total_daily_cost >= daily_limit:
logger.info(f"user {username} reached daily limit")
raise HTTPException(
status_code=400,
detail="You reached your daily limit. Please wait until tomorrow to continue using the service.",
)
# check the total size of all files, if it's too big +200mb, return an error
total_size = sum(file.size for file in files)
if total_size > 200000000:
raise HTTPException(
status_code=400,
detail="Total file size is too big, please use files that are less than 20mb in total",
)
# save the files to the user's directory
converted_name = convert_name(username)
user_dir = os.path.join(USERS_DIR, converted_name, "data")
if not os.path.exists(user_dir):
os.makedirs(user_dir)
file_paths = []
for file in files:
file_path = os.path.join(user_dir, file.filename)
with open(file_path, "wb") as f:
f.write(file.file.read())
file_paths.append(file_path)
# add the file paths to the prompt
for file_path in file_paths:
if file_path.lower().endswith(
(
".png",
".jpg",
".jpeg",
".gif",
".svg",
".bmp",
".webp",
".jfif",
".pjpeg",
".pjp",
".ico",
)
):
url_encoded_image = urllib.parse.quote(os.path.basename(file_path))
file_details += f'\n\n'
else:
url_encoded_file = urllib.parse.quote(os.path.basename(file_path))
file_details += (
f"\n[data/{os.path.basename(file_path)}](data/{url_encoded_file})\n"
)
prompt = file_details + "<p>" + prompt + "</p>"
result = MessageParser.add_file_paths_to_message(prompt, file_details)
return await process_message(
prompt, username, "users", display_name, result, chat_id
)
# openAI response route without modules
@router.post(
"/message_no_modules/",
tags=["Messaging", LOGIN_REQUIRED],
summary="Send a message to the AI without modules",
description="This endpoint allows you to send a message to the AI by providing a username, session token, and prompt. If the token is valid, the AI will respond to the prompt. If the token is invalid, an HTTP 401 error will be returned.",
response_description="Returns the AI's response if the token is valid, else returns an HTTPException with status code 401.",
responses={
200: {
"description": "AI responded successfully",
"content": {
"application/json": {
"example": {"message": "AI responded successfully"}
}
},
},
401: {
"description": "Token is invalid",
"content": {
"application/json": {"example": {"detail": "Token is invalid"}}
},
},
},
)
async def handle_message_no_modules(request: Request, message: userMessage):
user = request.state.user
settings = await SettingsManager.load_settings(USERS_DIR, user.username)
if count_tokens(message.prompt) > settings["memory"]["input"]:
raise HTTPException(status_code=400, detail="Prompt is too long")
(
total_tokens_used,
total_cost,
daily_limit,
total_daily_tokens_used,
total_daily_cost,
display_name,
) = (0, 0, 0, 0, 0, "")
with Database() as db, UsersDAO() as dao, ChatTabsDAO() as chat_tabs_dao, AdminControlsDAO() as admin_controls_dao:
total_tokens_used, total_cost = db.get_token_usage(user.username)
total_daily_tokens_used, total_daily_cost = db.get_token_usage(
user.username, True
)
display_name = dao.get_display_name(user.username)
daily_limit = admin_controls_dao.get_daily_limit()
has_access = dao.get_user_access(user.username)
user_id = dao.get_user_id(user.username)
tab_data = chat_tabs_dao.get_tab_data(user_id)
active_tab_data = chat_tabs_dao.get_active_tab_data(user_id)
# if no active tab, set chat_id to 0
if message.chat_id is None and active_tab_data is None:
message.chat_id = "0"
# put the data in the database
chat_tabs_dao.insert_tab_data(
user_id, message.chat_id, "new chat", message.chat_id, True
)
# if there is an active tab, set chat_id to the active tab's chat_id
else:
chat_tabs_dao.update_created_at(user_id, message.chat_id)
message.chat_id = active_tab_data.chat_id
if not has_access or has_access == "false" or has_access == "False":
logger.info(f"user {user.username} does not have access")
raise HTTPException(
status_code=400,
detail="You do not have access yet, ask permission from the administrator or wait for your trial to start",
)
if total_daily_cost >= daily_limit:
logger.info(f"user {user.username} reached daily limit")
raise HTTPException(
status_code=400,
detail="You reached your daily limit. Please wait until tomorrow to continue using the service.",
)
return await process_message(
message.prompt,
user.username,
USERS_DIR,
message.display_name,
chat_id=message.chat_id,
)
# message route with audio
@router.post(
"/message_audio/",
tags=["Messaging", LOGIN_REQUIRED],
summary="Send an Audio message and get a transcript",
description="This endpoint allows you to send an audio message to the AI by providing a username, session token, and audio file. If the token is valid, a transcript of the audio is sent back. If the token is invalid, an HTTP 401 error will be returned.",
response_description="Returns a transcript of the audio if the token is valid, else returns an HTTPException with status code 401.",
responses={
200: {
"description": "Audio message sent successfully",
"content": {
"application/json": {
"example": {"message": "Audio message sent successfully"}
}
},
},
401: {
"description": "Token is invalid",
"content": {
"application/json": {"example": {"detail": "Token is invalid"}}
},
},
},
)
async def handle_message_audio(request: Request, audio_file: UploadFile):
return await AudioProcessor.upload_audio(
USERS_DIR, request.state.user.username, audio_file
)
@router.post(
"/generate_audio/",
tags=["Text to Speech", LOGIN_REQUIRED],
summary="Generate audio from text",
description="This endpoint allows you to generate audio from text by providing a username, session token, and prompt. If the token is valid, an audio file is sent back. If the token is invalid, an HTTP 401 error will be returned.",
response_description="Returns an audio file if the token is valid, else returns an HTTPException with status code 401.",
responses={
200: {
"description": "Audio generated successfully",
"content": {
"application/json": {
"example": {"message": "Audio generated successfully"}
}
},
},
401: {
"description": "Token is invalid",
"content": {
"application/json": {"example": {"detail": "Token is invalid"}}
},
},
},
)
async def handle_generate_audio(request: Request, message: generateAudioMessage):
user = request.state.user
audio_path = await AudioProcessor.generate_audio(
message.prompt, user.username, USERS_DIR
)
return FileResponse(audio_path, media_type="audio/wav")
@router.post(
"/save_data/",
tags=["Data", LOGIN_REQUIRED],
summary="Save data to a JSON file",
description="This endpoint allows you to save the user's data to a JSON file by providing a username and session token. If the token is valid, the data will be saved to a JSON file. If the token is invalid, an HTTP 401 error will be returned.",
response_description="Returns the JSON file if the token is valid, else returns an HTTPException with status code 401.",
responses={
200: {
"description": "Data saved successfully",
"content": {
"application/json": {"example": {"message": "Data saved successfully"}}
},
},
401: {
"description": "Token is invalid",
"content": {
"application/json": {"example": {"detail": "Token is invalid"}}
},
},
},
)
async def handle_save_data(request: Request):
user = request.state.user
if os.environ.get("IS_SINGLE_USER") == "true":
# Paths for memory file and settings file
json_file_path = os.path.join("data", "user", user.username, "memory.json")
settings_file = os.path.join("data", "user", user.username, "settings.json")
else:
# Paths for memory file and settings file
json_file_path = os.path.join(USERS_DIR, user.username, "memory.json")
settings_file = os.path.join(USERS_DIR, user.username, "settings.json")
# create the json_file_path and settings_file if they don't exist
if not os.path.exists(json_file_path):
with open(json_file_path, "w") as f:
json.dump({}, f)
if not os.path.exists(settings_file):
with open(settings_file, "w") as f:
json.dump({}, f)
# Check if the memory file exists
if not os.path.exists(json_file_path):
# todo: add an empty memory file
pass
# Export memory to a JSON file if it exists
if os.path.exists(json_file_path):
export_memory_to_file(path=json_file_path, username=user.username)
# Get the user's notes directory
user_notes_dir = os.path.join(USERS_DIR, user.username, "notes")
# Check if the notes directory exists, if not create an empty one
if not os.path.exists(user_notes_dir):
os.makedirs(user_notes_dir)
# Create a temporary directory
with tempfile.TemporaryDirectory() as temp_dir:
# Copy the user's notes directory
shutil.copytree(user_notes_dir, os.path.join(temp_dir, "notes"))
# Check and copy the settings file
if os.path.exists(settings_file):
shutil.copy2(settings_file, os.path.join(temp_dir, "settings.json"))
# Check and copy the memory file
if os.path.exists(json_file_path):
shutil.copy2(json_file_path, os.path.join(temp_dir, "memory.json"))
# Get current date
current_date = datetime.now().strftime("%Y%m%d")
# Create zip filename
zip_filename = f"{user.username}_{current_date}_clang_data.zip"
# Zip the temporary directory
shutil.make_archive(
os.path.join(USERS_DIR, user.username, "data"), "zip", temp_dir
)
# Rename the zip file
shutil.move(
os.path.join(USERS_DIR, user.username, "data.zip"),
os.path.join(USERS_DIR, user.username, zip_filename),
)
# Serve the zip file
file_path = os.path.join(USERS_DIR, user.username, zip_filename)
with open(file_path, "rb") as file:
content = file.read()
response = Response(content, media_type="application/zip")
response.headers["Content-Disposition"] = f'attachment; filename="{zip_filename}"'
return response
@router.post(
"/upload_data/",
tags=["Data", LOGIN_REQUIRED],
summary="Upload user data",
description="This endpoint allows you to upload the user's data by providing a username, session token, and data file. If the token is valid, the user's data will be uploaded. If the token is invalid, an HTTP 401 error will be returned.",
response_description="Returns a success message if the token is valid, else returns an HTTPException with status code 401.",
responses={
200: {
"description": "User data uploaded successfully",
"content": {
"application/json": {
"example": {"message": "User data uploaded successfully"}
}
},
},
401: {
"description": "Token is invalid",
"content": {
"application/json": {"example": {"detail": "Token is invalid"}}
},
},
},
)
async def handle_upload_data(request: Request, data_file: UploadFile = File(...)):
user = request.state.user
username = user.username
# Save the uploaded file to the user's directory
file_path = os.path.join(USERS_DIR, username, data_file.filename)
with open(file_path, "wb") as buffer:
shutil.copyfileobj(data_file.file, buffer)
# Check if the file is a zip file
if zipfile.is_zipfile(file_path):
# Extract the zip file
with zipfile.ZipFile(file_path, "r") as zip_ref:
zip_ref.extractall(os.path.join(USERS_DIR, username))
# Check for 'memory.json', and 'settings.json'
if "memory.json" not in os.listdir(
os.path.join(USERS_DIR, username)
) or "settings.json" not in os.listdir(os.path.join(USERS_DIR, username)):
raise HTTPException(
status_code=400, detail="Zip file is missing required files"
)
# Verify 'memory.json' is a valid JSON file
try:
with open(os.path.join(USERS_DIR, username, "memory.json")) as f:
json.load(f)
except json.JSONDecodeError:
raise HTTPException(
status_code=400, detail="'memory.json' is not a valid JSON file"
)
# Verify 'settings.json' is a valid JSON file
try:
with open(os.path.join(USERS_DIR, username, "settings.json")) as f:
json.load(f)
except json.JSONDecodeError:
raise HTTPException(
status_code=400, detail="'settings.json' is not a valid JSON file"
)