Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
perf(tools): search_web fetches query variants concurrently in one call
Ruben Lütke1cbcc667b929
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex 261b3f286a..e5b6496bd0 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -407,6 +407,10 @@ _DELEGATE_VOICE_DIRECTIVE = ("calls in ONE round instead of one per round; never re-issue a tool call ""(or a rephrasing of it) whose result you already have; as soon as the ""gathered evidence answers the question, stop calling tools and answer. "+ "For web research: put your 2-3 query variants into ONE search_web call "+ "(its 'queries' parameter) and ANSWER from that first round of results — "+ "a good spoken answer NOW beats a perfect one after more digging; search "+ "again only if the first results are genuinely unusable. ""Keep the final answer concise and speakable.")diff --git a/jarvis/plugins/tool/search_web.py b/jarvis/plugins/tool/search_web.pyindex 04d58a95c5..1c0b0952b5 100644--- a/jarvis/plugins/tool/search_web.py+++ b/jarvis/plugins/tool/search_web.py@@ -39,6 +39,14 @@ _WEATHER_CALL_TIMEOUT_S: Final[float] = _TIMEOUT_S / 2_GEOCODE_URL: Final[str] = "https://geocoding-api.open-meteo.com/v1/search"_FORECAST_URL: Final[str] = "https://api.open-meteo.com/v1/forecast"+# Concurrent query variants per call (BUG-072 follow-up). Three phrasings+# cover a research question; more only dilutes the merged snippet budget.+_MAX_QUERY_VARIANTS: Final[int] = 3+# Ceiling for the merged result list across all variants — keeps the tool+# result within the loop's payload cap while still carrying more evidence+# than a single-query call.+_MAX_MERGED_RESULTS: Final[int] = 8+# How the brain must consume a non-empty result set. Live forensic 2026-06-28# (voice session, Turn 4 "wie viele Punkte brauche ich fuer eine 1"): the brain # i18n-allow# (Gemini) concatenated the raw DuckDuckGo hits — titles, snippets, dates, URLs,@@ -134,6 +142,45 @@ def _condition_text(code: object) -> str:return "unknown conditions"+def _merge_outcomes(outcomes: list[Any]) -> Any:+ """Merge per-variant search outcomes into one, deduplicated by URL.++ Results interleave across variants (first hit of each variant first) so+ one variant cannot crowd out the others' evidence. Status is honest:+ ``ok`` when anything was found, ``empty`` when at least one backend+ reached its index, ``unavailable`` only when none did.+ """+ from jarvis.plugins.tool.search_backends import SearchOutcome++ if len(outcomes) == 1:+ return outcomes[0]+ merged: list[dict[str, Any]] = []+ seen_urls: set[str] = set()+ for rank in range(max(len(o.results) for o in outcomes) if outcomes else 0):+ for outcome in outcomes:+ if rank >= len(outcome.results):+ continue+ result = outcome.results[rank]+ url = str(result.get("url", "")).strip().lower()+ if url and url in seen_urls:+ continue+ if url:+ seen_urls.add(url)+ merged.append(result)+ merged = merged[:_MAX_MERGED_RESULTS]+ if any(o.status == "ok" and o.results for o in outcomes):+ status = "ok" if merged else "empty"+ elif any(o.status == "empty" for o in outcomes):+ status = "empty"+ else:+ status = "unavailable"+ backend = next(+ (o.backend for o in outcomes if o.status == "ok" and o.results),+ outcomes[0].backend if outcomes else "none",+ )+ return SearchOutcome(results=merged, backend=backend, status=status)++async def _weather_results(query: str, client: Any) -> list[dict[str, Any]] | None:"""Open-Meteo lookup: geocode the location in *query*, fetch a 3-dayforecast, return it as one search-result snippet. ``None`` = not@@ -227,6 +274,9 @@ class SearchWebTool:"from your own knowledge, without searching. ""For weather questions, put the location in the query (e.g. 'weather ""Berlin tomorrow'). "+ "For research questions, pass 2-3 DIFFERENT phrasings via 'queries' "+ "in ONE call (fetched concurrently) instead of searching again in a "+ "later round — one call should gather all the evidence you need. ""DO NOT USE for actions on connected systems (use cli_* or MCP tools ""for that) — 'my X' or 'start X' is NEVER search intent.")@@ -234,6 +284,16 @@ class SearchWebTool:"type": "object","properties": {"query": {"type": "string", "description": "Search query"},+ "queries": {+ "type": "array",+ "items": {"type": "string"},+ "description": (+ "Up to 3 query variants fetched CONCURRENTLY in this one "+ "call (different phrasings/languages of the same research "+ "question). Preferred over issuing a second search in a "+ "later round."+ ),+ },"max_results": {"type": "integer", "default": 5},},"required": ["query"],@@ -242,8 +302,22 @@ class SearchWebTool:async def execute(self, args: dict[str, Any], ctx: ExecutionContext) -> ToolResult:query = (args.get("query") or "").strip()max_results = int(args.get("max_results", 5))- if not query:+ # Query variants (2026-07-17, BUG-072 follow-up): a research question+ # used to cost TWO sequential model rounds because the first search's+ # evidence was thin and the model refined its query in the next round+ # — a full provider round-trip per refinement. Variants passed in ONE+ # call run concurrently under the same voice deadline, so the model+ # gathers all evidence in a single round.+ raw_variants = args.get("queries")+ variants: list[str] = []+ for candidate in ([query] + list(raw_variants or []))[: _MAX_QUERY_VARIANTS + 1]:+ text = str(candidate or "").strip()+ if text and text.lower() not in {v.lower() for v in variants}:+ variants.append(text)+ variants = variants[:_MAX_QUERY_VARIANTS]+ if not variants:return ToolResult(success=False, output=None, error="query missing")+ query = variants[0]try:import httpx@@ -274,12 +348,16 @@ class SearchWebTool:)# General web search: real DuckDuckGo web search, with the DDG- # Instant-Answer box as a cheap encyclopedic fallback. Bounded by the- # same single voice-path deadline as the weather path.+ # Instant-Answer box as a cheap encyclopedic fallback. All query+ # variants run CONCURRENTLY and share the single voice-path deadline,+ # so three variants cost the same wall time as one.try:async with asyncio.timeout(_TIMEOUT_S):async with httpx.AsyncClient(timeout=_TIMEOUT_S) as client:- outcome = await run_search(query, max_results, client=client)+ outcomes = await asyncio.gather(*[+ run_search(variant, max_results, client=client)+ for variant in variants+ ])except Exception: # noqa: BLE001 — incl. TimeoutError: never sink the turnreturn ToolResult(success=True,@@ -294,12 +372,15 @@ class SearchWebTool:},)+ outcome = _merge_outcomes(outcomes)output: dict[str, Any] = {"query": query,"results": outcome.results,"backend": outcome.backend,"status": outcome.status,}+ if len(variants) > 1:+ output["queries"] = variantsif outcome.status == "unavailable":output["detail"] = ("Web search is temporarily unavailable. Tell the user the search "diff --git a/tests/unit/plugins/tool/test_search_web_query_variants.py b/tests/unit/plugins/tool/test_search_web_query_variants.pynew file mode 100644index 0000000000..c0f018556f--- /dev/null+++ b/tests/unit/plugins/tool/test_search_web_query_variants.py@@ -0,0 +1,152 @@+"""Concurrent query variants in one search_web call (BUG-072 follow-up).++A research question used to cost TWO sequential model rounds: the first+search's evidence was thin, so the model refined its query in the NEXT+round — a full provider round-trip per refinement (live: the Bugatti-Divo+question ran two searches ≈ 12.5 s). Variants passed via ``queries`` run+concurrently inside one tool call, so all evidence arrives in one round.++Contract under test:+ 1. ``queries`` variants all reach the backend; results merge interleaved+ and deduplicate by URL; ``ok`` when anything was found.+ 2. The variant list is bounded (3) and deduplicated case-insensitively;+ the primary ``query`` is always variant one.+ 3. A single-query call behaves exactly as before (no wrapper changes).+ 4. Status honesty: all-empty merges to ``empty``, all-unavailable to+ ``unavailable``.+"""+from __future__ import annotations++from uuid import uuid4++import pytest++from jarvis.core.protocols import ExecutionContext+from jarvis.plugins.tool import search_web+from jarvis.plugins.tool.search_backends import SearchOutcome++_CTX = ExecutionContext(+ trace_id=uuid4(),+ user_utterance="test",+ config={},+ memory_read=None,+ approved_by="auto",+)+++def _hit(url: str, title: str = "t") -> dict[str, str]:+ return {"title": title, "snippet": "s", "url": url}+++async def test_variants_run_and_merge_deduplicated(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seen: list[str] = []++ async def fake_run_search(query, max_results, *, client, searcher=None):+ seen.append(query)+ by_query = {+ "bugatti divo for sale europe": [_hit("https://a.example"), _hit("https://b.example")],+ "bugatti divo kaufen": [_hit("https://a.example"), _hit("https://c.example")],+ }+ return SearchOutcome(+ results=by_query.get(query, []), backend="ddg_serp", status="ok"+ )++ monkeypatch.setattr(search_web, "run_search", fake_run_search)+ tool = search_web.SearchWebTool()++ result = await tool.execute(+ {+ "query": "bugatti divo for sale europe",+ "queries": ["bugatti divo kaufen"],+ },+ _CTX,+ )++ assert result.success+ assert sorted(seen) == ["bugatti divo for sale europe", "bugatti divo kaufen"]+ urls = [r["url"] for r in result.output["results"]]+ # Rank-interleaved merge: rank 0 of each variant first (variant 2's rank-0+ # hit deduplicates against variant 1's), then rank 1 of each variant.+ assert urls == ["https://a.example", "https://b.example", "https://c.example"]+ assert result.output["status"] == "ok"+ assert result.output["queries"] == [+ "bugatti divo for sale europe",+ "bugatti divo kaufen",+ ]+++async def test_variant_list_is_bounded_and_deduplicated(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ seen: list[str] = []++ async def fake_run_search(query, max_results, *, client, searcher=None):+ seen.append(query)+ return SearchOutcome(results=[_hit(f"https://{len(seen)}.example")],+ backend="ddg_serp", status="ok")++ monkeypatch.setattr(search_web, "run_search", fake_run_search)+ tool = search_web.SearchWebTool()++ result = await tool.execute(+ {+ "query": "primary",+ "queries": ["PRIMARY", "second", "third", "fourth", "fifth"],+ },+ _CTX,+ )++ assert result.success+ # Case-insensitive dedupe of the primary + hard cap of 3 variants.+ assert seen == ["primary", "second", "third"]+++async def test_single_query_output_shape_is_unchanged(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ async def fake_run_search(query, max_results, *, client, searcher=None):+ return SearchOutcome(results=[_hit("https://only.example")],+ backend="ddg_serp", status="ok")++ monkeypatch.setattr(search_web, "run_search", fake_run_search)+ tool = search_web.SearchWebTool()++ result = await tool.execute({"query": "single"}, _CTX)++ assert result.success+ assert result.output["query"] == "single"+ assert "queries" not in result.output+ assert [r["url"] for r in result.output["results"]] == ["https://only.example"]+++ ("statuses", "expected"),+ [(("empty", "empty"), "empty"), (("unavailable", "unavailable"), "unavailable")],+)+async def test_merged_status_stays_honest(+ monkeypatch: pytest.MonkeyPatch,+ statuses: tuple[str, str],+ expected: str,+) -> None:+ calls: list[str] = []++ async def fake_run_search(query, max_results, *, client, searcher=None):+ calls.append(query)+ return SearchOutcome(+ results=[], backend="ddg", status=statuses[len(calls) - 1]+ )++ monkeypatch.setattr(search_web, "run_search", fake_run_search)+ tool = search_web.SearchWebTool()++ result = await tool.execute({"query": "a", "queries": ["b"]}, _CTX)++ assert result.success+ assert result.output["status"] == expected+ assert result.output["results"] == []