mirxakamran893 commited on
Commit
d1406e8
Β·
verified Β·
1 Parent(s): efbfb8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -28
app.py CHANGED
@@ -1,45 +1,48 @@
1
  import gradio as gr
2
- import faiss
3
- import numpy as np
4
  import json
5
  import os
6
- import requests
 
7
  from sentence_transformers import SentenceTransformer
8
 
9
- # Load embedding model
10
- embed_model = SentenceTransformer("all-MiniLM-L6-v2")
11
-
12
- # Load your data
13
  with open("texts.json", "r") as f:
14
  texts = json.load(f)
15
 
16
- index = faiss.read_index("faiss_index.bin")
17
- text_embeddings = embed_model.encode(texts)
18
 
19
- # API info
20
  API_KEY = os.environ.get("OPENROUTER_API_KEY")
21
  MODEL = "deepseek/deepseek-chat-v3-0324:free"
22
 
23
- def get_relevant_context(question, top_k=3, threshold=0.6):
24
- question_embedding = embed_model.encode([question])
25
- distances, indices = index.search(np.array(question_embedding), top_k)
26
-
27
- context = []
28
- for i, dist in zip(indices[0], distances[0]):
29
- if dist < threshold:
30
- context.append(texts[i])
31
- return context
32
 
 
33
  def chat_with_data(message, history):
 
 
 
 
 
 
34
  context = get_relevant_context(message)
35
  if not context:
36
- return "❌ Sorry, I can only help with topics related to LogiqCurve."
37
 
38
  context_text = "\n".join(context)
39
  prompt = f"You are a helpful assistant for LogiqCurve. Use only the following context:\n\n{context_text}\n\nUser: {message}"
40
 
41
- messages = [{"role": "system", "content": "You are a helpful assistant that only uses provided context."}]
42
- messages.append({"role": "user", "content": prompt})
 
 
43
 
44
  headers = {
45
  "Authorization": f"Bearer {API_KEY}",
@@ -54,15 +57,14 @@ def chat_with_data(message, history):
54
  try:
55
  res = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
56
  res.raise_for_status()
57
- reply = res.json()["choices"][0]["message"]["content"]
58
  except Exception as e:
59
- reply = f"❌ Error: {e}"
60
-
61
- return reply
62
 
 
63
  gr.ChatInterface(
64
  fn=chat_with_data,
65
- title="LogiqCurve Assistant",
66
- description="Ask anything about LogiqCurve (based on website data only)",
67
  theme="soft"
68
  ).launch()
 
1
  import gradio as gr
2
+ import requests
 
3
  import json
4
  import os
5
+ import faiss
6
+ import numpy as np
7
  from sentence_transformers import SentenceTransformer
8
 
9
+ # βœ… Load vector store and data
10
+ index = faiss.read_index("faiss_index.bin")
 
 
11
  with open("texts.json", "r") as f:
12
  texts = json.load(f)
13
 
14
+ # βœ… Load embedding model
15
+ model = SentenceTransformer("all-MiniLM-L6-v2")
16
 
17
+ # βœ… OpenRouter setup
18
  API_KEY = os.environ.get("OPENROUTER_API_KEY")
19
  MODEL = "deepseek/deepseek-chat-v3-0324:free"
20
 
21
+ # βœ… Helper: Find top-k relevant context
22
+ def get_relevant_context(query, k=5):
23
+ query_vector = model.encode([query])
24
+ scores, indices = index.search(np.array(query_vector), k)
25
+ return [texts[i] for i in indices[0] if i < len(texts)]
 
 
 
 
26
 
27
+ # βœ… Chat logic
28
  def chat_with_data(message, history):
29
+ greetings = ["hi", "hello", "hey", "salam", "assalamualaikum", "good morning", "good evening"]
30
+ message_lower = message.lower().strip()
31
+
32
+ if any(greet in message_lower for greet in greetings):
33
+ return "πŸ‘‹ Hello! How can I assist you regarding LogiqCurve today?"
34
+
35
  context = get_relevant_context(message)
36
  if not context:
37
+ return "❌ Sorry, I can only answer questions related to LogiqCurve and its services."
38
 
39
  context_text = "\n".join(context)
40
  prompt = f"You are a helpful assistant for LogiqCurve. Use only the following context:\n\n{context_text}\n\nUser: {message}"
41
 
42
+ messages = [
43
+ {"role": "system", "content": "You are a helpful assistant that answers only using provided context."},
44
+ {"role": "user", "content": prompt}
45
+ ]
46
 
47
  headers = {
48
  "Authorization": f"Bearer {API_KEY}",
 
57
  try:
58
  res = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
59
  res.raise_for_status()
60
+ return res.json()["choices"][0]["message"]["content"]
61
  except Exception as e:
62
+ return f"❌ Error: {e}"
 
 
63
 
64
+ # βœ… Gradio UI
65
  gr.ChatInterface(
66
  fn=chat_with_data,
67
+ title="MK Assistant",
68
+ description="Ask questions related to LogiqCurve. Chat is limited to website-related content only.",
69
  theme="soft"
70
  ).launch()