Spaces:
Sleeping
Sleeping
File size: 5,245 Bytes
9d0cb7b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | """Search + Pushover tools aligned with 2_lab2.ipynb (without notebook debug logging)."""
import json
import os
from urllib.parse import quote
import requests
from langchain_core.tools import Tool
def _serper_search(query: str) -> str:
key = os.getenv("SERPER_API_KEY", "")
if not key:
raise RuntimeError("SERPER_API_KEY not set")
resp = requests.post(
"https://google.serper.dev/search",
headers={"X-API-KEY": key, "Content-Type": "application/json"},
json={"q": query, "gl": "us", "hl": "en", "num": 10},
timeout=30,
)
resp.raise_for_status()
payload = resp.json()
answer_box = payload.get("answerBox") or payload.get("answer_box")
if isinstance(answer_box, dict):
for k in ("answer", "snippet", "title"):
if answer_box.get(k):
return str(answer_box[k])
organic = payload.get("organic")
if isinstance(organic, list) and organic:
top = organic[0]
parts = [top.get("title") or "", top.get("snippet") or "", top.get("link") or ""]
return "\n".join(p for p in parts if p).strip()
return json.dumps(payload)[:1000]
def _ddg_fallback(query: str) -> str:
url = f"https://api.duckduckgo.com/?q={quote(query)}&format=json&no_redirect=1&no_html=1"
resp = requests.get(url, timeout=30)
resp.raise_for_status()
payload = resp.json()
answer = (payload.get("Answer") or "").strip()
if answer:
return answer
abstract = (payload.get("AbstractText") or "").strip()
heading = (payload.get("Heading") or "").strip()
if abstract:
return "\n".join(s for s in [heading, abstract] if s).strip()
related = payload.get("RelatedTopics")
if isinstance(related, list):
for item in related:
if isinstance(item, dict) and item.get("Text"):
return str(item["Text"])
topics = item.get("Topics") if isinstance(item, dict) else None
if isinstance(topics, list):
for t in topics:
if isinstance(t, dict) and t.get("Text"):
return str(t["Text"])
return "No instant answer found."
def _wikipedia_fallback(query: str) -> str:
url = "https://en.wikipedia.org/w/api.php"
resp = requests.get(
url,
params={
"action": "opensearch",
"search": query,
"limit": 3,
"namespace": 0,
"format": "json",
},
timeout=30,
)
resp.raise_for_status()
data = resp.json()
titles = data[1] if len(data) > 1 else []
descs = data[2] if len(data) > 2 else []
urls = data[3] if len(data) > 3 else []
lines = []
for i in range(min(3, len(titles), len(urls))):
t, d, u = titles[i], descs[i] if i < len(descs) else "", urls[i]
lines.append(" - ".join(s for s in [t, d, u] if s))
out = "\n".join(lines).strip()
if out:
return out
rest_url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + quote(query.replace(" ", "_"))
resp2 = requests.get(rest_url, timeout=30)
resp2.raise_for_status()
p2 = resp2.json()
title = (p2.get("title") or "").strip()
extract = (p2.get("extract") or "").strip()
page = ((p2.get("content_urls") or {}).get("desktop") or {}).get("page")
return "\n".join(s for s in [title, extract, page] if s).strip() or "No Wikipedia results."
def _llm_fallback(query: str) -> str:
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
msg = llm.invoke(
[
{"role": "system", "content": "You are a helpful assistant. If you do not know, say so briefly."},
{"role": "user", "content": query},
]
)
return str(getattr(msg, "content", msg))
def safe_serper_run(query: str) -> str:
try:
return _serper_search(query)
except Exception:
try:
ddg = _ddg_fallback(query)
if ddg and ddg != "No instant answer found.":
return ddg
except Exception:
pass
try:
wiki = _wikipedia_fallback(query)
if wiki and wiki != "No Wikipedia results.":
return wiki
except Exception:
pass
return _llm_fallback(query)
pushover_token = os.getenv("PUSHOVER_TOKEN")
pushover_user = os.getenv("PUSHOVER_USER")
pushover_url = "https://api.pushover.net/1/messages.json"
def push(text: str) -> str:
"""Send a push notification (optional; set PUSHOVER_TOKEN and PUSHOVER_USER)."""
if not pushover_token or not pushover_user:
return "Pushover is not configured."
requests.post(
pushover_url,
data={"token": pushover_token, "user": pushover_user, "message": text},
timeout=30,
)
return "success"
def build_lab2_tools() -> list:
tool_search = Tool(
name="search",
func=safe_serper_run,
description="Useful for when you need more information from an online search",
)
tool_push = Tool(
name="send_push_notification",
func=push,
description="useful for when you want to send a push notification",
)
return [tool_search, tool_push]
|