Spaces:
Sleeping
Sleeping
| import os | |
| import json | |
| from tools._session import _session | |
| def web_search(query: str) -> str: | |
| """Search Google via Serper API for current information. | |
| Use this for factual questions, recent events, or anything requiring web search. | |
| """ | |
| api_key = os.getenv("SERPER_API_KEY") | |
| if not api_key: | |
| return "SERPER_API_KEY not set." | |
| try: | |
| response = _session.post( | |
| "https://google.serper.dev/search", | |
| headers={"X-API-KEY": api_key, "Content-Type": "application/json"}, | |
| data=json.dumps({"q": query, "num": 5}), | |
| timeout=15, | |
| ) | |
| response.raise_for_status() | |
| data = response.json() | |
| parts = [] | |
| # Answer box (direct answer) | |
| if "answerBox" in data: | |
| ab = data["answerBox"] | |
| answer = ab.get("answer") or ab.get("snippet") or "" | |
| if answer: | |
| parts.append(f"Direct answer: {answer}") | |
| # Organic results | |
| for r in data.get("organic", [])[:5]: | |
| title = r.get("title", "") | |
| link = r.get("link", "") | |
| snippet = r.get("snippet", "") | |
| parts.append(f"Title: {title}\nURL: {link}\nSnippet: {snippet}") | |
| return "\n---\n".join(parts) if parts else "No results found." | |
| except Exception as e: | |
| return f"Search error: {e}" | |