Haseeb-001 commited on
Commit
f30ac75
·
verified ·
1 Parent(s): 1be16e0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -0
app.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import faiss
3
+ import pickle
4
+ import streamlit as st
5
+ from groq import Groq
6
+ from sentence_transformers import SentenceTransformer
7
+
8
+ # Initialize the Groq client for Llama LLM
9
+ GROQ_API_KEY = "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"
10
+ client = Groq(
11
+ api_key=GROQ_API_KEY,
12
+ )
13
+
14
+ # Load FAISS index and metadata
15
+ def load_faiss_index(index_path, metadata_path):
16
+ if not os.path.exists(index_path) or not os.path.exists(metadata_path):
17
+ raise FileNotFoundError("FAISS index or metadata file not found!")
18
+ index = faiss.read_index(index_path)
19
+ with open(metadata_path, "rb") as f:
20
+ metadata = pickle.load(f)
21
+ return index, metadata
22
+
23
+ # Load the FAISS index and metadata
24
+ index, metadata = load_faiss_index("faiss_index.bin", "metadata.pkl")
25
+
26
+ # Initialize the SentenceTransformer for embedding
27
+ embedder = SentenceTransformer("all-MiniLM-L6-v2")
28
+
29
+ # Streamlit UI Configuration
30
+ st.set_page_config(page_title="RAG Chatbot: Healthcare, Education & Finance", layout="wide")
31
+ st.title("🤖 RAG Chatbot: Healthcare, Education & Finance")
32
+ st.markdown("Welcome to the **AI Chatbot**! Ask anything about **healthcare**, **education**, or **finance**.")
33
+
34
+ # Initialize session state for chat history
35
+ if "messages" not in st.session_state:
36
+ st.session_state.messages = []
37
+
38
+ # Input field for user queries
39
+ user_input = st.text_input("💬 Type your message:", placeholder="Ask me anything...")
40
+
41
+ # Function to generate Llama LLM responses using Groq API
42
+ def generate_llama_response(user_query, context):
43
+ response = client.chat.completions.create(
44
+ messages=[
45
+ {"role": "system", "content": "You are an expert assistant in Healthcare, Education, and Finance."},
46
+ {"role": "user", "content": f"Context: {context}\n\nQuery: {user_query}"}
47
+ ],
48
+ model="llama-3.3-70b-versatile",
49
+ stream=False,
50
+ )
51
+ return response.choices[0].message.content
52
+
53
+ # Function to handle user queries and retrieve responses
54
+ def handle_query(user_query):
55
+ # Embed the user query and search FAISS
56
+ query_vector = embedder.encode([user_query])
57
+ _, top_indices = index.search(query_vector, k=3)
58
+ relevant_contexts = [metadata[i] for i in top_indices[0]]
59
+
60
+ # Combine retrieved chunks into context
61
+ context = "\n".join(relevant_contexts)
62
+
63
+ # Generate response from Llama LLM
64
+ response = generate_llama_response(user_query, context)
65
+
66
+ # Save user input and response to FAISS for tracking
67
+ user_vector = embedder.encode([user_query])
68
+ index.add(user_vector)
69
+ metadata.append(user_query)
70
+ faiss.write_index(index, "faiss_index.bin")
71
+ with open("metadata.pkl", "wb") as f:
72
+ pickle.dump(metadata, f)
73
+
74
+ return response
75
+
76
+ # Process user input
77
+ if user_input:
78
+ # Display user message
79
+ st.session_state.messages.append({"role": "user", "content": user_input})
80
+
81
+ # Get bot response
82
+ bot_response = handle_query(user_input)
83
+ st.session_state.messages.append({"role": "assistant", "content": bot_response})
84
+
85
+ # Display chat messages
86
+ for message in st.session_state.messages:
87
+ if message["role"] == "user":
88
+ st.markdown(f"**You:** {message['content']}")
89
+ else:
90
+ st.markdown(f"**Bot:** {message['content']}")