11from flask import Flask , request , jsonify , render_template , Response , stream_with_context , session , send_from_directory
22from flask_wtf .csrf import CSRFProtect
3- from rag_system import rag_system
3+ from rag_system import RAGSystem
44import hashlib
55import subprocess
66import os
2626app .config ['SESSION_COOKIE_HTTPONLY' ] = True
2727app .config ['SESSION_COOKIE_SECURE' ] = bool (os .getenv ('SESSION_COOKIE_SECURE' ))
2828
29+ app .rag_system = RAGSystem ()
30+
2931csrf = CSRFProtect (app )
3032
3133# Initialize Redis connection
@@ -52,13 +54,13 @@ def handle_ask_request(request, session):
5254 if 'anonymous_id' not in session :
5355 session ['anonymous_id' ] = str (uuid .uuid4 ())
5456 anonymous_id = session ['anonymous_id' ]
55-
57+
5658 # Determine the source based on the user agent
5759 user_agent = request .headers .get ('User-Agent' , '' )
5860 source = 'Ask Defang Discord Bot' if 'Discord Bot' in user_agent else 'Ask Defang Website'
5961
6062 # Use the shared generate function directly
61- return Response (stream_with_context (generate (query , source , anonymous_id )), content_type = 'text/markdown' )
63+ return Response (stream_with_context (generate (app . rag_system , query , source , anonymous_id )), content_type = 'text/markdown' )
6264
6365@app .route ('/' , methods = ['GET' , 'POST' ])
6466def index ():
@@ -110,7 +112,7 @@ def trigger_rebuild():
110112
111113 print ("Rebuilding embeddings..." )
112114 try :
113- rag_system .rebuild_embeddings ()
115+ app . rag_system .rebuild_embeddings ()
114116 except Exception as e :
115117 print (f"Error rebuilding embeddings: { str (e )} " )
116118 return jsonify ({"error" : "Error rebuilding embeddings" , "details" : str (e )}), 500
@@ -136,7 +138,7 @@ def debug_context():
136138 query = data .get ('query' , '' )
137139 if not query :
138140 return jsonify ({"error" : "Query is required" }), 400
139- context = rag_system .get_context (query )
141+ context = app . rag_system .get_context (query )
140142 return jsonify ({"context" : context })
141143
142144
@@ -180,7 +182,7 @@ def handle_webhook():
180182 return 'OK'
181183 # Fetch the conversation and generate an LLM answer for the user
182184 logger .info (f"Detected a user reply in conversation { conversation_id } ; fetching an answer from LLM..." )
183- answer_intercom_conversation (conversation_id )
185+ answer_intercom_conversation (app . rag_system , conversation_id )
184186 else :
185187 logger .info (f"Received webhook for unsupported topic: { topic } ; no action taken." )
186188 return 'OK'
0 commit comments