"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(tools): make web_search resilient via multi-engine fallback (#232)
Haozhe Wu04480e8a03b3
diff --git a/agent/src/tools/web_search_tool.py b/agent/src/tools/web_search_tool.pyindex 454a8b911..29de2cca1 100644--- a/agent/src/tools/web_search_tool.py+++ b/agent/src/tools/web_search_tool.py@@ -1,16 +1,37 @@-"""Web search tool: search the web via DuckDuckGo (free, no API key)."""+"""Web search tool: free multi-engine search via ddgs (no API key).++`ddgs` (the successor to `duckduckgo_search`) is a metasearch aggregator: it can+query DuckDuckGo, Google, Bing, Brave, Mojeek, Yahoo and more behind one API,+none of which need an API key. DuckDuckGo alone rate-limits aggressively from+cloud / shared IPs (issue #231: ``web_search`` showed ❌ while the run still+succeeded via ``read_url``), so we pass an explicit ordered backend list and let+ddgs fall through a throttled engine to the next one, with a short retry/backoff+on top for transient failures.+"""from __future__ import annotationsimport json+import logging+import os+import timefrom typing import Anyfrom src.agent.tools import BaseToolfrom src.security.scanner import with_security_warnings+logger = logging.getLogger(__name__)++# Free, no-key engines aggregated by ddgs, tried in order. A single engine+# returning nothing or being rate-limited no longer fails the whole search.+# Override (or pin to one engine) via VIBE_TRADING_SEARCH_BACKENDS.+_DEFAULT_BACKENDS = "duckduckgo, google, bing, brave, mojeek, yahoo"+_MAX_ATTEMPTS = 3+_BACKOFF_BASE_SECONDS = 0.8+class WebSearchTool(BaseTool):- """Search the web via DuckDuckGo and return top results."""+ """Search the web via ddgs across several free engines and return top results."""name = "web_search"@@ -26,9 +47,9 @@ class WebSearchTool(BaseTool):except ImportError:return Falsedescription = (- "Search the web via DuckDuckGo. Returns top results with title, URL, "- "and snippet. Use this to find information, news, or URLs before "- "reading them with read_url."+ "Search the web across free engines (DuckDuckGo, Google, Bing, Brave, "+ "Mojeek, Yahoo). Returns top results with title, URL, and snippet. Use "+ "this to find information, news, or URLs before reading them with read_url.")parameters = {"type": "object",@@ -48,25 +69,67 @@ class WebSearchTool(BaseTool):repeatable = Truedef execute(self, **kwargs: Any) -> str:- """Run a DuckDuckGo search.+ """Run a web search across free engines with retry and backend fallback.Args:**kwargs: Must include query; optionally max_results.Returns:- JSON with search results or error.+ JSON envelope with status, query, the backend list used, and results+ (or an actionable error message on persistent failure)."""query = kwargs["query"]max_results = min(int(kwargs.get("max_results", 5)), 10)+ backends = os.getenv("VIBE_TRADING_SEARCH_BACKENDS", _DEFAULT_BACKENDS).strip() or "auto"try:+ from ddgs import DDGS++ supports_backend = True+ except ImportError:try:- from ddgs import DDGS+ from duckduckgo_search import DDGS # legacy package, no engine selectionexcept ImportError:- from duckduckgo_search import DDGS+ return json.dumps(+ {+ "status": "error",+ "error": "Web search package not installed. Run: pip install ddgs",+ },+ ensure_ascii=False,+ )+ supports_backend = False- with DDGS() as ddgs:- raw = list(ddgs.text(query, max_results=max_results))+ last_error: Exception | None = None+ for attempt in range(1, _MAX_ATTEMPTS + 1):+ try:+ with DDGS() as client:+ if supports_backend:+ raw = list(client.text(query, max_results=max_results, backend=backends))+ else:+ raw = list(client.text(query, max_results=max_results))+ except TypeError:+ # Older ddgs/duckduckgo_search without the backend kwarg.+ supports_backend = False+ continue+ except Exception as exc: # noqa: BLE001 — surface a clean error to the agent+ last_error = exc+ # "No results found" is a definitive empty answer, not a transient+ # failure — retrying or switching engines won't change it.+ if "no results" in str(exc).lower():+ return json.dumps(+ {+ "status": "ok",+ "query": query,+ "backends": backends if supports_backend else "duckduckgo",+ "results": [],+ "note": "No results found for this query across the search engines.",+ },+ ensure_ascii=False,+ )+ logger.warning("web_search attempt %d/%d failed: %s", attempt, _MAX_ATTEMPTS, exc)+ if attempt < _MAX_ATTEMPTS:+ time.sleep(_BACKOFF_BASE_SECONDS * attempt)+ continueresults = [{@@ -76,22 +139,28 @@ class WebSearchTool(BaseTool):}for r in raw]- payload = {"status": "ok", "query": query, "results": results}+ payload = {+ "status": "ok",+ "query": query,+ "backends": backends if supports_backend else "duckduckgo",+ "results": results,+ }payload = with_security_warnings(payload,fields=("results.*.title", "results.*.snippet"),)return json.dumps(payload, ensure_ascii=False)- except ImportError:- return json.dumps(- {- "status": "error",- "error": "DuckDuckGo search package not installed. Run: pip install ddgs",- },- ensure_ascii=False,- )- except Exception as exc:- return json.dumps(- {"status": "error", "error": str(exc)},- ensure_ascii=False,- )++ return json.dumps(+ {+ "status": "error",+ "error": (+ f"Web search failed after {_MAX_ATTEMPTS} attempts "+ f"(backends: {backends if supports_backend else 'duckduckgo'}): {last_error}. "+ "Free search engines rate-limit aggressively from cloud/shared IPs — "+ "retry shortly, set VIBE_TRADING_SEARCH_BACKENDS to a different engine "+ "list (e.g. 'google, bing'), or read a known URL directly with read_url."+ ),+ },+ ensure_ascii=False,+ )diff --git a/agent/tests/test_web_search_tool.py b/agent/tests/test_web_search_tool.pynew file mode 100644index 000000000..458b4fc76--- /dev/null+++ b/agent/tests/test_web_search_tool.py@@ -0,0 +1,141 @@+"""Tests for WebSearchTool: multi-backend fallback, retry, and error handling.++Covers issue #231 — a single rate-limited engine (DuckDuckGo) should no longer+fail the whole search. All tests mock ``ddgs.DDGS`` so no network calls are made.+"""+import json+import sys+from contextlib import contextmanager+from types import ModuleType+from unittest.mock import MagicMock++import pytest++from src.tools.web_search_tool import WebSearchTool+++def _make_ddgs_module(text_impl):+ """Build a fake ``ddgs`` module whose DDGS().text delegates to text_impl."""+ module = ModuleType("ddgs")++ class FakeDDGS:+ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def text(self, query, max_results=5, **kwargs):+ return text_impl(query, max_results=max_results, **kwargs)++ module.DDGS = FakeDDGS+ return module+++@contextmanager+def _patch_ddgs(monkeypatch, text_impl):+ monkeypatch.setitem(sys.modules, "ddgs", _make_ddgs_module(text_impl))+ yield++[email protected](autouse=True)+def _clear_backend_env(monkeypatch):+ monkeypatch.delenv("VIBE_TRADING_SEARCH_BACKENDS", raising=False)+++def test_returns_results_and_passes_backend_list(monkeypatch):+ """Happy path: results mapped to title/url/snippet and the backend list is forwarded."""+ seen = {}++ def text_impl(query, max_results, **kwargs):+ seen.update(kwargs)+ return [{"title": "T1", "href": "http://a", "body": "snippet1"}]++ with _patch_ddgs(monkeypatch, text_impl):+ out = json.loads(WebSearchTool().execute(query="nvidia"))++ assert out["status"] == "ok"+ assert out["results"][0] == {"title": "T1", "url": "http://a", "snippet": "snippet1"}+ # The default multi-engine list is forwarded so a throttled engine falls through.+ assert seen.get("backend") == "duckduckgo, google, bing, brave, mojeek, yahoo"+++def test_env_overrides_backends(monkeypatch):+ """VIBE_TRADING_SEARCH_BACKENDS overrides the default engine list."""+ monkeypatch.setenv("VIBE_TRADING_SEARCH_BACKENDS", "google, bing")+ seen = {}++ def text_impl(query, max_results, **kwargs):+ seen.update(kwargs)+ return [{"title": "T", "href": "http://x", "body": "b"}]++ with _patch_ddgs(monkeypatch, text_impl):+ out = json.loads(WebSearchTool().execute(query="aapl"))++ assert out["status"] == "ok"+ assert seen.get("backend") == "google, bing"+++def test_retries_transient_failure_then_succeeds(monkeypatch):+ """A transient exception is retried (with backoff) and a later attempt wins."""+ monkeypatch.setattr("src.tools.web_search_tool.time.sleep", lambda *_: None)+ calls = {"n": 0}++ def text_impl(query, max_results, **kwargs):+ calls["n"] += 1+ if calls["n"] == 1:+ raise RuntimeError("Ratelimit 202")+ return [{"title": "ok", "href": "http://ok", "body": "b"}]++ with _patch_ddgs(monkeypatch, text_impl):+ out = json.loads(WebSearchTool().execute(query="msft"))++ assert out["status"] == "ok"+ assert calls["n"] == 2+++def test_no_results_is_ok_empty_not_error(monkeypatch):+ """ddgs raising 'No results found.' yields an ok+empty envelope, not ❌."""+ monkeypatch.setattr("src.tools.web_search_tool.time.sleep", lambda *_: None)++ def text_impl(query, max_results, **kwargs):+ raise RuntimeError("No results found.")++ with _patch_ddgs(monkeypatch, text_impl):+ out = json.loads(WebSearchTool().execute(query="zzzz-no-such-thing"))++ assert out["status"] == "ok"+ assert out["results"] == []+ assert "note" in out+++def test_persistent_failure_returns_actionable_error(monkeypatch):+ """When every attempt fails, the error names the retry/env/read_url remedies."""+ monkeypatch.setattr("src.tools.web_search_tool.time.sleep", lambda *_: None)+ calls = {"n": 0}++ def text_impl(query, max_results, **kwargs):+ calls["n"] += 1+ raise RuntimeError("Ratelimit 429")++ with _patch_ddgs(monkeypatch, text_impl):+ out = json.loads(WebSearchTool().execute(query="tsla"))++ assert out["status"] == "error"+ assert calls["n"] == 3 # exhausted all attempts+ assert "VIBE_TRADING_SEARCH_BACKENDS" in out["error"]+ assert "read_url" in out["error"]+++def test_max_results_capped_at_10(monkeypatch):+ """max_results is clamped to 10."""+ seen = {}++ def text_impl(query, max_results, **kwargs):+ seen["max_results"] = max_results+ return []++ with _patch_ddgs(monkeypatch, text_impl):+ WebSearchTool().execute(query="q", max_results=50)++ assert seen["max_results"] == 10