mirxakamran893 commited on
Commit
ad421bc
Β·
verified Β·
1 Parent(s): 39f5430

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -44
app.py CHANGED
@@ -6,47 +6,36 @@ import numpy as np
6
  import json
7
  from sentence_transformers import SentenceTransformer
8
 
9
- # βœ… Load context
10
  with open("texts.json", "r", encoding="utf-8") as f:
11
  texts = json.load(f)
12
 
13
  index = faiss.read_index("faiss_index.bin")
14
  embed_model = SentenceTransformer("all-MiniLM-L6-v2")
15
 
16
- # βœ… API Setup
17
  API_KEY = os.environ.get("OPENROUTER_API_KEY")
18
- MODEL = "meta-llama/llama-3.3-8b-instruct:free"
19
 
20
- # βœ… Context search
21
- def get_context(query, top_k=5, min_score=0.05):
22
  query_vec = embed_model.encode([query])
23
  D, I = index.search(np.array(query_vec), top_k)
24
-
25
- # If top score is too low, reject
26
- if D[0][0] < min_score:
27
- return None
28
-
29
  return "\n".join([texts[i] for i in I[0]])
30
 
31
- # βœ… Chat function
32
  def chat_fn(message, history):
33
- context = get_context(message)
34
- if context is None:
35
- return history[:-1] + [(message, "❌ Sorry! I cannot answer that.")]
36
-
37
  headers = {
38
  "Authorization": f"Bearer {API_KEY}",
39
  "Content-Type": "application/json"
40
  }
41
 
 
 
42
  messages = [
43
- {
44
- "role": "system",
45
- "content": f"You are a helpful assistant. Use ONLY this context to answer:\n{context}\nIf not found in context, reply: 'Sorry! I cannot answer that.'"
46
- }
47
  ]
48
 
49
- for user, assistant in history[:-1]:
50
  messages.append({"role": "user", "content": user})
51
  messages.append({"role": "assistant", "content": assistant})
52
 
@@ -64,28 +53,10 @@ def chat_fn(message, history):
64
  except Exception as e:
65
  reply = f"❌ Error: {e}"
66
 
67
- return history[:-1] + [(message, reply)]
68
-
69
- # βœ… UI
70
- with gr.Blocks(css="""
71
- .footer {display: none !important;}
72
- #chat-window {height: 500px !important; overflow-y: auto;}
73
- """) as demo:
74
- chatbot = gr.Chatbot(elem_id="chat-window")
75
- state = gr.State([])
76
-
77
- with gr.Row():
78
- msg = gr.Textbox(placeholder="Type your message and press enter...", scale=9)
79
-
80
- # Typing sim
81
- def user_send(message, history):
82
- return "", history + [(message, "⏳ ...")]
83
-
84
- def complete_chat(message, history):
85
- return chat_fn(message, history)
86
-
87
- msg.submit(user_send, [msg, state], [msg, chatbot]).then(
88
- complete_chat, [msg, state], [chatbot]
89
- )
90
 
91
- demo.launch()
 
 
 
 
 
6
  import json
7
  from sentence_transformers import SentenceTransformer
8
 
9
+ # βœ… Load context data
10
  with open("texts.json", "r", encoding="utf-8") as f:
11
  texts = json.load(f)
12
 
13
  index = faiss.read_index("faiss_index.bin")
14
  embed_model = SentenceTransformer("all-MiniLM-L6-v2")
15
 
 
16
  API_KEY = os.environ.get("OPENROUTER_API_KEY")
17
+ MODEL = "qwen/qwen-2.5-coder-32b-instruct:free"
18
 
19
+ # βœ… RAG context retriever
20
+ def get_context(query, top_k=5):
21
  query_vec = embed_model.encode([query])
22
  D, I = index.search(np.array(query_vec), top_k)
 
 
 
 
 
23
  return "\n".join([texts[i] for i in I[0]])
24
 
25
+ # βœ… Chat handler
26
  def chat_fn(message, history):
 
 
 
 
27
  headers = {
28
  "Authorization": f"Bearer {API_KEY}",
29
  "Content-Type": "application/json"
30
  }
31
 
32
+ context = get_context(message)
33
+
34
  messages = [
35
+ {"role": "system", "content": f"You are a helpful assistant. ONLY use the context below to answer:\n\n{context}"}
 
 
 
36
  ]
37
 
38
+ for user, assistant in history:
39
  messages.append({"role": "user", "content": user})
40
  messages.append({"role": "assistant", "content": assistant})
41
 
 
53
  except Exception as e:
54
  reply = f"❌ Error: {e}"
55
 
56
+ return reply
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ # βœ… Launch chatbot without title or description
59
+ gr.ChatInterface(
60
+ fn=chat_fn,
61
+ theme="soft"
62
+ ).launch()