1+ """
2+ TechCorp AI Assistant - Interactive RAG Chat Interface
3+ """
4+
5+ from flask import Flask , render_template , request , jsonify , Response , stream_with_context
6+ import os
7+ import sys
8+ from datetime import datetime
9+ import json
10+ import time
11+
12+ # Add core modules to path
13+ sys .path .append (os .path .join (os .path .dirname (__file__ ), 'core' ))
14+
15+ from core .vector_engine import VectorEngine
16+ from core .chat_engine import ChatEngine
17+ from core .document_processor import DocumentProcessor
18+
19+ app = Flask (__name__ )
20+
21+ # Initialize RAG components
22+ print ("\n " + "=" * 60 )
23+ print ("🚀 Starting TechCorp AI Assistant" )
24+ print ("=" * 60 )
25+ print ("\n [INIT] Loading RAG components..." )
26+
27+ vector_engine = VectorEngine ()
28+ print ("[INIT] Vector engine ready" )
29+
30+ chat_engine = ChatEngine (vector_engine )
31+ print ("[INIT] Chat engine ready" )
32+
33+ doc_processor = DocumentProcessor (vector_engine )
34+ print ("[INIT] Document processor ready" )
35+
36+ @app .route ('/' )
37+ def index ():
38+ """Render the chat interface"""
39+ return render_template ('index.html' )
40+ @app .route ('/chat' , methods = ['POST' ])
41+ def chat ():
42+ """Handle chat messages"""
43+ try :
44+ data = request .json
45+ user_message = data .get ('message' , '' )
46+
47+ if not user_message :
48+ return jsonify ({'error' : 'No message provided' }), 400
49+
50+ # Get response from RAG system
51+ response = chat_engine .get_response (user_message )
52+
53+ return jsonify ({
54+ 'response' : response ['answer' ],
55+ 'sources' : response ['sources' ],
56+ 'confidence' : response ['confidence' ],
57+ 'timestamp' : datetime .now ().isoformat ()
58+ })
59+
60+ except Exception as e :
61+ return jsonify ({'error' : str (e )}), 500
62+
63+ @app .route ('/api/chat/stream' , methods = ['POST' ])
64+ def chat_stream ():
65+ """Handle chat messages with streaming response"""
66+ def generate ():
67+ try :
68+ data = request .json
69+ user_message = data .get ('message' , '' )
70+
71+ if not user_message :
72+ yield f"data: { json .dumps ({'error' : 'No message provided' })} \n \n "
73+ return
74+
75+ # Send initial event
76+ yield f"data: { json .dumps ({'event' : 'start' })} \n \n "
77+
78+ # Get response from RAG system
79+ response = chat_engine .get_response (user_message )
80+
81+ # Stream the response word by word
82+ words = response ['answer' ].split ()
83+ for i , word in enumerate (words ):
84+ time .sleep (0.05 ) # Small delay for streaming effect
85+ yield f"data: { json .dumps ({'event' : 'token' , 'content' : word + ' ' })} \n \n "
86+
87+ # Send sources at the end
88+ yield f"data: { json .dumps ({'event' : 'sources' , 'sources' : response ['sources' ], 'confidence' : response ['confidence' ]})} \n \n "
89+
90+ # Send completion event
91+ yield f"data: { json .dumps ({'event' : 'done' })} \n \n "
92+
93+ except Exception as e :
94+ yield f"data: { json .dumps ({'event' : 'error' , 'error' : str (e )})} \n \n "
95+
96+ return Response (
97+ stream_with_context (generate ()),
98+ mimetype = 'text/event-stream' ,
99+ headers = {
100+ 'Cache-Control' : 'no-cache' ,
101+ 'X-Accel-Buffering' : 'no'
102+ }
103+ )
104+
105+ @app .route ('/api/status' , methods = ['GET' ])
106+ def status ():
107+ """Get system status"""
108+ try :
109+ stats = vector_engine .get_stats ()
110+ return jsonify ({
111+ 'status' : 'operational' ,
112+ 'documents' : stats ['total_documents' ],
113+ 'chunks' : stats ['total_chunks' ],
114+ 'last_updated' : stats ['last_updated' ]
115+ })
116+ except Exception as e :
117+ return jsonify ({
118+ 'status' : 'error' ,
119+ 'message' : str (e )
120+ }), 500
121+
122+
123+ if __name__ == '__main__' :
124+ # Initialize database with documents on first run
125+ if not vector_engine .is_initialized ():
126+ print ("First run detected. Processing TechCorp documents..." )
127+ doc_processor .process_all_documents ()
128+ print ("Document processing complete!" )
129+
130+ # Run the app
131+ app .run (host = '0.0.0.0' , port = 5252 , debug = True )
0 commit comments