-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
3910 lines (3239 loc) · 154 KB
/
app.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
# app.py
# Standard library imports
import asyncio
import json
import logging
import os
import platform
import socket
import subprocess
import sys
import threading
import uuid
import time
import math
from uuid import uuid4
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone, timedelta
from functools import lru_cache, partial
from logging.handlers import RotatingFileHandler
from pathlib import Path
from queue import Queue, Empty, Full
from typing import List, Dict, Optional
from dataclasses import dataclass
# Third-party imports - Core Web Framework
from quart import (
Quart, request, jsonify, render_template, url_for, redirect,
session, abort, Response, send_file, make_response, request,
render_template_string, flash, send_from_directory, websocket
)
from quart_cors import cors
from quart_schema import QuartSchema
from quart_auth import (
QuartAuth, AuthUser, current_user, login_user,
logout_user, Unauthorized
)
import pkg_resources
import traceback
# Third-party imports - Database and ORM
from sqlalchemy import select, func
from alembic import command
from alembic.config import Config as AlembicConfig
from dotenv import load_dotenv
# Third-party imports - AI/ML Services
import openai
import anthropic
import tiktoken
import google.generativeai as genai
from google.generativeai import GenerativeModel
from openai import OpenAI
# Third-party imports - Vector Storage
from pinecone import Pinecone
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext
from llama_index.vector_stores.pinecone import PineconeVectorStore
from llama_index.embeddings.openai import OpenAIEmbedding
# Third-party imports - Async HTTP and Network
import aiohttp
from aiohttp import ClientSession, AsyncResolver, ClientTimeout
from aiolimiter import AsyncLimiter
import aiofiles
import aiofiles.os as aio_os
from async_timeout import timeout
from tenacity import retry, stop_after_attempt, wait_exponential
import dns.resolver
# Third-party imports - Web Scraping and Processing
from bs4 import BeautifulSoup
from werkzeug.utils import secure_filename
# Local imports - Auth and Models
from auth import auth_bp, UserWrapper, login_required
from models import (
get_session, engine, Base,
Folder, Conversation, User, SystemMessage, Website, UploadedFile
)
# Local imports - Utils and Processing
from text_processing import format_text
from file_utils import (
get_user_folder, get_system_message_folder, get_uploads_folder,
get_processed_texts_folder, get_llmwhisperer_output_folder,
ensure_folder_exists, get_file_path, FileUtils
)
from file_processing import FileProcessor
from embedding_store import EmbeddingStore
from init_db import init_db
# Load environment variables
load_dotenv()
# Initialize OpenAI
from openai import OpenAI
client = OpenAI()
openai.api_key = os.getenv("OPENAI_API_KEY")
if openai.api_key is None:
raise ValueError("OPENAI_API_KEY environment variable not set")
# Initialize Pinecone
pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))
db_url = os.getenv('DATABASE_URL')
BRAVE_SEARCH_API_KEY = os.getenv('BRAVE_SEARCH_API_KEY')
# Debug configuration
debug_mode = True
# Initialize application
app = Quart(__name__)
app = cors(app, allow_origin="*")
QuartSchema(app)
# Application configuration
app.config.update(
ASYNC_MODE=True,
PROPAGATE_EXCEPTIONS=True,
SSE_RETRY_TIMEOUT=30000,
SECRET_KEY=os.getenv('SECRET_KEY'),
TEMPLATES_AUTO_RELOAD=True,
MAX_CONTENT_LENGTH=16 * 1024 * 1024, # 16 MB max-body-size
MAX_FORM_MEMORY_SIZE=16 * 1024 * 1024, # 16 MB max-form-size
)
# Configure auth settings - do this BEFORE initializing QuartAuth
app.config.update(
QUART_AUTH_COOKIE_SECURE=False if app.debug else True,
QUART_AUTH_COOKIE_DOMAIN=None,
QUART_AUTH_COOKIE_NAME="auth_token",
QUART_AUTH_COOKIE_PATH="/",
QUART_AUTH_COOKIE_SAMESITE="Lax",
# Convert duration to seconds instead of using timedelta
QUART_AUTH_DURATION=60 * 60 * 24 * 30, # 30 days in seconds
QUART_AUTH_SALT='cookie-session-aiui'
)
# Initialize QuartAuth
auth_manager = QuartAuth(app)
auth_manager.user_class = UserWrapper
# Register the blueprint
app.register_blueprint(auth_bp)
@app.errorhandler(Unauthorized)
async def unauthorized_handler(error):
await flash('Please log in to access this page.', 'warning')
return redirect(url_for('auth.login'))
@app.errorhandler(Exception)
async def handle_exception(error):
app.logger.error(f"Unhandled exception: {str(error)}")
app.logger.exception("Full error traceback:")
return await render_template('error.html', error=str(error))
@app.errorhandler(404)
async def not_found_error(error):
app.logger.error(f"404 Error: {error}")
return await render_template('error.html', error="Page not found"), 404
@app.errorhandler(500)
async def internal_error(error):
app.logger.error(f"500 Error: {error}")
return await render_template('error.html', error="Internal server error"), 500
@app.route('/static/<path:filename>')
async def static_files(filename):
return await send_from_directory('static', filename)
# Define the UnicodeFormatter class for logging
class UnicodeFormatter(logging.Formatter):
"""Custom formatter that properly handles Unicode characters in log messages."""
def format(self, record):
if isinstance(record.msg, bytes):
record.msg = record.msg.decode('utf-8', errors='replace')
elif not isinstance(record.msg, str):
record.msg = str(record.msg)
if record.args:
record.args = tuple(
arg.decode('utf-8', errors='replace') if isinstance(arg, bytes)
else str(arg) if not isinstance(arg, str)
else arg
for arg in record.args
)
return super().format(record)
def setup_logging(app, debug_mode):
# Remove any existing handlers
logging.getLogger().handlers.clear()
app.logger.handlers.clear()
# Configure root logger
logging.basicConfig(
level=logging.DEBUG if debug_mode else logging.INFO,
format='%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s', #milliseconds included
datefmt='%Y-%m-%d %H:%M:%S'
)
# Custom Unicode formatter
unicode_formatter = UnicodeFormatter("%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s")
# Set up file handler with rotation
file_handler = RotatingFileHandler(
"app.log",
maxBytes=100000,
backupCount=3,
encoding='utf-8'
)
file_handler.setFormatter(unicode_formatter)
file_handler.setLevel(logging.DEBUG if debug_mode else logging.INFO)
# Set up console handler with color formatting
class ColorFormatter(logging.Formatter):
"""Add colors to log levels"""
grey = "\x1b[38;21m"
blue = "\x1b[34;21m"
yellow = "\x1b[33;21m"
red = "\x1b[31;21m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
FORMATS = {
logging.DEBUG: blue + "%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s" + reset,
logging.INFO: grey + "%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s" + reset,
logging.WARNING: yellow + "%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s" + reset,
logging.ERROR: red + "%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s" + reset,
logging.CRITICAL: bold_red + "%(asctime)s.%(msecs)03d - %(levelname)s - %(message)s" + reset,
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt, datefmt='%Y-%m-%d %H:%M:%S')
return formatter.format(record)
# Console handler with color formatting
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(ColorFormatter())
console_handler.setLevel(logging.DEBUG if debug_mode else logging.INFO) # Show all levels in console
# Configure app logger
app.logger.addHandler(file_handler)
app.logger.addHandler(console_handler)
app.logger.propagate = False
app.logger.setLevel(logging.DEBUG if debug_mode else logging.INFO)
# Add console handler to root logger as well
root_logger = logging.getLogger()
root_logger.addHandler(console_handler)
root_logger.setLevel(logging.DEBUG if debug_mode else logging.INFO)
# Completely silence SQLAlchemy logging
logging.getLogger('sqlalchemy').setLevel(logging.ERROR)
logging.getLogger('sqlalchemy.engine').setLevel(logging.ERROR)
logging.getLogger('sqlalchemy.engine.base.Engine').setLevel(logging.ERROR)
logging.getLogger('sqlalchemy.dialects').setLevel(logging.ERROR)
logging.getLogger('sqlalchemy.pool').setLevel(logging.ERROR)
logging.getLogger('sqlalchemy.orm').setLevel(logging.ERROR)
# Additional SQLAlchemy logging suppression
logging.getLogger('sqlalchemy.engine.base').setLevel(logging.ERROR)
logging.getLogger('sqlalchemy.engine.impl').setLevel(logging.ERROR)
logging.getLogger('sqlalchemy.engine.logger').setLevel(logging.ERROR)
# Reduce noise from other loggers but show their warnings and errors
noisy_loggers = [
'httpcore',
'hypercorn.error',
'hypercorn.access',
'pinecone',
'unstract',
'asyncio',
'httpx',
'urllib3',
'requests',
'pinecone_plugin_interface.logging'
]
for logger_name in noisy_loggers:
logger = logging.getLogger(logger_name)
logger.setLevel(logging.WARNING)
logger.addHandler(console_handler)
logger.propagate = False
# Disable SQL statement logging explicitly
logging.getLogger('sqlalchemy.engine.Engine.logger').disabled = True
# Log startup message
app.logger.info("Application logging initialized")
if debug_mode:
app.logger.debug("Debug mode enabled")
app.logger.debug("Console logging enabled with colors")
# Usage in app.py
setup_logging(app, debug_mode)
# File upload configuration
BASE_UPLOAD_FOLDER = Path(os.path.abspath(os.path.join(os.path.dirname(__file__), 'user_files'))).resolve()
app.config['BASE_UPLOAD_FOLDER'] = str(BASE_UPLOAD_FOLDER)
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'docx'}
# Create the upload folder if it doesn't exist
try:
upload_folder = Path(app.config['BASE_UPLOAD_FOLDER'])
upload_folder.mkdir(parents=True, exist_ok=True)
os.chmod(str(upload_folder), 0o777)
app.logger.info(f"Successfully configured BASE_UPLOAD_FOLDER: {upload_folder}")
except Exception as e:
app.logger.error(f"Error during upload folder configuration: {str(e)}")
# Initialize file processing
embedding_store = None
file_processor = None
@app.before_serving
async def startup():
global embedding_store, file_processor
try:
app.logger.info("Initializing application components")
# Initialize database
await init_db()
# Initialize EmbeddingStore
embedding_store = EmbeddingStore(db_url, logger=app.logger)
await embedding_store.initialize()
# Initialize FileProcessor
file_processor = FileProcessor(embedding_store, app)
# Initialize FileUtils and verify upload folder
app.file_utils = FileUtils(app)
base_upload_folder = Path(app.config['BASE_UPLOAD_FOLDER'])
await app.file_utils.ensure_folder_exists(base_upload_folder)
app.logger.info("Application initialization completed successfully")
except Exception as e:
app.logger.error("Application startup failed", exc_info=True)
raise
@app.after_serving
async def shutdown():
try:
# Close database connection
await engine.dispose()
app.logger.info("Database connection closed")
# Add explicit cleanup of any active connections
if hasattr(app, '_connection_pool'):
await app._connection_pool.close()
app.logger.info("Connection pool closed")
# Clear FileUtils cache if it exists
if hasattr(app, 'file_utils'):
app.file_utils.get_user_folder.cache_clear()
app.file_utils.get_system_message_folder.cache_clear()
app.file_utils.get_uploads_folder.cache_clear()
app.file_utils.get_processed_texts_folder.cache_clear()
app.file_utils.get_llmwhisperer_output_folder.cache_clear()
app.file_utils.get_web_search_results_folder.cache_clear()
app.logger.info("FileUtils caches cleared")
delattr(app, 'file_utils')
app.logger.info("FileUtils cleanup completed")
except Exception as e:
app.logger.error(f"Error during shutdown: {str(e)}")
app.logger.exception("Full shutdown error traceback:")
raise
# Begin of status update manager
@dataclass
class SessionStatus:
user_id: int
session_id: str
message: str
last_updated: float
expires_at: float
websocket: Optional[object] = None
active: bool = False
class StatusUpdateManager:
PING_INTERVAL = 30 # seconds
SESSION_TIMEOUT = 3600 # 1 hour in seconds
CLEANUP_INTERVAL = 300 # 5 minutes
def __init__(self):
self._sessions: Dict[str, SessionStatus] = {}
self._cleanup_lock = asyncio.Lock()
self._last_cleanup = time.time()
self.connection_count = 0
self.locks = {}
self.initial_messages_sent = set()
def _generate_session_id(self, user_id: int) -> str:
"""Generate a unique session ID combining user_id and UUID."""
return f"{user_id}-{uuid.uuid4()}"
def create_session(self, user_id: int) -> str:
"""Create a new session and return its ID."""
session_id = self._generate_session_id(user_id)
current_time = time.time()
self._sessions[session_id] = SessionStatus(
user_id=user_id,
session_id=session_id,
message="Session initialized",
last_updated=current_time,
expires_at=current_time + self.SESSION_TIMEOUT
)
self._cleanup_expired_sessions()
return session_id
async def register_connection(self, session_id: str, websocket) -> bool:
"""Register a WebSocket connection for a session."""
async with self._cleanup_lock:
if session_id not in self._sessions:
return False
session = self._sessions[session_id]
# Only increment if session wasn't already active
if not session.active:
self.connection_count += 1
self._sessions[session_id] = SessionStatus(
user_id=session.user_id,
session_id=session_id,
message="Connected to status updates",
last_updated=time.time(),
expires_at=time.time() + self.SESSION_TIMEOUT,
websocket=websocket,
active=True
)
self.locks[session_id] = asyncio.Lock()
# Send initial connection message with session ID
try:
await websocket.send(json.dumps({
'type': 'status',
'status': 'connected',
'session_id': session_id,
'timestamp': datetime.now().isoformat()
}))
except Exception as e:
app.logger.error(f"Error sending initial connection message: {str(e)}")
return False
app.logger.debug(f"WebSocket connection registered for session ID: {session_id}. Active connections: {self.connection_count}")
return True
async def send_status_update(self, session_id: str, message: str, status: str = None) -> bool:
"""
Send a status update to a session.
Args:
session_id: The session ID
message: Status message to send
status: Optional status type (e.g. 'error')
"""
if session_id not in self._sessions or not self._sessions[session_id].active:
return False
session = self._sessions[session_id]
current_time = time.time()
# Update session status
self._sessions[session_id] = SessionStatus(
user_id=session.user_id,
session_id=session_id,
message=message,
last_updated=current_time,
expires_at=current_time + self.SESSION_TIMEOUT,
websocket=session.websocket,
active=session.active
)
# Send WebSocket update
lock = self.locks.get(session_id)
if lock:
async with lock:
try:
status_data = {
'type': 'status',
'message': message,
'timestamp': datetime.now().isoformat(),
'id': str(uuid.uuid4())
}
if status:
status_data['status'] = status
await session.websocket.send(json.dumps(status_data))
return True
except Exception as e:
app.logger.error(f"Error sending status update: {str(e)}")
await self.remove_connection(session_id)
return False
return False
async def send_ping(self, session_id: str) -> bool:
"""Send a ping message to keep the connection alive."""
if session_id not in self._sessions or not self._sessions[session_id].active:
return False
session = self._sessions[session_id]
try:
ping_data = {
'type': 'ping',
'timestamp': datetime.now().isoformat()
}
await session.websocket.send(json.dumps(ping_data))
return True
except Exception as e:
app.logger.debug(f"Error sending ping: {str(e)}")
await self.remove_connection(session_id)
return False
async def remove_connection(self, session_id: str) -> None:
"""Remove a session's WebSocket connection."""
async with self._cleanup_lock:
if session_id in self._sessions:
session = self._sessions[session_id]
# Only decrement if session was active
if session.active:
self.connection_count = max(0, self.connection_count - 1)
if session.websocket:
try:
await session.websocket.close(1000, "Connection closed normally")
except Exception as e:
app.logger.debug(f"Error closing websocket: {str(e)}")
# Update session to inactive state
self._sessions[session_id] = SessionStatus(
user_id=session.user_id,
session_id=session_id,
message=session.message,
last_updated=time.time(),
expires_at=session.expires_at,
websocket=None,
active=False
)
self.locks.pop(session_id, None)
self.initial_messages_sent.discard(session_id)
app.logger.debug(f"WebSocket connection removed for session ID: {session_id}. Active connections: {self.connection_count}")
def _cleanup_expired_sessions(self) -> None:
"""Clean up expired sessions."""
current_time = time.time()
if current_time - self._last_cleanup < self.CLEANUP_INTERVAL:
return
expired_sessions = [
session_id for session_id, session in self._sessions.items()
if current_time > session.expires_at
]
for session_id in expired_sessions:
del self._sessions[session_id]
self._last_cleanup = current_time
# Initialize the status update manager
status_manager = StatusUpdateManager()
async def update_status(message: str, session_id: str, status: str = None):
"""
Helper status update function.
Args:
message: Status message to send
session_id: WebSocket session ID
status: Optional status type (e.g. 'error')
"""
try:
await status_manager.send_status_update(
session_id=session_id,
message=message,
status=status
)
except Exception as e:
app.logger.error(f"Error sending status update: {str(e)}")
@app.route('/ws/diagnostic')
async def websocket_diagnostic():
"""
Endpoint to check WebSocket configuration and connectivity
"""
try:
# Gather environment information
env_info = {
'WEBSOCKET_ENABLED': os.getenv('WEBSOCKET_ENABLED'),
'WEBSOCKET_PATH': os.getenv('WEBSOCKET_PATH'),
'REQUEST_HEADERS': dict(request.headers),
'SERVER_SOFTWARE': os.getenv('SERVER_SOFTWARE'),
'FORWARDED_ALLOW_IPS': os.getenv('FORWARDED_ALLOW_IPS'),
'PROXY_PROTOCOL': os.getenv('PROXY_PROTOCOL'),
}
# Check if running behind proxy
is_proxied = any(h in request.headers for h in [
'X-Forwarded-For',
'X-Real-IP',
'X-Forwarded-Proto'
])
diagnostic_info = {
'environment': env_info,
'is_proxied': is_proxied,
'websocket_config': {
'ping_interval': app.config.get('WEBSOCKET_PING_INTERVAL'),
'ping_timeout': app.config.get('WEBSOCKET_PING_TIMEOUT'),
'max_message_size': app.config.get('WEBSOCKET_MAX_MESSAGE_SIZE')
}
}
return jsonify(diagnostic_info)
except Exception as e:
return jsonify({
'error': str(e),
'traceback': traceback.format_exc()
}), 500
@app.websocket('/ws/chat/status')
@login_required
async def ws_chat_status():
"""WebSocket endpoint for status updates"""
user_id = int(current_user.auth_id)
session_id = status_manager.create_session(user_id)
app.logger.info(f"WebSocket connection initiated for session {session_id}")
try:
# Verify authentication
if not current_user.is_authenticated:
app.logger.warning(f"Unauthorized WebSocket connection attempt for session {session_id}")
return
# Get user and verify status
user = await current_user.get_user()
if not user or user.status != 'Active':
app.logger.warning(f"Inactive or invalid user attempted WebSocket connection: {session_id}")
return
# Register the websocket connection
app.logger.info(f"Registering WebSocket connection for session {session_id}")
success = await status_manager.register_connection(session_id, websocket._get_current_object())
if not success:
app.logger.error(f"Failed to register WebSocket connection for session {session_id}")
return
# Send initial connection message
app.logger.info(f"Sending initial connection message for session {session_id}")
await status_manager.send_status_update(
session_id=session_id,
message="WebSocket connection established"
)
# Main message loop
while True:
try:
message = await websocket.receive()
app.logger.debug(f"Received WebSocket message for session {session_id}: {message}")
if not message:
continue
try:
data = json.loads(message)
if data.get('type') == 'ping':
await websocket.send(json.dumps({
'type': 'pong',
'timestamp': datetime.now().isoformat(),
'session_id': session_id
}))
except json.JSONDecodeError:
continue
except asyncio.CancelledError:
app.logger.info(f"WebSocket connection cancelled for session {session_id}")
break
except Exception as e:
app.logger.error(f"Error in WebSocket connection: {str(e)}")
app.logger.exception("Full traceback:")
finally:
app.logger.info(f"Cleaning up WebSocket connection for session {session_id}")
await status_manager.remove_connection(session_id)
app.logger.info(f"WebSocket cleanup complete for session {session_id}")
async def periodic_ping(connection_id):
"""Periodically send ping messages to keep the connection alive"""
try:
while True:
await asyncio.sleep(status_manager.PING_INTERVAL)
if not await status_manager.send_ping(connection_id):
break
except asyncio.CancelledError:
pass
except Exception as e:
app.logger.error(f"Error in periodic ping: {str(e)}")
@app.route('/chat/status/health')
@login_required
async def chat_status_health():
"""Health check endpoint for WebSocket connections"""
try:
quart_version = pkg_resources.get_distribution('quart').version
except:
quart_version = "unknown"
response_data = {
'status': 'healthy',
'active_connections': status_manager.connection_count,
'server_time': datetime.now().isoformat(),
'server_info': {
'worker_pid': os.getpid(),
'python_version': sys.version,
'quart_version': quart_version
}
}
return jsonify(response_data)
@app.route('/debug/config')
async def debug_config():
"""Debug endpoint to verify configuration"""
return jsonify({
'env_vars': {
'DEBUG_CONFIG': os.getenv('DEBUG_CONFIG'),
'WEBSOCKET_PATH': os.getenv('WEBSOCKET_PATH'),
'PORT': os.getenv('PORT'),
},
'routes': {
'websocket': '/ws/chat/status',
'health': '/chat/status/health'
},
'server_info': {
'worker_class': 'uvicorn.workers.UvicornWorker',
'gunicorn_config_path': os.path.exists('gunicorn.conf.py'),
'app_yaml_path': os.path.exists('.do/app.yaml')
}
})
@app.route('/debug/config/full')
@login_required
async def debug_config_full():
"""Detailed debug endpoint to verify configuration (login required)"""
import os
def mask_sensitive_value(key: str, value: str) -> str:
"""Mask sensitive values in environment variables"""
sensitive_keys = {'API_KEY', 'SECRET', 'PASSWORD', 'TOKEN', 'DATABASE_URL'}
if any(sensitive_word in key.upper() for sensitive_word in sensitive_keys):
if len(str(value)) > 8:
return f"{value[:4]}...{value[-4:]}"
return "****"
return value
try:
# Get all files in the current directory
files = os.listdir('.')
do_files = os.listdir('.do') if os.path.exists('.do') else []
# Read the contents of the config files
gunicorn_config = ''
if os.path.exists('gunicorn.conf.py'):
with open('gunicorn.conf.py', 'r') as f:
gunicorn_config = f.read()
app_yaml = ''
if os.path.exists('.do/app.yaml'):
with open('.do/app.yaml', 'r') as f:
app_yaml = f.read()
# Mask sensitive environment variables
masked_env_vars = {
key: mask_sensitive_value(key, value)
for key, value in os.environ.items()
}
response_data = {
'env_vars': masked_env_vars,
'files': {
'root': files,
'do_directory': do_files
},
'configs': {
'gunicorn': gunicorn_config,
'app_yaml': app_yaml
},
'routes': {
'websocket': '/ws/chat/status',
'health': '/chat/status/health'
},
'server_info': {
'worker_class': 'uvicorn.workers.UvicornWorker',
'gunicorn_config_path': os.path.exists('gunicorn.conf.py'),
'app_yaml_path': os.path.exists('.do/app.yaml'),
'current_directory': os.getcwd()
},
'user_info': {
'is_authenticated': current_user.is_authenticated
}
}
app.logger.info("Debug configuration accessed by authenticated user")
return jsonify(response_data)
except Exception as e:
app.logger.error("Error in debug configuration endpoint: %s", str(e))
return jsonify({'error': 'Internal server error'}), 500
@app.route('/debug/websocket-config')
@login_required
async def debug_websocket_config():
"""Debug endpoint to check WebSocket configuration"""
return jsonify({
'websocket_enabled': True,
'websocket_path': '/ws/chat/status',
'current_connections': status_manager.connection_count,
'server_info': {
'worker_class': 'uvicorn.workers.UvicornWorker',
'websocket_timeout': 300
}
})
# Ending of status update manager
# Begining of web search
#### Common helper functions for both standard and intelligent web search
@app.route('/api/system-messages/<int:system_message_id>/toggle-search', methods=['POST'])
@login_required
async def toggle_search(system_message_id):
"""
Toggle web search settings for a system message.
Args:
system_message_id (int): The ID of the system message to update
Returns:
JSON response with updated search settings
"""
try:
data = await request.get_json()
enable_web_search = data.get('enableWebSearch')
enable_intelligent_search = data.get('enableIntelligentSearch')
# Input validation
if enable_web_search is None:
return jsonify({'error': 'enableWebSearch parameter is required'}), 400
if not isinstance(enable_web_search, bool):
return jsonify({'error': 'enableWebSearch must be a boolean value'}), 400
async with get_session() as session:
# Get the system message
result = await session.execute(
select(SystemMessage).filter_by(id=system_message_id)
)
system_message = result.scalar_one_or_none()
if not system_message:
return jsonify({'error': 'System message not found'}), 404
# Get current user from database
user_result = await session.execute(
select(User).filter_by(id=int(current_user.auth_id))
)
current_user_obj = user_result.scalar_one_or_none()
if not current_user_obj:
return jsonify({'error': 'User not found'}), 404
# Check permissions
if not current_user_obj.is_admin and system_message.created_by != current_user_obj.id:
return jsonify({'error': 'Unauthorized to modify this system message'}), 403
# Update the search settings
system_message.enable_web_search = enable_web_search
# Add timestamp for tracking
system_message.updated_at = datetime.now(timezone.utc)
# Commit the changes
await session.commit()
app.logger.info(f"Search settings updated for system message {system_message_id} by user {current_user_obj.id}")
return jsonify({
'message': 'Search settings updated successfully',
'enableWebSearch': system_message.enable_web_search,
'enableIntelligentSearch': enable_intelligent_search,
'updatedAt': system_message.updated_at.isoformat()
}), 200
except Exception as e:
app.logger.error(f"Error in toggle_search: {str(e)}")
return jsonify({
'error': 'Failed to update search settings',
'details': str(e)
}), 500
async def understand_query(client, model: str, messages: List[Dict[str, str]], user_query: str, is_standard_search: bool = True, session_id: str = None) -> str:
app.logger.info(f"Starting query understanding for user query: '{user_query[:50]}'")
system_message = """Analyze the conversation history and the latest user query.
Provide a concise interpretation of what information the user is seeking,
considering the full context of the conversation."""
# Only include the conversation history, excluding the latest user query
conversation_history = "\n".join([f"{msg['role'].capitalize()}: {msg['content'][:50]}..." for msg in messages[:-1]])
# Add the latest user query separately
conversation_history += f"\nUser: {user_query}"
app.logger.debug(f"Constructed conversation history for query understanding: {conversation_history}")
messages_for_model = [
{"role": "system", "content": system_message},
{"role": "user", "content": conversation_history}
]
# Use gpt-4o-mini-2024-07-18 for standard search, otherwise use the provided model
query_model = "gpt-4o-mini-2024-07-18" if is_standard_search else model
app.logger.info(f"Sending request to model {query_model} for query interpretation")
try:
if session_id:
await update_status(f"Asking {query_model} for analysis to generate a query", session_id)
interpretation, _ = await get_response_from_model(client, query_model, messages_for_model, temperature=0.3)
interpreted_query = interpretation.strip()
app.logger.info(f"Query interpreted. Interpretation: '{interpreted_query[:100]}'")
if session_id:
await update_status("Query analysis completed", session_id)
return interpreted_query
except Exception as e:
app.logger.error(f"Error in understand_query: {str(e)}")
if session_id:
await update_status("Error occurred during query interpretation", session_id)
raise WebSearchError(f"Failed to interpret query: {str(e)}")
class WebSearchError(Exception):
"""Custom exception for web search errors."""
pass
class CustomResolver:
"""A simple custom DNS resolver that uses socket.getaddrinfo"""
def __init__(self, loop):
self._loop = loop
async def resolve(self, hostname, port=0, family=socket.AF_INET):
try:
result = await self._loop.run_in_executor(
None,
partial(
socket.getaddrinfo,
hostname,
port,
family,
socket.SOCK_STREAM
)
)
return [{'hostname': hostname, 'host': r[4][0], 'port': port} for r in result]
except socket.gaierror as e:
raise aiohttp.ClientError(f"DNS lookup failed for {hostname}: {str(e)}")
async def perform_web_search(query: str) -> List[Dict[str, str]]:
app.logger.info(f"Starting web search for query: '{query[:50]}'")
url = 'https://api.search.brave.com/res/v1/web/search'
headers = {
'Accept': 'application/json',