Spaces:
Running

sitcod3's picture
sync: backend/src -> Space (browser settings autosave + writable settings file)
6eb6c4e verified
Raw History Blame Contribute Delete
5.73 kB
"""Exa neural web search client (server-side only — the key never leaves the backend).
Follows the build-with-exa skill: the recommended request is the query plus
token-efficient content extraction and nothing else — `query`, `type: "auto"`,
and `contents: { "highlights": true }`. Every other request field is added only
when the caller explicitly requires it (no boilerplate `numResults`, no
deprecated `livecrawl`, no `category` unless explicitly requested).
Results carry plain http(s) URLs which the webnav service re-runs through
net_guard before the agent visits them, so a malicious/typoed result can never
aim the browser at internal space.
"""
from __future__ import annotations
from typing import Any
import aiohttp
from .config import settings
class ExaNotConfiguredError(RuntimeError):
"""EXA_API_KEY is missing — search runs in a disabled, explicit state."""
class ExaSearchError(RuntimeError):
"""The Exa API call failed (network, status, or payload shape)."""
class ExaClient:
"""Thin async client for the Exa /search endpoint."""
def __init__(
self,
api_key: str | None = None,
base_url: str | None = None,
timeout_seconds: float = 15.0,
):
self._api_key = api_key if api_key is not None else settings.exa_api_key
self._base_url_override = base_url
self._timeout = aiohttp.ClientTimeout(total=timeout_seconds)
@property
def base_url(self) -> str:
"""Resolve the effective Exa base URL, honoring live settings updates."""
configured = (
self._base_url_override
if self._base_url_override is not None
else settings.exa_base_url
)
return (configured or "https://api.exa.ai").rstrip("/")
@property
def configured(self) -> bool:
return bool(self._api_key)
async def search(
self,
query: str,
num_results: int | None = None,
category: str | None = None,
) -> list[dict[str, Any]]:
"""Run a neural search; returns [{title, url, snippet, published_date}]."""
if not query or not query.strip():
raise ExaSearchError("Search query is required")
if not self.configured:
raise ExaNotConfiguredError(
"EXA_API_KEY is not set — add it to backend/.env to enable web search"
)
# Recommended request per build-with-exa skill: query + type:auto +
# contents.highlights:true, nothing else unless explicitly required.
body: dict[str, Any] = {
"query": query.strip(),
"type": "auto",
"contents": {"highlights": True},
}
# numResults is a product decision, not boilerplate — omit unless set.
result_limit = 10
if num_results is not None:
result_limit = max(1, min(int(num_results), 100))
body["numResults"] = result_limit
# category only when the caller explicitly requests constrained retrieval.
if category:
body["category"] = category
url = f"{self.base_url}/search"
assert self._api_key is not None # guarded by configured above
headers = {"x-api-key": self._api_key, "Content-Type": "application/json"}
try:
async with (
aiohttp.ClientSession(timeout=self._timeout) as session,
session.post(url, json=body, headers=headers) as resp,
):
if resp.status == 401 or resp.status == 403:
raise ExaSearchError(f"Exa rejected the API key (HTTP {resp.status})")
if resp.status != 200:
# Provider bodies may echo request credentials; keep errors
# safe for logs and client-facing fallback messages.
raise ExaSearchError(f"Exa search failed (HTTP {resp.status})")
payload = await resp.json(content_type=None)
except (aiohttp.ClientError, TimeoutError) as exc:
raise ExaSearchError("Could not reach Exa") from exc
results = payload.get("results") if isinstance(payload, dict) else None
if not isinstance(results, list):
raise ExaSearchError("Exa returned an unexpected payload")
normalized: list[dict[str, Any]] = []
for row in results:
if not isinstance(row, dict) or not row.get("url"):
continue
# On /search, content lives nested inside `contents`; highlights is
# the recommended extraction mode. Fall back to top-level text for
# resilience against older/shaped responses.
contents = row.get("contents") or {}
highlights = contents.get("highlights") if isinstance(contents, dict) else None
snippet = ""
if isinstance(highlights, list):
snippet = " ".join(h for h in highlights if isinstance(h, str))
elif isinstance(highlights, str):
snippet = highlights
if not snippet:
snippet = row.get("text") or ""
normalized.append({
"title": str(row.get("title") or row["url"])[:200],
"url": row["url"],
"snippet": snippet[:300],
"published_date": row.get("publishedDate"),
})
if len(normalized) >= result_limit:
break
return normalized
# Module-level singleton (same DI style as browser_manager / llm_provider).
exa_client = ExaClient()