File size: 1,350 Bytes
2628a0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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}"