Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: continue searching past unusable results and add a Wikipedia fallback (#12892)
oobabooga0a154081743a
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 82d5d322121..10766442e64 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -16915,6 +16915,57 @@ def _empty_result_with_requested_images(return empty_text + "\n\n---\n\n" + found+def _wikipedia_search(query, max_results, timeout, deadline, cancel_event, website_policy):+ """search English Wikipedia independently of ddgs through the guarded HTTP fetcher."""+ # ddgs uses a one-result Wikipedia lookup, so full-text search recovers misses and failures.+ from html import unescape++ params = urllib.parse.urlencode(+ {+ "action": "query",+ "list": "search",+ "srsearch": query,+ "format": "json",+ "srlimit": min(max_results, 50),+ "srnamespace": 0,+ }+ )+ error, body, _ = _fetch_url_raw(+ "https://en.wikipedia.org/w/api.php?" + params,+ timeout = timeout,+ deadline = deadline,+ cancel_event = cancel_event,+ website_policy = website_policy,+ raw_bytes_max = 1024 * 1024,+ extra_headers = {"User-Agent": "UnslothStudio/1.0 (https://github.com/unslothai/unsloth)"},+ )+ if error:+ raise RuntimeError(error)+ payload = json.loads(body)+ if "error" in payload:+ raise RuntimeError("Wikipedia search API returned an error")+ return [+ {+ "title": item["title"],+ "href": "https://en.wikipedia.org/wiki/"+ + urllib.parse.quote(item["title"].replace(" ", "_"), safe = ""),+ "body": unescape(re.sub(r"<[^>]+>", "", item.get("snippet", ""))),+ }+ for item in payload["query"]["search"]+ if isinstance(item, dict) and isinstance(item.get("title"), str) and item["title"].strip()+ ]+++def _usable_search_results(results, website_policy):+ from .web_access_policy import check_url_access+ return [+ r+ for r in results+ if isinstance(r, dict)+ and check_url_access(str(r.get("href") or "").strip(), website_policy)[0]+ ]++def _web_search(query: str,max_results: int = 5,@@ -16925,11 +16976,7 @@ def _web_search(include_images: bool = False,image_queries = None,) -> str:- """Search the web through the approved engine tiers and return formatted results. If ``url`` is provided,- fetches that page directly instead of searching. ``include_images`` adds image results registered- server-side and offered to the model as ``[[img:<id>]]`` tokens, with a frontend-only- envelope appended: one picture per ``image_queries`` subject when the model named them, else- a handful for the query. ``image_queries`` alone (no query) is a pure image lookup."""+ """search approved tiers, fetch a URL, or return registered ``[[img:<id>]]`` images alone."""# Direct URL fetch mode.if url and url.strip():fetch_timeout = 60 if timeout is None else min(timeout, 60)@@ -16944,8 +16991,7 @@ def _web_search(if subjects and not (query and query.strip()):if not include_images:return IMAGE_SEARCH_DISABLED- # Ahead of the try below, so this one has to carry its own guard: execute_tool returns a string for every- # input, and a raise here would escape _web_search.+ # guard here because execute_tool requires a string result and this is outside the try.found = _image_search_or_none(subjects, timeout, cancel_event, website_policy)if found is None:return "No images found for: " + ", ".join(subjects)@@ -16953,57 +16999,88 @@ def _web_search(if not query or not query.strip():return "No query provided."- # A disconnect sets cancel_event; DDGS.text() is blocking and cannot be interrupted mid-flight, so gate on either- # side: skip an already-cancelled request, and discard results that land after the client has gone.+ # DDGS.text() is blocking, so cancellation is checked before and after the call.if cancel_event is not None and cancel_event.is_set():return "Search cancelled."try:- from ddgs import DDGS- from ddgs.engines import ENGINES-from .web_access_policy import check_url_access, scope_search_query- engine_tiers = _resolve_engine_tiers(ENGINES.get("text", {}))- if not engine_tiers:- return "Search failed: no approved search engine is available."-effective_query = scope_search_query(query, website_policy)- # The policy filters below, so ask for a deeper pool when one actually restricts: a page whose top hits are- # all disallowed otherwise yields nothing even when valid results rank just under them. Test the domain lists,- # not the dict: a run always stores a normalized policy, which is truthy even when unrestricted.+ # overfetch for allowed hits below blocked ones; normalized policy remains truthy.restricted = any((website_policy or {}).get(key) for key in ("allowedDomains", "blockedDomains"))wanted = max_results * _POLICY_OVERFETCH if restricted else max_results- # ddgs applies `timeout` per client, as both the engine HTTP timeout and its fan-out wait, so- # a client per tier would restart the budget and a 7s web_search could block ~14s.+ # bound fallback even if importing or resolving ddgs fails before its normal budget starts.deadline = time.monotonic() + timeout if timeout else None- client = DDGS(timeout = timeout)- # ddgs signals an empty sweep by RAISING, so a tier's exception means try the next tier; the- # last is re-raised for _search_failure_message to classify as a single-tier failure would be.- results, last_error = [], None- for backend in engine_tiers:- if cancel_event is not None and cancel_event.is_set():- return "Search cancelled."- if deadline is not None:- remaining = deadline - time.monotonic()- if remaining <= 0:+ client, results, last_error = None, [], None+ rejected_results = False+ wikipedia_fallback = False+ try:+ from ddgs import DDGS+ from ddgs.engines import ENGINES++ engine_tiers = _resolve_engine_tiers(ENGINES.get("text", {}))+ if not engine_tiers:+ raise RuntimeError("no approved search engine is available.")+ # reset after setup to keep the primary budget; the earlier deadline bounds fallback.+ deadline = time.monotonic() + timeout if timeout else None+ client = DDGS(timeout = timeout)+ # DDGS uses per-client timeouts; tiers share one budget and images reuse the client.+ for backend in engine_tiers:+ if cancel_event is not None and cancel_event.is_set():+ return "Search cancelled."+ if deadline is not None:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ break+ client = DDGS(timeout = remaining)+ try:+ candidates = client.text(effective_query, max_results = wanted, backend = backend)+ results = _usable_search_results(candidates, website_policy)+ rejected_results = rejected_results or bool(candidates and not results)+ except Exception as exc: # noqa: BLE001 - try the next tier before classifying the failure+ last_error = exc+ continue+ if results:break- client = DDGS(timeout = remaining)- try:- results = client.text(effective_query, max_results = wanted, backend = backend)- except Exception as exc: # noqa: BLE001 - re-raised below when no tier produced anything- last_error = exc- continue- if results:- break- if not results and last_error is not None:- raise last_error+ except Exception as exc:+ last_error = excif cancel_event is not None and cancel_event.is_set():return "Search cancelled."+ if not results:+ remaining = deadline - time.monotonic() if deadline else 5.0+ allowed, _, _ = check_url_access("https://en.wikipedia.org/w/api.php", website_policy)+ if allowed and remaining > 0:+ try:+ fallback_timeout = min(remaining, 5.0)+ fallback_deadline = time.monotonic() + fallback_timeout+ if deadline is not None:+ fallback_deadline = min(fallback_deadline, deadline)+ results = _usable_search_results(+ _wikipedia_search(+ query,+ wanted,+ fallback_timeout,+ fallback_deadline,+ cancel_event,+ website_policy,+ ),+ website_policy,+ )+ wikipedia_fallback = bool(results)+ except Exception:+ logger.debug("Independent Wikipedia search failed", exc_info = True)+ if cancel_event is not None and cancel_event.is_set():+ return "Search cancelled."+ # blocked results take precedence over earlier tier exceptions.+ if not results and last_error is not None and not rejected_results:+ raise last_errorif not results:return _empty_result_with_requested_images(- EMPTY_SEARCH_RESULTS[0],+ EMPTY_SEARCH_RESULTS[1]+ if rejected_results and restricted+ else EMPTY_SEARCH_RESULTS[0],subjects,include_images,timeout,@@ -17018,7 +17095,7 @@ def _web_search(allowed, _reason, _hostname = check_url_access(href, website_policy)if not allowed:continue- title = " ".join(str(r.get("title") or "").split())+ title = " ".join(str(r.get("title") or href).split())snippet = " ".join(str(r.get("body") or "").split())parts.append(f"Title: {title}\nURL: {href}\nSnippet: {snippet}")if not parts:@@ -17031,17 +17108,23 @@ def _web_search(website_policy,)text = "\n\n---\n\n".join(parts)+ if wikipedia_fallback:+ text = (+ "General web search was unavailable or returned no usable results. "+ "These are Wikipedia-only encyclopedia results, not current web coverage.\n\n"+ + text+ )text += ("\n\n---\n\nIMPORTANT: These are only short snippets. ""To get the full page content, call web_search with "'the url parameter (e.g. {"url": "<URL>"}).')if include_images and subjects:- # The model named what it will show: one picture per subject, no generic pile.+ # named subjects require one image each rather than a generic image batch.found = _image_search_or_none(subjects, timeout, cancel_event, website_policy)if found is not None:text += "\n\n---\n\n" + found- elif include_images:+ elif include_images and not wikipedia_fallback:text += _web_search_images_suffix(client,effective_query,@@ -17050,13 +17133,12 @@ def _web_search(website_policy,)elif subjects:- # Replayed history keeps teaching the parameter; say so, don't drop it.+ # replayed history must retain the disabled-search reminder.text += "\n\n---\n\n" + IMAGE_SEARCH_DISABLEDreturn textexcept Exception as e:failure = _search_failure_message(e, timeout)- # ddgs signals an empty sweep by RAISING, so that exit is an empty result too and owes the named subjects- # their pictures. A genuine failure keeps its message alone: pictures under an error read as a partial answer.+ # ddgs raises on an empty sweep; attach requested images only to empty results, not genuine errors.if failure == EMPTY_SEARCH_RESULTS[0]:return _empty_result_with_requested_images(failure,diff --git a/studio/backend/tests/test_search_images.py b/studio/backend/tests/test_search_images.pyindex b6f0136e765..eec59a964f9 100644--- a/studio/backend/tests/test_search_images.py+++ b/studio/backend/tests/test_search_images.py@@ -59,6 +59,7 @@ RAW_IMAGES = [@pytest.fixture(autouse = True)def _isolated_state(monkeypatch, tmp_path):+ monkeypatch.setattr(tools, "_wikipedia_search", lambda *args: [])monkeypatch.setattr(search_images, "_registry", {})monkeypatch.setattr(search_images, "_inflight", {})monkeypatch.setattr(search_images, "_cleared_unservable", set())diff --git a/studio/backend/tests/test_web_access_policy.py b/studio/backend/tests/test_web_access_policy.pyindex 9fbd530a06c..cc793a8775a 100644--- a/studio/backend/tests/test_web_access_policy.py+++ b/studio/backend/tests/test_web_access_policy.py@@ -290,6 +290,8 @@ def test_direct_fetch_rechecks_every_redirect_before_dns(monkeypatch):def _search_with_raising_ddgs(monkeypatch, exc: Exception) -> str:+ monkeypatch.setattr(tools, "_wikipedia_search", lambda *args: [])+class FakeDDGS:def __init__(self, **_kwargs):passdiff --git a/studio/backend/tests/test_web_search_fallback.py b/studio/backend/tests/test_web_search_fallback.pynew file mode 100644index 00000000000..b12e5f62dc5--- /dev/null+++ b/studio/backend/tests/test_web_search_fallback.py@@ -0,0 +1,353 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import json+import sys+import threading+from concurrent.futures import ThreadPoolExecutor+from types import SimpleNamespace+from unittest.mock import Mock+from unittest.mock import patch+import pytest+from core.inference import tools+++def missing_ddgs():+ return patch.dict(sys.modules, {"ddgs": None})++[email protected]("args", [{}, {"query": " "}, {"query": 123}])+def test_missing_input_does_not_contact_fallback(args):+ with patch.object(tools, "_wikipedia_search") as wiki:+ assert tools.execute_tool("web_search", args) == "No query provided."+ wiki.assert_not_called()+++def test_missing_package_recovers():+ with (+ missing_ddgs(),+ patch.object(+ tools,+ "_wikipedia_search",+ return_value = [+ {+ "title": "Python",+ "href": "https://en.wikipedia.org/wiki/Python",+ "body": "snippet",+ }+ ],+ ) as wiki,+ ):+ result = tools._web_search("Python", timeout = 8)+ assert "Wikipedia-only" in result and "URL: https://" in result+ wiki.assert_called_once()+++ "policy", [{"blockedDomains": ["wikipedia.org"]}, {"allowedDomains": ["python.org"]}]+)+def test_policy_skips_wikipedia(policy):+ with missing_ddgs(), patch.object(tools, "_wikipedia_search") as wiki:+ assert tools._web_search("Python", website_policy = policy).startswith("Search failed:")+ wiki.assert_not_called()+++def test_cancel_skips_network():+ event = threading.Event()+ event.set()+ with patch.object(tools, "_wikipedia_search") as wiki:+ assert tools._web_search("Python", cancel_event = event) == "Search cancelled."+ wiki.assert_not_called()+++def test_cancel_during_fallback_discards_results():+ event = threading.Event()++ def wiki(*a):+ event.set()+ return [+ {"title": "Python", "href": "https://en.wikipedia.org/wiki/Python", "body": "snippet"}+ ]++ with missing_ddgs(), patch.object(tools, "_wikipedia_search", side_effect = wiki):+ assert tools._web_search("Python", cancel_event = event) == "Search cancelled."+++def test_both_fail_preserves_primary_error():+ with (+ missing_ddgs(),+ patch.object(tools, "_wikipedia_search", side_effect = RuntimeError("offline")),+ ):+ assert "import of ddgs halted" in tools._web_search("Python")+++def test_api_html_and_url():+ response = {+ "query": {+ "search": [+ {"title": "A & B", "snippet": 'An <span class="searchmatch">A</span> & B'}+ ]+ }+ }+ with patch.object(+ tools, "_fetch_url_raw", return_value = (None, json.dumps(response), "application/json")+ ) as fetch:+ result = tools._wikipedia_search("A & B", 5, 3, None, None, None)+ assert result == [+ {"title": "A & B", "href": "https://en.wikipedia.org/wiki/A_%26_B", "body": "An A & B"}+ ]+ assert fetch.call_args.kwargs["raw_bytes_max"] == 1024 * 1024+++PRIMARY_RESULT = [+ {"title": "Primary", "href": "https://primary.example/page", "body": "Current information"}+]+FALLBACK_RESULT = [+ {"title": "Wikipedia", "href": "https://en.wikipedia.org/wiki/Example", "body": "Background"}+]+++def provider(monkeypatch):+ """controls provider responses without network calls or ddgs's lazy proxy."""+ state = SimpleNamespace(calls = [], respond = lambda client, query, **kwargs: PRIMARY_RESULT)++ class DDGS:+ def __init__(self, timeout):+ self.timeout = timeout++ def text(self, query, **kwargs):+ state.calls.append((query, kwargs["backend"], self.timeout, kwargs["max_results"]))+ return state.respond(self, query, **kwargs)++ monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS = DDGS))+ monkeypatch.setitem(+ sys.modules,+ "ddgs.engines",+ SimpleNamespace(ENGINES = {"text": {"wikipedia": object(), "google": object()}}),+ )+ state.wiki = Mock(return_value = FALLBACK_RESULT)+ monkeypatch.setattr(tools, "_wikipedia_search", state.wiki)+ return state+++def search_clock(monkeypatch):+ clock = SimpleNamespace(now = 100.0)+ monkeypatch.setattr(tools, "time", SimpleNamespace(monotonic = lambda: clock.now))+ return clock++[email protected]("timeout", [0.6, 9, 300, None, 0])+def test_primary_success_keeps_full_provider_timeout(provider, search_clock, timeout):+ result = tools._web_search("current information", timeout = timeout)+ assert "Title: Primary" in result+ assert len(provider.calls) == 1+ query, backend, budget, wanted = provider.calls[0]+ assert (query, backend, wanted) == ("current information", "wikipedia", 5)+ assert budget == pytest.approx(timeout) if timeout is not None else budget is None+ provider.wiki.assert_not_called()++[email protected]("blocked", [False, True])+def test_primary_late_success_is_not_replaced(provider, search_clock, blocked):+ def respond(client, query, **kwargs):+ if client.timeout < 298:+ raise TimeoutError("provider needed 298 seconds")+ search_clock.now += 298+ return PRIMARY_RESULT++ provider.respond = respond+ policy = {"blockedDomains": ["wikipedia.org"]} if blocked else None+ result = tools._web_search("current information", website_policy = policy)+ assert "Title: Primary" in result+ provider.wiki.assert_not_called()+++def test_primary_second_tier_gets_original_remaining_budget(provider, search_clock):+ def respond(client, query, **kwargs):+ if kwargs["backend"] == "wikipedia":+ search_clock.now += 297+ return []+ if client.timeout < 3:+ raise TimeoutError("second tier needs the remaining three seconds")+ return PRIMARY_RESULT++ provider.respond = respond+ result = tools._web_search("current information")+ assert "Title: Primary" in result+ assert [call[2] for call in provider.calls] == [300, 3]+ provider.wiki.assert_not_called()+++def test_primary_image_search_retains_client_budget(provider, monkeypatch, search_clock):+ budgets = []++ def images(client, *args):+ budgets.append(client.timeout)+ return "\nIMAGES_FOUND" if client.timeout >= 8 else ""++ monkeypatch.setattr(tools, "_web_search_images_suffix", images)+ result = tools._web_search("current information", timeout = 9, include_images = True)+ assert "IMAGES_FOUND" in result+ assert budgets == [9]+ provider.wiki.assert_not_called()+++def test_primary_eight_parallel_successes_all_use_provider(provider):+ lock = threading.Lock()+ entered = []+ all_entered = threading.Event()+ release = threading.Event()++ def respond(client, query, **kwargs):+ with lock:+ entered.append(query)+ if len(entered) == 8:+ all_entered.set()+ release.wait(3)+ return PRIMARY_RESULT++ provider.respond = respond+ with ThreadPoolExecutor(max_workers = 8) as pool:+ futures = [pool.submit(tools._web_search, f"query {i}", timeout = 5) for i in range(8)]+ try:+ admitted = all_entered.wait(1)+ finally:+ release.set()+ results = [future.result(timeout = 5) for future in futures]+ assert admitted, f"Only {len(entered)} successful requests reached the provider"+ assert all("Title: Primary" in result for result in results)+ provider.wiki.assert_not_called()+++def test_fallback_uses_only_remaining_budget(provider, search_clock):+ def respond(client, query, **kwargs):+ search_clock.now += 4+ return []++ provider.respond = respond+ assert "Wikipedia-only" in tools._web_search("query", timeout = 9)+ assert provider.wiki.call_args.args[2:4] == (1, 109)++[email protected]("timeout", [30, None])+def test_fallback_has_its_own_five_second_cap(provider, search_clock, timeout):+ provider.respond = lambda *args, **kwargs: []+ assert "Wikipedia-only" in tools._web_search("query", timeout = timeout)+ assert provider.wiki.call_args.args[2:4] == (5, 105)+++def test_fallback_does_not_extend_exhausted_budget(provider, search_clock):+ def respond(client, query, **kwargs):+ search_clock.now += 10+ raise TimeoutError("primary timeout")++ provider.respond = respond+ assert "primary timeout" in tools._web_search("query", timeout = 9)+ provider.wiki.assert_not_called()+++def test_primary_overrun_success_keeps_legacy_behavior(provider, search_clock):+ def respond(client, query, **kwargs):+ search_clock.now += 10+ return PRIMARY_RESULT++ provider.respond = respond+ assert "Title: Primary" in tools._web_search("query", timeout = 9)+ provider.wiki.assert_not_called()++[email protected]("outcome", ["empty", "error", "missing_url"])+def test_fallback_recovers_when_all_tiers_are_unusable(provider, outcome):+ def respond(client, query, **kwargs):+ if outcome == "error":+ raise RuntimeError("provider failed")+ if outcome == "missing_url":+ return [{"title": "No URL", "body": "Unusable"}]+ return []++ provider.respond = respond+ assert "Wikipedia-only" in tools._web_search("query")+ assert len(provider.calls) == 2+ provider.wiki.assert_called_once()+++def test_filtered_first_tier_continues_to_usable_second_tier(provider):+ def respond(client, query, **kwargs):+ if kwargs["backend"] == "wikipedia":+ return [{"title": "Blocked", "href": "https://blocked.example/page", "body": "Blocked"}]+ return PRIMARY_RESULT++ provider.respond = respond+ result = tools._web_search("query", website_policy = {"blockedDomains": ["blocked.example"]})+ assert "Title: Primary" in result+ assert "blocked.example/page" not in result+ assert len(provider.calls) == 2+ provider.wiki.assert_not_called()+++def test_cancel_during_primary_discards_answer_without_fallback(provider):+ event = threading.Event()++ def respond(client, query, **kwargs):+ event.set()+ return PRIMARY_RESULT++ provider.respond = respond+ assert tools._web_search("query", cancel_event = event) == "Search cancelled."+ provider.wiki.assert_not_called()++[email protected]("timeout", [None, 0])+def test_primary_without_deadline_reuses_client_between_tiers(provider, timeout):+ def respond(client, query, **kwargs):+ if kwargs["backend"] == "wikipedia":+ client.first_tier_ran = True+ return []+ assert client.first_tier_ran+ return PRIMARY_RESULT++ provider.respond = respond+ assert "Title: Primary" in tools._web_search("query", timeout = timeout)+ provider.wiki.assert_not_called()++[email protected]("import_fails", [False, True])+def test_setup_time_preserves_primary_budget_but_bounds_failed_import_fallback(+ provider, search_clock, monkeypatch, import_fails+):+ import builtins++ real_import = builtins.__import__++ def delayed_import(name, *args, **kwargs):+ if name == "ddgs":+ search_clock.now += 2+ if import_fails:+ raise ImportError("ddgs unavailable")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", delayed_import)+ result = tools._web_search("query", timeout = 3)+ if import_fails:+ assert "Wikipedia-only" in result+ assert provider.wiki.call_args.args[2:4] == (1, 103)+ assert not provider.calls+ else:+ assert "Title: Primary" in result+ assert provider.calls[0][2] == 3+ provider.wiki.assert_not_called()++[email protected]("failing", ["wikipedia", "google"])+def test_blocked_tier_answer_outranks_other_tier_error(provider, failing):+ def respond(client, query, **kwargs):+ if kwargs["backend"] == failing:+ raise RuntimeError("provider failed")+ return [{"title": "Blocked", "href": "https://blocked.example/page", "body": "Blocked"}]++ provider.respond = respond+ provider.wiki.return_value = []+ result = tools._web_search("query", website_policy = {"blockedDomains": ["blocked.example"]})+ assert result.startswith(tools.EMPTY_SEARCH_RESULTS[1])diff --git a/studio/backend/tests/test_web_search_tiers.py b/studio/backend/tests/test_web_search_tiers.pyindex 71e61fa241d..1c25335bb1b 100644--- a/studio/backend/tests/test_web_search_tiers.py+++ b/studio/backend/tests/test_web_search_tiers.py@@ -1,13 +1,9 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Built-in text search runs an approved allowlist, tier by tier, and never reaches Yandex.+"""uses the real DDGS selector so fan-out cannot hide tier-resolution errors."""-Drives the real DDGS engine selector through ``execute_tool``; only each engine's own ``search`` is-replaced, so the tier strings really are resolved by ddgs and a fan-out cannot hide.-"""--import time+from types import SimpleNamespaceimport pytest@@ -62,9 +58,10 @@ class _Recorder:def engine_calls(monkeypatch):from ddgs.ddgs import DDGS- # 9.14.4 defines _get_network_client; a DHT cache hit would skip the engines entirely.+ # disable the 9.14.4 DHT cache because a hit skips every engine.if callable(getattr(DDGS, "_get_network_client", None)):monkeypatch.setattr(DDGS, "_get_network_client", lambda self: None)+ monkeypatch.setattr(tools, "_wikipedia_search", lambda *args: [])return _Recorder(monkeypatch)@@ -73,8 +70,7 @@ def _names(recorder):def _require_two_tiers():- """Skip rather than go red if an upstream release ever leaves fewer than two resolvable tiers.- Both pins resolve two: 9.14.4 all three members, 9.8.0 yahoo alone."""+ """skip if upstream resolves fewer than two tiers; 9.14.4 has every tier-two engine and 9.8.0 only Yahoo."""resolved = tools._resolve_engine_tiers(ENGINES["text"])if len(resolved) < 2:pytest.skip(f"installed ddgs resolves only {len(resolved)} tier(s): {resolved}")@@ -172,7 +168,7 @@ def test_disabled_engines_are_dropped_from_a_tier(monkeypatch, engine_calls):def test_the_caller_timeout_is_one_budget_for_both_tiers(monkeypatch, engine_calls):- """Tier 2 inherits what is LEFT of the timeout: a fresh copy doubles what the caller asked for."""+ """tier 2 must receive the remaining timeout because a fresh budget doubles the caller's limit."""from ddgs.ddgs import DDGSbudgets = []@@ -184,34 +180,29 @@ def test_the_caller_timeout_is_one_budget_for_both_tiers(monkeypatch, engine_calmonkeypatch.setattr(DDGS, "__init__", recording_init)- # Tier 1 burns most of the budget before coming back empty, so tier 2 runs with what is left.- def slow_tier_one(name):- if name in TIER1:- return "empty"- return "results"-- engine_calls.install(slow_tier_one)- for name in TIER1:- cls = ENGINES["text"].get(name)- if cls is not None:- inner = cls.search- monkeypatch.setattr(- cls, "search", lambda self, q, _i = inner, **k: (time.sleep(0.3), _i(self, q, **k))[1]- )-- tools.execute_tool("web_search", {"query": "unsloth", "timeout": 3})-- tier_budgets = [b for b in budgets if isinstance(b, (int, float))]- assert len(tier_budgets) >= 3, f"expected a client per tier, saw {budgets}"- # Each value is the budget REMAINING when that tier starts, so the invariant is that it shrinks- # and never exceeds what the caller asked for. Summing them would be summing overlapping windows.- assert tier_budgets == sorted(- tier_budgets, reverse = True- ), f"budget did not shrink: {tier_budgets}"- assert (- tier_budgets[-1] < tier_budgets[0]- ), f"tier 2 was handed {tier_budgets[-1]}, not the remainder of {tier_budgets[0]}"- assert max(tier_budgets) <= tier_budgets[0], "a tier was handed more than the original budget"+ engine_calls.install(lambda name: "empty" if name in TIER1 else "results")+ clock = SimpleNamespace(now = 100.0)+ monkeypatch.setattr(tools, "time", SimpleNamespace(monotonic = lambda: clock.now))+ real_text = DDGS.text+ searched_tiers = []++ def timed_text(self, *args, **kwargs):+ searched_tiers.append(kwargs["backend"])+ try:+ return real_text(self, *args, **kwargs)+ finally:+ # advance only Studio's clock so ddgs engine selection stays deterministic.+ clock.now += 1++ monkeypatch.setattr(DDGS, "text", timed_text)+ # timeout belongs to the executor, not the model-provided tool arguments.+ result = tools.execute_tool("web_search", {"query": "unsloth"}, timeout = 3)++ assert "URL:" in result+ assert searched_tiers == tools._resolve_engine_tiers(ENGINES["text"])+ assert set(_names(engine_calls)) & set(TIER2), "the second tier must actually run"+ # the initial client and first tier get three seconds; the second tier gets the two seconds left.+ assert budgets == [3, 3, 2]def test_the_resolver_never_names_an_engine_outside_the_tiers():