markobinario commited on
Commit
77cf9e6
·
verified ·
1 Parent(s): 04963f4

Update ai_chatbot.py

Browse files
Files changed (1) hide show
  1. ai_chatbot.py +56 -1
ai_chatbot.py CHANGED
@@ -2,6 +2,8 @@ from sentence_transformers import SentenceTransformer
2
  import numpy as np
3
  from typing import List, Dict, Tuple
4
  import re
 
 
5
 
6
  class AIChatbot:
7
  def __init__(self):
@@ -97,4 +99,57 @@ class AIChatbot:
97
 
98
  def add_faq(self, question: str, answer: str) -> bool:
99
  """No-op when FAQs are disabled."""
100
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import numpy as np
3
  from typing import List, Dict, Tuple
4
  import re
5
+ import os
6
+ import requests
7
 
8
  class AIChatbot:
9
  def __init__(self):
 
99
 
100
  def add_faq(self, question: str, answer: str) -> bool:
101
  """No-op when FAQs are disabled."""
102
+ return False
103
+
104
+
105
+ # ===== UI helpers for Hugging Face integration =====
106
+ def chat_with_bot_via_gateway(chatbot: "AIChatbot", message: str, history: List[Tuple[str, str]], gateway_base_url: str | None = None) -> str:
107
+ if chatbot is None:
108
+ return "Sorry, the chatbot is not available at the moment. Please try again later."
109
+ if not message or not message.strip():
110
+ return "Please enter a message to start the conversation."
111
+
112
+ base_url = gateway_base_url or os.environ.get('GATEWAY_BASE_URL', 'https://database-46m3.onrender.com')
113
+
114
+ try:
115
+ resp = requests.get(f"{base_url}/faqs", params={"question": message}, timeout=10)
116
+ if resp.ok:
117
+ data = resp.json()
118
+ if data.get('answer'):
119
+ return data['answer']
120
+ except Exception as e:
121
+ print(f"FAQ gateway error: {e}")
122
+
123
+ answer, confidence = chatbot.find_best_match(message)
124
+
125
+ try:
126
+ if confidence < 0.7 and (not answer or 'specifically designed' in (answer or '').lower()):
127
+ requests.post(f"{base_url}/unanswered_questions", json={"question": message}, timeout=10)
128
+ except Exception as e:
129
+ print(f"Log unanswered error: {e}")
130
+
131
+ return answer
132
+
133
+
134
+ def get_faqs_via_gateway(gateway_base_url: str | None = None) -> str:
135
+ base_url = gateway_base_url or os.environ.get('GATEWAY_BASE_URL', 'https://database-46m3.onrender.com')
136
+ try:
137
+ sample_questions = [
138
+ "What are the admission requirements?",
139
+ "How to apply?",
140
+ "Where is the campus located?"
141
+ ]
142
+ items: List[Dict[str, str]] = []
143
+ for q in sample_questions:
144
+ r = requests.get(f"{base_url}/faqs", params={"question": q}, timeout=10)
145
+ if r.ok and r.json().get('answer'):
146
+ items.append({"question": q, "answer": r.json()['answer']})
147
+ if not items:
148
+ return "No FAQs available at the moment."
149
+ faq_text = "## 📚 Frequently Asked Questions\n\n"
150
+ for i, faq in enumerate(items, 1):
151
+ faq_text += f"**{i}. {faq['question']}**\n"
152
+ faq_text += f"{faq['answer']}\n\n"
153
+ return faq_text
154
+ except Exception as e:
155
+ return f"Could not load FAQs from gateway: {e}"