from evenage import tool
from typing import Dict

@tool(
    name="web_search",
    description="Search the web for information on a given topic",
    parameters={
        "query": {
            "type": "string",
            "description": "The search query"
        },
        "max_results": {
            "type": "integer",
            "description": "Maximum number of results to return",
            "default": 5
        }
    },
    trace=True
)
def web_search(query: str, max_results: int = 5) -> Dict:
    """Search the web and return results."""
    results = []
    # ... actual search logic
    return {
        "query": query,
        "results": results,
        "count": len(results)
    }
        or kwargs.get("message")
        or (args[0] if args else "")
    )
    query = str(query).strip()
    if not query:
        return "Error: Missing query parameter."

    max_results = int(kwargs.get("max_results", 5))
    api_key = os.getenv("SERPER_API_KEY")
    if not api_key:
        return "Error: SERPER_API_KEY not set. Add it to your .env file."

    try:
        import requests

        url = "https://google.serper.dev/search"
        headers = {
            "X-API-KEY": api_key,
            "Content-Type": "application/json; charset=utf-8",
        }
        payload = {"q": query}

        response = requests.post(url, headers=headers, json=payload, timeout=10)
        response.raise_for_status()
        data = response.json()

        organic = data.get("organic", [])
        if not organic:
            return f"No results found for: {query}"

        results = []
        for i, item in enumerate(organic[:max_results], 1):
            title = item.get("title", "Untitled")
            snippet = item.get("snippet", "")
            link = item.get("link", "")
            results.append(f"{i}. {title}\n   {snippet}\n   {link}")

        return "\n\n".join(results)

    except requests.exceptions.RequestException as e:
        return f"Error: HTTP failure - {e}"
    except Exception as e:
        return f"Error searching web: {str(e)}"
