Njap-png commited on
Commit
cf5f816
·
1 Parent(s): b294605

Improve live web search integration and concise focused responses

Browse files
Files changed (1) hide show
  1. app.py +36 -13
app.py CHANGED
@@ -201,6 +201,18 @@ def safe_web_answer(query):
201
  def generate_response(message, history):
202
  low = message.strip().lower().strip("!?.,")
203
  greetings = {"hello", "hi", "hey", "greetings", "howdy", "yo"}
 
 
 
 
 
 
 
 
 
 
 
 
204
  if low in greetings:
205
  response = "Hello! I'm Agron, a self-improving neural interface. How can I help you today?"
206
  persist_interaction({"ts": __import__("time").time(), "user": message, "assistant": response})
@@ -221,14 +233,25 @@ def generate_response(message, history):
221
  response = "I've learned from you and my training sources: " + "; ".join(parts) + "."
222
  persist_interaction({"ts": __import__("time").time(), "user": message, "assistant": response})
223
  return response
 
 
 
 
 
 
 
 
 
224
  if VOICE_MODEL is not None:
225
  mem_lines = [f"User: {r['user']}\nAgron: {r['assistant']}" for r in interactions[-3:]]
226
  mem_ctx = "\n".join(mem_lines)
227
  user_content = message
228
  if mem_ctx:
229
  user_content = f"Relevant memory:\n{mem_ctx}\n\nUser: {message}"
 
 
230
  _msgs = [
231
- {"role": "system", "content": "You are Agron, a helpful, warm, knowledgeable AI assistant. Speak naturally and concisely. Stay focused on the question, avoid filler and repetition. If unsure, say so and suggest 'Search & learn web'."},
232
  {"role": "user", "content": user_content},
233
  ]
234
  _prompt = VOICE_TOK.apply_chat_template(_msgs, tokenize=False, add_generation_prompt=True)
@@ -606,26 +629,25 @@ def _decode_bing(url):
606
 
607
  def web_search(query, max_results=5):
608
  try:
609
- r = requests.get("https://www.bing.com/search", params={"q": query}, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}, timeout=20)
 
610
  soup = BeautifulSoup(r.text, "html.parser")
611
  out = []
612
- for h in soup.select("h2 a"):
613
- title = h.get_text(strip=True)
614
- raw = h.get("href", "")
615
- link = _decode_bing(raw) if "bing.com/ck/a" in raw else raw
616
- parent = h.find_parent("li") or h.find_parent("div")
617
- snippet = ""
618
- if parent:
619
- p = parent.select_one("p, .b_caption p, .snippet")
620
- if p:
621
- snippet = p.get_text(strip=True)
622
  if link and title:
623
  out.append({"title": title, "url": link, "snippet": snippet})
624
  if len(out) >= max_results:
625
  break
626
  if not out:
627
  try:
628
- dr = requests.get("https://api.duckduckgo.com/", params={"q": query, "format": "json", "no_html": "1"}, timeout=20)
629
  dd = dr.json()
630
  if dd.get("Abstract"):
631
  out.append({"title": dd.get("Heading", query), "url": dd.get("AbstractURL", ""), "snippet": dd.get("Abstract", "")})
@@ -637,6 +659,7 @@ def web_search(query, max_results=5):
637
  return []
638
 
639
 
 
640
  def crawl_page(url):
641
  try:
642
  r = requests.get(url, timeout=20, headers={"User-Agent": "Mozilla/5.0"}, allow_redirects=True)
 
201
  def generate_response(message, history):
202
  low = message.strip().lower().strip("!?.,")
203
  greetings = {"hello", "hi", "hey", "greetings", "howdy", "yo"}
204
+ search_intent = any(k in low for k in ["search", "find", "look up", "lookup", "browse", "web"])
205
+ if search_intent:
206
+ res = web_search(message, 5)
207
+ if res:
208
+ lines = [f"{i+1}. {r['title']} — {r.get('snippet','')} ({r['url']})" for i, r in enumerate(res)]
209
+ response = "Here are live web results:\n" + "\n".join(lines)
210
+ persist_interaction({"ts": __import__("time").time(), "user": message, "assistant": response})
211
+ return response
212
+ else:
213
+ response = "I couldn't find web results for that query. Try rephrasing it."
214
+ persist_interaction({"ts": __import__("time").time(), "user": message, "assistant": response})
215
+ return response
216
  if low in greetings:
217
  response = "Hello! I'm Agron, a self-improving neural interface. How can I help you today?"
218
  persist_interaction({"ts": __import__("time").time(), "user": message, "assistant": response})
 
233
  response = "I've learned from you and my training sources: " + "; ".join(parts) + "."
234
  persist_interaction({"ts": __import__("time").time(), "user": message, "assistant": response})
235
  return response
236
+ _web_ctx = ""
237
+ try:
238
+ if len(message.strip()) >= 4:
239
+ _res = web_search(message, 3)
240
+ _lines = [f"- {r['title']}: {r.get('snippet','')}" for r in _res if (r.get('snippet') or '').strip()]
241
+ if _lines:
242
+ _web_ctx = "Web search results (live):\n" + "\n".join(_lines[:3])
243
+ except Exception:
244
+ _web_ctx = ""
245
  if VOICE_MODEL is not None:
246
  mem_lines = [f"User: {r['user']}\nAgron: {r['assistant']}" for r in interactions[-3:]]
247
  mem_ctx = "\n".join(mem_lines)
248
  user_content = message
249
  if mem_ctx:
250
  user_content = f"Relevant memory:\n{mem_ctx}\n\nUser: {message}"
251
+ if _web_ctx:
252
+ user_content = f"{_web_ctx}\n\n{user_content}\n\nAnswer using the live web results above."
253
  _msgs = [
254
+ {"role": "system", "content": "You are Agron, a helpful AI assistant. You do have live web search results whenever they are included in the user message. Use them to answer accurately. Never say you cannot search or browse the internet. Stay concise and focused. If still unsure, suggest 'Search & learn web'."},
255
  {"role": "user", "content": user_content},
256
  ]
257
  _prompt = VOICE_TOK.apply_chat_template(_msgs, tokenize=False, add_generation_prompt=True)
 
629
 
630
  def web_search(query, max_results=5):
631
  try:
632
+ headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36", "Accept": "text/html"}
633
+ r = requests.post("https://html.duckduckgo.com/html/", data={"q": query}, headers=headers, timeout=25)
634
  soup = BeautifulSoup(r.text, "html.parser")
635
  out = []
636
+ for res in soup.select(".result"):
637
+ a = res.select_one("a.result__a")
638
+ if not a:
639
+ continue
640
+ title = a.get_text(strip=True)
641
+ link = a.get("href", "")
642
+ sn = res.select_one(".result__snippet")
643
+ snippet = sn.get_text(strip=True) if sn else ""
 
 
644
  if link and title:
645
  out.append({"title": title, "url": link, "snippet": snippet})
646
  if len(out) >= max_results:
647
  break
648
  if not out:
649
  try:
650
+ dr = requests.get("https://api.duckduckgo.com/", params={"q": query, "format": "json", "no_html": "1"}, headers=headers, timeout=20)
651
  dd = dr.json()
652
  if dd.get("Abstract"):
653
  out.append({"title": dd.get("Heading", query), "url": dd.get("AbstractURL", ""), "snippet": dd.get("Abstract", "")})
 
659
  return []
660
 
661
 
662
+
663
  def crawl_page(url):
664
  try:
665
  r = requests.get(url, timeout=20, headers={"User-Agent": "Mozilla/5.0"}, allow_redirects=True)