Source code for aidputils.agents.tools.experimental.websearch.brave

from __future__ import annotations

from typing import Any

from aidputils.agents.toolkit.tool_common import as_str as _as_str
from aidputils.agents.tools.experimental.websearch.base import BaseWebSearchHandler
from aidputils.agents.tools.experimental.websearch.web_search_models import NormalizedWebResult


[docs] class BraveWebSearchHandler(BaseWebSearchHandler): """ Brave Search parser (engine-native JSON). Supported shapes (best-effort; proxy may return variants): - {"web": {"results": [ {"title","url","description"|"snippet", ...}, ... ]}} - {"results": [...]} (proxy-normalized / passthrough) """ def __init__(self): super().__init__("BRAVE")
[docs] def get_endpoint(self, conf: dict) -> str: # Brave direct-provider endpoint return "https://api.search.brave.com/res/v1/web/search"
[docs] def parse(self, data: Any) -> list[NormalizedWebResult]: if not isinstance(data, dict): return [] # Brave typically nests under `web.results` web = data.get("web") if isinstance(web, dict) and isinstance(web.get("results"), list): results = web["results"] else: # Some proxies return `results` already results = data.get("results") if not isinstance(results, list): return self._fallback(data) out: list[NormalizedWebResult] = [] for r in results: if not isinstance(r, dict): continue out.append( NormalizedWebResult( title=_as_str(r.get("title")), url=_as_str(r.get("url")), snippet=_as_str(r.get("description") or r.get("snippet")), source=_as_str(r.get("source") or self.engine), published_time=_as_str( r.get("published_time") or r.get("publishedTime") ), ) ) return out