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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -32
app.py CHANGED
@@ -1,42 +1,45 @@
1
  import gradio as gr
2
  import faiss
3
- import json
4
  import numpy as np
 
5
  import os
6
- from sentence_transformers import SentenceTransformer
7
  import requests
 
8
 
9
  # Load embedding model
10
  embed_model = SentenceTransformer("all-MiniLM-L6-v2")
11
 
12
- # Load FAISS index and texts
13
- index = faiss.read_index("faiss_index.bin")
14
  with open("texts.json", "r") as f:
15
  texts = json.load(f)
16
 
17
- # OpenRouter API Key (Set as secret in Hugging Face Space settings)
 
 
 
18
  API_KEY = os.environ.get("OPENROUTER_API_KEY")
19
  MODEL = "deepseek/deepseek-chat-v3-0324:free"
20
 
21
- # Perform semantic search using FAISS
22
- def search_context(query, k=5):
23
- query_embedding = embed_model.encode([query])
24
- distances, indices = index.search(np.array(query_embedding), k)
25
- relevant_chunks = [texts[i] for i in indices[0] if i < len(texts)]
26
- return "\n".join(relevant_chunks)
 
 
 
27
 
28
- def chat_fn(message, history):
29
- # Search knowledge base
30
- context = search_context(message)
 
31
 
32
- if not context.strip():
33
- return "❌ Sorry, I can only answer questions related to the content of logiqcurve.com."
34
 
35
- # Construct prompt
36
- messages = [
37
- {"role": "system", "content": "You are an assistant that only answers based on the provided CONTEXT. Do not answer from general knowledge. If the answer is not in the CONTEXT, reply with 'Sorry, I can only answer questions related to the content of logiqcurve.com.'"},
38
- {"role": "user", "content": f"CONTEXT:\n{context}\n\nQUESTION:\n{message}"},
39
- ]
40
 
41
  headers = {
42
  "Authorization": f"Bearer {API_KEY}",
@@ -49,20 +52,17 @@ def chat_fn(message, history):
49
  }
50
 
51
  try:
52
- response = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
53
- response.raise_for_status()
54
- reply = response.json()["choices"][0]["message"]["content"]
55
  except Exception as e:
56
  reply = f"❌ Error: {e}"
57
 
58
  return reply
59
 
60
- # Gradio Chat Interface (for Hugging Face Space)
61
- chatbot = gr.ChatInterface(
62
- fn=chat_fn,
63
- title="LogiqCurve ChatBot",
64
- description="Ask anything about logiqcurve.com. This bot only answers based on its content.",
65
  theme="soft"
66
- )
67
-
68
- chatbot.launch()
 
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}",
 
52
  }
53
 
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()