EnochSearch / tools_lab2.py
SuperLikeLT's picture
Upload folder using huggingface_hub
9d0cb7b verified
Raw History Blame Contribute Delete
5.25 kB
"""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]