Mihirsingh1101 commited on
Commit
37de86d
·
verified ·
1 Parent(s): a5de502

Update rag_faiss.py

Browse files
Files changed (1) hide show
  1. rag_faiss.py +92 -50
rag_faiss.py CHANGED
@@ -27,22 +27,83 @@ print("🔹 Loading embedding model...")
27
  embedder = SentenceTransformer(EMBED_MODEL)
28
 
29
  # -------------------------------
30
- # SMALL TALK HANDLER
31
  # -------------------------------
32
- SMALL_TALK_RESPONSES = {
33
- "hello": "Hello! I’m the official virtual assistant for GUESSS India. How can I help you today?",
34
- "hi": "Hi there! I’m here to help you with information about GUESSS India.",
35
- "hey": "Hey! Feel free to ask me anything about GUESSS India.",
36
- "how are you": "I’m doing well, thank you! How can I assist you today?",
37
- "good morning": "Good morning! How can I help you with GUESSS India?",
38
- "good evening": "Good evening! How can I assist you today?",
39
- "thank you": "You’re welcome! If you have more questions about GUESSS India, I’m here to help.",
40
- "thanks": "You’re welcome! Happy to help."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  }
42
 
43
- def is_small_talk(query: str) -> bool:
44
  q = query.lower().strip()
45
- return any(key in q for key in SMALL_TALK_RESPONSES)
 
 
 
 
46
 
47
  # -------------------------------
48
  # VECTOR STORE
@@ -52,12 +113,12 @@ class VectorStore:
52
  print(f"🔹 Loading FAISS index from {INDEX_FILE}")
53
 
54
  if not os.path.exists(INDEX_FILE):
55
- raise FileNotFoundError("❌ FAISS index not found.")
56
-
57
- self.index = faiss.read_index(INDEX_FILE)
58
 
59
  if not os.path.exists(META_FILE):
60
- raise FileNotFoundError("❌ meta.pkl not found.")
 
 
61
 
62
  with open(META_FILE, "rb") as f:
63
  self.texts = pickle.load(f)
@@ -103,32 +164,25 @@ def call_openrouter(prompt, max_tokens=300):
103
  "max_tokens": max_tokens
104
  }
105
 
106
- try:
107
- r = requests.post(
108
- OPENROUTER_URL,
109
- headers=headers,
110
- json=payload,
111
- timeout=60
112
- )
113
- r.raise_for_status()
114
- return r.json()["choices"][0]["message"]["content"]
115
-
116
- except Exception as e:
117
- return f"❌ Error contacting OpenRouter: {e}"
118
 
119
  # -------------------------------
120
- # MAIN RAG LOGIC
121
  # -------------------------------
122
- def answer_question(vs, question):
123
- q = question.lower().strip()
124
-
125
- # 1️⃣ Handle greetings / small talk
126
- if is_small_talk(q):
127
- for key in SMALL_TALK_RESPONSES:
128
- if key in q:
129
- return SMALL_TALK_RESPONSES[key]
130
 
131
- # 2️⃣ Knowledge-based → FAISS
132
  contexts = vs.search(question, k=4)
133
 
134
  if not contexts:
@@ -154,15 +208,3 @@ QUESTION: {question}
154
  ANSWER:
155
  """
156
  return call_openrouter(prompt)
157
-
158
- # -------------------------------
159
- # EXAMPLE USAGE (for local test)
160
- # -------------------------------
161
- if __name__ == "__main__":
162
- vs = VectorStore()
163
-
164
- while True:
165
- user_q = input("\nYou: ")
166
- if user_q.lower() in ["exit", "quit"]:
167
- break
168
- print("Bot:", answer_question(vs, user_q))
 
27
  embedder = SentenceTransformer(EMBED_MODEL)
28
 
29
  # -------------------------------
30
+ # SMALL TALK / IDENTITY INTENTS
31
  # -------------------------------
32
+ SMALL_TALK_INTENTS = {
33
+ "greeting": {
34
+ "keywords": [
35
+ "hello", "hi", "hey", "hii", "hai",
36
+ "good morning", "good evening", "good afternoon"
37
+ ],
38
+ "answer": "Hello! I’m the official virtual assistant for GUESSS India. How can I help you today?"
39
+ },
40
+ "wellbeing": {
41
+ "keywords": [
42
+ "how are you", "how r you", "how are u",
43
+ "how do you do", "are you okay"
44
+ ],
45
+ "answer": "I’m doing well, thank you! How can I assist you with GUESSS India today?"
46
+ },
47
+ "identity": {
48
+ "keywords": [
49
+ "who are you", "what are you",
50
+ "tell me about yourself", "introduce yourself"
51
+ ],
52
+ "answer": "I’m a virtual assistant created to provide accurate and reliable information about GUESSS India."
53
+ },
54
+ "name": {
55
+ "keywords": [
56
+ "what is your name", "your name",
57
+ "do you have a name", "who should i call you"
58
+ ],
59
+ "answer": "I don’t have a personal name, but you can think of me as the GUESSS India Assistant."
60
+ },
61
+ "capabilities": {
62
+ "keywords": [
63
+ "what do you do", "what can you do",
64
+ "how can you help", "what help can you provide"
65
+ ],
66
+ "answer": (
67
+ "I answer questions related to GUESSS India, including surveys, programs, "
68
+ "campus ambassadors, podcasts, and general information."
69
+ )
70
+ },
71
+ "trust": {
72
+ "keywords": [
73
+ "can i trust you", "is your information reliable",
74
+ "are you reliable", "is this official"
75
+ ],
76
+ "answer": "Yes. My responses are based on approved and verified information provided by the GUESSS India team."
77
+ },
78
+ "human": {
79
+ "keywords": [
80
+ "are you human", "are you a real person",
81
+ "are you ai", "are you a bot"
82
+ ],
83
+ "answer": "No. I’m an AI-based assistant designed to share verified information from GUESSS India."
84
+ },
85
+ "availability": {
86
+ "keywords": [
87
+ "are you available", "are you always available",
88
+ "when are you available"
89
+ ],
90
+ "answer": "Yes. I’m available 24/7 on the GUESSS India website."
91
+ },
92
+ "thanks": {
93
+ "keywords": [
94
+ "thank you", "thanks", "thank u", "thx"
95
+ ],
96
+ "answer": "You’re welcome! If you have more questions about GUESSS India, I’m here to help."
97
+ }
98
  }
99
 
100
+ def handle_small_talk(query: str):
101
  q = query.lower().strip()
102
+ for intent in SMALL_TALK_INTENTS.values():
103
+ for kw in intent["keywords"]:
104
+ if kw in q:
105
+ return intent["answer"]
106
+ return None
107
 
108
  # -------------------------------
109
  # VECTOR STORE
 
113
  print(f"🔹 Loading FAISS index from {INDEX_FILE}")
114
 
115
  if not os.path.exists(INDEX_FILE):
116
+ raise FileNotFoundError("❌ index.faiss not found")
 
 
117
 
118
  if not os.path.exists(META_FILE):
119
+ raise FileNotFoundError("❌ meta.pkl not found")
120
+
121
+ self.index = faiss.read_index(INDEX_FILE)
122
 
123
  with open(META_FILE, "rb") as f:
124
  self.texts = pickle.load(f)
 
164
  "max_tokens": max_tokens
165
  }
166
 
167
+ r = requests.post(
168
+ OPENROUTER_URL,
169
+ headers=headers,
170
+ json=payload,
171
+ timeout=60
172
+ )
173
+ r.raise_for_status()
174
+ return r.json()["choices"][0]["message"]["content"]
 
 
 
 
175
 
176
  # -------------------------------
177
+ # MAIN ANSWER FUNCTION
178
  # -------------------------------
179
+ def answer_question(vs, question: str):
180
+ # 1️⃣ Small talk / identity
181
+ small_talk = handle_small_talk(question)
182
+ if small_talk:
183
+ return small_talk
 
 
 
184
 
185
+ # 2️⃣ Knowledge-based (RAG)
186
  contexts = vs.search(question, k=4)
187
 
188
  if not contexts:
 
208
  ANSWER:
209
  """
210
  return call_openrouter(prompt)