"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(search): try enabled fallbacks after empty ddgs results
Haozhe Wu0d946491c769
diff --git a/README.md b/README.mdindex 187ff25b1..c5102aaf2 100644--- a/README.md+++ b/README.md@@ -1850,6 +1850,12 @@ with `--host` / `--port`.**MCP tools exposed (82):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `alpha_zoo`, `alpha_bench`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `read_run_artifact`, `list_strategies`, `query_strategies`, `get_strategy_evidence`, `refresh_strategy_evidence`, `adapt_strategy`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_southbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `quantlib_call`, `cashflow_performance`, `orderbook_depth`, `sentiment`, `technical_indicators`, `get_fundamentals`, `get_fund_nav`, `get_cn_macro_series`, `get_cn_announcements`, `search_broker_reports`, `paper_trade_step`.+`web_search` tries its existing Sogou and Bing China fallbacks when ddgs returns+no results or fails. Set `VIBE_TRADING_SEARCH_BING_FALLBACK=0` to disable both.+This chain returns an empty result only when its enabled sources finish without+an unresolved error; an unavailable source produces an actionable error if no+other source returns results.+`quantlib_call` attribution requires finite sector weights and returns, finite Carino return inputs, and a finite non-negative weight-sum tolerance. Invalid data is rejected explicitly rather than returned as an attribution result containing `NaN`. Missing returns for a zero-weight sector may still be inferred from the other side.`quantlib_call` maximum-drawdown analysis measures underwater duration from the latest visit to the peak before the worst trough. An earlier drawdown that already recovered is excluded from that duration.diff --git a/agent/src/tools/web_search_tool.py b/agent/src/tools/web_search_tool.pyindex 0726c01c4..2d2fa9078 100644--- a/agent/src/tools/web_search_tool.py+++ b/agent/src/tools/web_search_tool.py@@ -254,25 +254,18 @@ class WebSearchTool(BaseTool):raw = list(client.text(query, max_results=max_results, backend=backends))else:raw = list(client.text(query, max_results=max_results))- except TypeError:+ except TypeError as exc:# Older ddgs/duckduckgo_search without the backend kwarg.+ last_error = excsupports_backend = Falsecontinueexcept 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.+ # An empty aggregator answer says nothing about the fallback+ # sources. Treat its exception and an empty list identically.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,- )+ last_error = None+ break+ last_error = exclogger.warning("web_search attempt %d/%d failed: %s", attempt, _MAX_ATTEMPTS, exc)# Network/egress errors (timeout, connection refused, unreachable)# won't recover on retry — stop retrying ddgs and fall through to@@ -284,6 +277,9 @@ class WebSearchTool(BaseTool):time.sleep(_BACKOFF_BASE_SECONDS * attempt)continue+ if not raw:+ last_error = None+ breakresults = [{"title": r.get("title", ""),@@ -304,11 +300,12 @@ class WebSearchTool(BaseTool):)return json.dumps(payload, ensure_ascii=False)- # Fallback chain when every ddgs backend is blocked (common behind+ # Fallback chain when ddgs is empty or blocked (common behind# restricted egress, e.g. CN hosts without VPN): sogou first (best CN# query quality), then cn.bing (real URLs, broader). Toggle via# VIBE_TRADING_SEARCH_BING_FALLBACK (default on).fb_err = "disabled"+ fb_errors: list[str] = []if get_env_config().agent_tuning.vibe_trading_search_bing_fallback:for fb_name, fb_fn in (("sogou", _sogou_search), ("bing_cn", _bing_cn_search)):try:@@ -331,14 +328,26 @@ class WebSearchTool(BaseTool):except Exception as exc: # noqa: BLE001logger.warning("%s fallback failed: %s", fb_name, exc)fb_err = f"{fb_name}: {exc}"+ fb_errors.append(fb_err)continue+ if last_error is None and not fb_errors:+ return json.dumps(+ {+ "status": "ok",+ "query": query,+ "backends": backends if supports_backend else "duckduckgo",+ "results": [],+ "note": "No results found after trying the enabled search sources.",+ },+ 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}. "- f"CN fallbacks (sogou, bing_cn): {fb_err}. "+ f"Web search failed after {attempt} ddgs attempts "+ f"(backends: {backends if supports_backend else 'duckduckgo'}): {last_error or 'no results'}. "+ f"CN fallbacks (sogou, bing_cn): {'; '.join(fb_errors) or fb_err}. ""Retry shortly, set VIBE_TRADING_SEARCH_BACKENDS to a different engine list, ""set VIBE_TRADING_SEARCH_BING_FALLBACK=0 to disable CN fallback, or read a ""known URL directly with read_url."diff --git a/agent/tests/test_security_scanner.py b/agent/tests/test_security_scanner.pyindex 8949841db..7a93ccfc5 100644--- a/agent/tests/test_security_scanner.py+++ b/agent/tests/test_security_scanner.py@@ -171,6 +171,7 @@ def test_web_search_retries_without_backend_when_ddgs_rejects_backend_kw(def test_web_search_treats_no_results_as_empty_success(monkeypatch: pytest.MonkeyPatch,) -> None:+ monkeypatch.setenv("VIBE_TRADING_SEARCH_BING_FALLBACK", "0")class FakeDDGS:def __enter__(self):return selfdiff --git a/agent/tests/test_web_search_tool.py b/agent/tests/test_web_search_tool.pyindex a1f7fccdf..b2536ec55 100644--- a/agent/tests/test_web_search_tool.py+++ b/agent/tests/test_web_search_tool.py@@ -43,6 +43,8 @@ def _clear_backend_env(monkeypatch):monkeypatch.delenv("VIBE_TRADING_SEARCH_BACKENDS", raising=False)monkeypatch.delenv("VIBE_TRADING_SEARCH_BING_FALLBACK", raising=False)monkeypatch.delenv("ALIYUN_IQS_API_KEY", raising=False)+ monkeypatch.setattr("src.tools.web_search_tool._sogou_search", MagicMock(return_value=[]))+ monkeypatch.setattr("src.tools.web_search_tool._bing_cn_search", MagicMock(return_value=[]))def test_returns_results_and_passes_backend_list(monkeypatch):@@ -97,7 +99,7 @@ def test_retries_transient_failure_then_succeeds(monkeypatch):def test_no_results_is_ok_empty_not_error(monkeypatch):- """ddgs raising 'No results found.' yields an ok+empty envelope, not ❌."""+ """Empty answers from all enabled sources remain an ok+empty envelope."""monkeypatch.setattr("src.tools.web_search_tool.time.sleep", lambda *_: None)def text_impl(query, max_results, **kwargs):@@ -111,6 +113,78 @@ def test_no_results_is_ok_empty_not_error(monkeypatch):assert "note" in out[email protected]("raises_empty", [False, True])+def test_empty_ddgs_tries_existing_fallbacks(monkeypatch, raises_empty):+ """An empty ddgs answer does not establish that other sources are empty."""+ calls = []++ def text_impl(query, max_results, **kwargs):+ calls.append("ddgs")+ if raises_empty:+ raise RuntimeError("No results found.")+ return []++ def sogou(query, max_results):+ calls.append("sogou")+ return []++ def bing(query, max_results):+ calls.append("bing_cn")+ return [{"title": "Earnings", "href": "https://example.test/earnings", "body": "Report"}]++ monkeypatch.setattr("src.tools.web_search_tool._sogou_search", sogou)+ monkeypatch.setattr("src.tools.web_search_tool._bing_cn_search", bing)+ with _patch_ddgs(monkeypatch, text_impl):+ out = json.loads(WebSearchTool().execute(query="quarterly earnings"))++ assert calls == ["ddgs", "sogou", "bing_cn"]+ assert out["status"] == "ok"+ assert out["backends"] == "bing_cn_fallback"+ assert out["results"][0]["url"] == "https://example.test/earnings"+++def test_empty_ddgs_respects_disabled_fallbacks(monkeypatch):+ monkeypatch.setenv("VIBE_TRADING_SEARCH_BING_FALLBACK", "0")+ forbidden = MagicMock(side_effect=AssertionError("fallback disabled"))+ monkeypatch.setattr("src.tools.web_search_tool._sogou_search", forbidden)+ monkeypatch.setattr("src.tools.web_search_tool._bing_cn_search", forbidden)+ with _patch_ddgs(monkeypatch, lambda *a, **kw: []):+ out = json.loads(WebSearchTool().execute(query="unmatched query"))+ assert out["status"] == "ok"+ assert out["results"] == []+ forbidden.assert_not_called()+++def test_empty_ddgs_does_not_hide_a_fallback_outage(monkeypatch):+ unavailable = MagicMock(side_effect=RuntimeError("Connection timed out"))+ monkeypatch.setattr("src.tools.web_search_tool._sogou_search", unavailable)+ with _patch_ddgs(monkeypatch, lambda *a, **kw: []):+ out = json.loads(WebSearchTool().execute(query="quarterly earnings"))+ unavailable.assert_called_once()+ assert out["status"] == "error"+ assert "Connection timed out" in out["error"]+++def test_nonempty_ddgs_does_not_invoke_fallbacks(monkeypatch):+ forbidden = MagicMock(side_effect=AssertionError("already have results"))+ monkeypatch.setattr("src.tools.web_search_tool._sogou_search", forbidden)+ monkeypatch.setattr("src.tools.web_search_tool._bing_cn_search", forbidden)+ with _patch_ddgs(monkeypatch, lambda *a, **kw: [{"title": "result", "href": "https://example.test"}]):+ out = json.loads(WebSearchTool().execute(query="quarterly earnings"))+ assert out["status"] == "ok"+ forbidden.assert_not_called()+++def test_backend_compatibility_failure_is_not_empty_success(monkeypatch):+ def text_impl(query, max_results, **kwargs):+ raise TypeError("unsupported client signature")++ with _patch_ddgs(monkeypatch, text_impl):+ out = json.loads(WebSearchTool().execute(query="quarterly earnings"))+ assert out["status"] == "error"+ assert "unsupported client signature" in out["error"]++def test_persistent_failure_returns_actionable_error(monkeypatch):"""When every attempt fails, the error names the retry/env/read_url remedies."""monkeypatch.setenv("VIBE_TRADING_SEARCH_BING_FALLBACK", "0")