1
1
from flask import Flask , request , jsonify , render_template , Response , stream_with_context , session , send_from_directory
2
2
from flask_wtf .csrf import CSRFProtect
3
- from rag_system import rag_system
3
+ from rag_system import RAGSystem
4
4
import hashlib
5
5
import subprocess
6
6
import os
26
26
app .config ['SESSION_COOKIE_HTTPONLY' ] = True
27
27
app .config ['SESSION_COOKIE_SECURE' ] = bool (os .getenv ('SESSION_COOKIE_SECURE' ))
28
28
29
+ app .rag_system = RAGSystem ()
30
+
29
31
csrf = CSRFProtect (app )
30
32
31
33
# Initialize Redis connection
@@ -52,13 +54,13 @@ def handle_ask_request(request, session):
52
54
if 'anonymous_id' not in session :
53
55
session ['anonymous_id' ] = str (uuid .uuid4 ())
54
56
anonymous_id = session ['anonymous_id' ]
55
-
57
+
56
58
# Determine the source based on the user agent
57
59
user_agent = request .headers .get ('User-Agent' , '' )
58
60
source = 'Ask Defang Discord Bot' if 'Discord Bot' in user_agent else 'Ask Defang Website'
59
61
60
62
# 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' )
62
64
63
65
@app .route ('/' , methods = ['GET' , 'POST' ])
64
66
def index ():
@@ -110,7 +112,7 @@ def trigger_rebuild():
110
112
111
113
print ("Rebuilding embeddings..." )
112
114
try :
113
- rag_system .rebuild_embeddings ()
115
+ app . rag_system .rebuild_embeddings ()
114
116
except Exception as e :
115
117
print (f"Error rebuilding embeddings: { str (e )} " )
116
118
return jsonify ({"error" : "Error rebuilding embeddings" , "details" : str (e )}), 500
@@ -136,7 +138,7 @@ def debug_context():
136
138
query = data .get ('query' , '' )
137
139
if not query :
138
140
return jsonify ({"error" : "Query is required" }), 400
139
- context = rag_system .get_context (query )
141
+ context = app . rag_system .get_context (query )
140
142
return jsonify ({"context" : context })
141
143
142
144
@@ -180,7 +182,7 @@ def handle_webhook():
180
182
return 'OK'
181
183
# Fetch the conversation and generate an LLM answer for the user
182
184
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 )
184
186
else :
185
187
logger .info (f"Received webhook for unsupported topic: { topic } ; no action taken." )
186
188
return 'OK'
0 commit comments