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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -42
app.py CHANGED
@@ -1,67 +1,68 @@
1
  import gradio as gr
2
  import faiss
3
- import numpy as np
4
  import json
5
- from sentence_transformers import SentenceTransformer
6
  import os
 
 
 
 
 
7
 
8
- # Load your content and index
 
9
  with open("texts.json", "r") as f:
10
  texts = json.load(f)
11
 
12
- index = faiss.read_index("faiss_index.bin")
 
 
13
 
14
- # Load embedding model
15
- embed_model = SentenceTransformer("all-MiniLM-L6-v2")
 
 
 
 
 
 
 
 
16
 
17
- # Helper to retrieve relevant chunks
18
- def retrieve_chunks(query, k=5):
19
- query_emb = embed_model.encode([query])
20
- D, I = index.search(np.array(query_emb), k)
21
- return [texts[i] for i in I[0] if i < len(texts)]
22
 
23
- # Main chatbot function
24
- def rag_chatbot(message, history, request: gr.Request):
25
- user_header = request.headers.get("X-Source", "")
26
- if user_header == "wordpress":
27
- # RAG logic for WordPress embed
28
- context_chunks = retrieve_chunks(message)
29
- context = "\n".join(context_chunks)
30
- if not context.strip():
31
- return "❌ I'm sorry, I can only assist with questions related to LogiqCurve.com."
32
- prompt = f"Answer based ONLY on this content:\n{context}\n\nQuestion: {message}"
33
- else:
34
- # Public fallback (general AI)
35
- prompt = message
36
 
37
- # Use OpenRouter API
38
  headers = {
39
- "Authorization": f"Bearer {os.environ.get('OPENROUTER_API_KEY')}",
40
  "Content-Type": "application/json"
41
  }
42
 
43
  payload = {
44
- "model": "deepseek/deepseek-chat-v3-0324:free",
45
- "messages": [
46
- {"role": "system", "content": "You are a helpful assistant."},
47
- {"role": "user", "content": prompt}
48
- ]
49
  }
50
 
51
  try:
52
- import requests
53
- res = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload)
54
- res.raise_for_status()
55
- return res.json()["choices"][0]["message"]["content"]
56
  except Exception as e:
57
- return f"❌ API Error: {e}"
 
 
58
 
59
- # Gradio interface
60
- iface = gr.ChatInterface(
61
- fn=rag_chatbot,
62
- title="LogiqCurve WordPress Assistant",
63
- description="Answers only based on the content of LogiqCurve.com",
64
  theme="soft"
65
  )
66
 
67
- iface.launch()
 
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}",
43
  "Content-Type": "application/json"
44
  }
45
 
46
  payload = {
47
+ "model": MODEL,
48
+ "messages": messages
 
 
 
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()