fix: resolve API key at call time so config changes take effect without restart

Previously, WebSearchTool cached the API key in __init__, so keys added
to config.json or env vars after gateway startup were never picked up.
This caused a confusing 'BRAVE_API_KEY not configured' error even after
the key was correctly set (issue #1069).

Changes:
- Store the init-time key separately, resolve via property at each call
- Improve error message to guide users toward the correct fix

Closes #1069
This commit is contained in:
haosenwang1018
2026-02-24 04:06:22 +08:00
parent 30361c9307
commit eeaad6e0c2

View File

@@ -58,12 +58,22 @@ class WebSearchTool(Tool):
} }
def __init__(self, api_key: str | None = None, max_results: int = 5): 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._init_api_key = api_key
self.max_results = max_results self.max_results = max_results
@property
def api_key(self) -> str:
"""Resolve API key at call time so env/config changes are picked up."""
return self._init_api_key or os.environ.get("BRAVE_API_KEY", "")
async def execute(self, query: str, count: int | None = None, **kwargs: Any) -> str: async def execute(self, query: str, count: int | None = None, **kwargs: Any) -> str:
if not self.api_key: if not self.api_key:
return "Error: BRAVE_API_KEY not configured" return (
"Error: Brave Search API key not configured. "
"Set BRAVE_API_KEY environment variable or add "
"tools.web.search.apiKey to ~/.nanobot/config.json, "
"then restart the gateway."
)
try: try:
n = min(max(count or self.max_results, 1), 10) n = min(max(count or self.max_results, 1), 10)