From ef572259747a59625865ef7d7c6fc72edb448c0c Mon Sep 17 00:00:00 2001 From: coldxiangyu Date: Tue, 24 Feb 2026 18:19:47 +0800 Subject: [PATCH] fix(web): resolve API key on each call + improve error message - Defer Brave API key resolution to execute() time instead of __init__, so env var or config changes take effect without gateway restart - Improve error message to reference actual config path (tools.web.search.apiKey) instead of only mentioning env var Fixes #1069 (issues 1 and 2 of 3) --- nanobot/agent/tools/web.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.py index 90cdda8..4ca788c 100644 --- a/nanobot/agent/tools/web.py +++ b/nanobot/agent/tools/web.py @@ -58,12 +58,21 @@ class WebSearchTool(Tool): } def __init__(self, api_key: str | None = None, max_results: int = 5): - self.api_key = api_key or os.environ.get("BRAVE_API_KEY", "") + self._config_api_key = api_key self.max_results = max_results - + + def _resolve_api_key(self) -> str: + """Resolve API key on each call to support hot-reload and env var changes.""" + return self._config_api_key or os.environ.get("BRAVE_API_KEY", "") + async def execute(self, query: str, count: int | None = None, **kwargs: Any) -> str: - if not self.api_key: - return "Error: BRAVE_API_KEY not configured" + api_key = self._resolve_api_key() + if not api_key: + return ( + "Error: Brave Search API key not configured. " + "Set it in ~/.nanobot/config.json under tools.web.search.apiKey " + "(or export BRAVE_API_KEY), then restart the gateway." + ) try: n = min(max(count or self.max_results, 1), 10) @@ -71,7 +80,7 @@ class WebSearchTool(Tool): r = await client.get( "https://api.search.brave.com/res/v1/web/search", params={"q": query, "count": n}, - headers={"Accept": "application/json", "X-Subscription-Token": self.api_key}, + headers={"Accept": "application/json", "X-Subscription-Token": api_key}, timeout=10.0 ) r.raise_for_status()