The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(search): add Nimble as a search provider (#36347)
Ilan Chemlaf99d0a4b389c
diff --git a/litellm/llms/base_llm/search/transformation.py b/litellm/llms/base_llm/search/transformation.pyindex 6987e261d4e..dee67e0b100 100644--- a/litellm/llms/base_llm/search/transformation.py+++ b/litellm/llms/base_llm/search/transformation.py@@ -18,6 +18,16 @@ else:LiteLLMLoggingObj = Any+_PERPLEXITY_UNIFIED_PARAMS: Final[frozenset[str]] = frozenset(+ (+ "max_results",+ "search_domain_filter",+ "country",+ "max_tokens_per_page",+ )+)++def _search_host(url: str) -> str:return urlsplit(url).netloc.lower()@@ -96,7 +106,7 @@ class BaseSearchConfig:return "POST"@staticmethod- def get_supported_perplexity_optional_params() -> set:+ def get_supported_perplexity_optional_params() -> frozenset[str]:"""Get the set of Perplexity unified search parameters.These are the standard parameters that providers should transform from.@@ -104,12 +114,7 @@ class BaseSearchConfig:Returns:Set of parameter names that are part of the unified spec"""- return {- "max_results",- "search_domain_filter",- "country",- "max_tokens_per_page",- }+ return _PERPLEXITY_UNIFIED_PARAMSdef _assert_trusted_api_base_for_server_credential(self,diff --git a/litellm/llms/nimble/__init__.py b/litellm/llms/nimble/__init__.pynew file mode 100644index 00000000000..05272cb1230--- /dev/null+++ b/litellm/llms/nimble/__init__.py@@ -0,0 +1,3 @@+from litellm.llms.nimble.search.transformation import NimbleSearchConfig++__all__ = ("NimbleSearchConfig",)diff --git a/litellm/llms/nimble/search/__init__.py b/litellm/llms/nimble/search/__init__.pynew file mode 100644index 00000000000..05272cb1230--- /dev/null+++ b/litellm/llms/nimble/search/__init__.py@@ -0,0 +1,3 @@+from litellm.llms.nimble.search.transformation import NimbleSearchConfig++__all__ = ("NimbleSearchConfig",)diff --git a/litellm/llms/nimble/search/transformation.py b/litellm/llms/nimble/search/transformation.pynew file mode 100644index 00000000000..7485686d230--- /dev/null+++ b/litellm/llms/nimble/search/transformation.py@@ -0,0 +1,264 @@+"""+Calls Nimble's /v2/search endpoint to search the web.++Nimble API Reference: https://docs.nimbleway.com/api-reference/search/search+"""++from __future__ import annotations++from collections.abc import Mapping+from types import MappingProxyType+from typing import TYPE_CHECKING, Final++import httpx+from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError++from litellm.llms.base_llm.chat.transformation import BaseLLMException+from litellm.llms.base_llm.search.transformation import (+ BaseSearchConfig,+ SearchResponse,+ SearchResult,+)+from litellm.secret_managers.main import get_secret_str++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj++_NIMBLE_DOCS_URL: Final = "https://docs.nimbleway.com/api-reference/search/search"+++class _NimbleResult(BaseModel):+ """One entry of Nimble's `results` array. Every field is optional so a single degraded+ result degrades to empty strings instead of failing the whole call."""++ model_config = ConfigDict(extra="ignore", frozen=True)++ title: str | None = None+ url: str | None = None+ content: str | None = None+ description: str | None = None+ # Free-form per Nimble's schema, so an unexpected shape must not fail the search.+ additional_data: object = None+++class _NimbleSearchResponse(BaseModel):+ """Nimble's /v2/search response envelope."""++ model_config = ConfigDict(extra="ignore", frozen=True)++ # Required: a search with no hits returns `[]`, so a null or absent `results` means the+ # body is not a search response and must not be reported as a successful empty search.+ results: tuple[_NimbleResult, ...]+++class _AdditionalData(BaseModel):+ """The slice of a result's free-form `additional_data` that maps onto SearchResult."""++ model_config = ConfigDict(extra="ignore", frozen=True)++ publish_date: str | None = None+++class _ErrorEnvelope(BaseModel):+ """Nimble reports errors as either `{"detail": ...}` (validation) or+ `{"success": "false", "task_id": ..., "message": ...}` (collection)."""++ model_config = ConfigDict(extra="ignore", frozen=True)++ detail: str | None = None+ message: str | None = None+++_DomainListAdapter: Final = TypeAdapter(tuple[str, ...])++_NOTHING: Final[Mapping[str, object]] = MappingProxyType({})+++def _optional(key: str, value: object) -> Mapping[str, object]:+ """A one-entry mapping to spread into a payload, or nothing when the value is absent."""+ return MappingProxyType({key: value}) if value is not None else _NOTHING+++class NimbleSearchConfig(BaseSearchConfig):+ NIMBLE_API_BASE = "https://sdk.nimbleway.com/v2"++ @staticmethod+ def ui_friendly_name() -> str:+ return "Nimble"++ def validate_environment(+ self,+ headers: dict[str, str], # mutable-ok: BaseSearchConfig.validate_environment signature+ api_key: str | None = None,+ api_base: str | None = None,+ **kwargs: object, # kwargs-ok: BaseSearchConfig.validate_environment signature+ ) -> dict[str, str]: # mutable-ok: the http handler passes this straight to httpx as headers+ """+ Validate environment and return headers.++ Returns a new dict rather than mutating ``headers``: the http handler calls this+ a second time after ``litellm/search/main.py`` already did, so it has to be idempotent.+ """+ resolved_api_key: Final = self.resolve_server_api_key(+ caller_api_key=api_key,+ caller_api_base=api_base,+ key_env_vars=("NIMBLE_API_KEY",),+ base_env_var="NIMBLE_API_BASE",+ default_api_base=self.NIMBLE_API_BASE,+ )+ if not resolved_api_key:+ raise ValueError("NIMBLE_API_KEY is not set. Set `NIMBLE_API_KEY` environment variable.")+ return { # mutable-ok: httpx requires a plain dict of headers+ **headers,+ "Authorization": f"Bearer {resolved_api_key}",+ "Content-Type": "application/json",+ # Nimble's client-attribution header: names the calling software, nothing else.+ "X-Client-Source": "litellm",+ }++ def get_complete_url(+ self,+ api_base: str | None,+ optional_params: dict[str, object], # mutable-ok: BaseSearchConfig.get_complete_url signature+ data: dict[str, object] | list[dict[str, object]] | None = None, # mutable-ok: base signature+ **kwargs: object, # kwargs-ok: BaseSearchConfig.get_complete_url signature+ ) -> str:+ resolved_base: Final = (api_base or get_secret_str("NIMBLE_API_BASE") or self.NIMBLE_API_BASE).rstrip("/")+ if resolved_base.endswith("/search"):+ return resolved_base+ return f"{resolved_base}/search"++ def transform_search_request(+ self,+ query: str | list[str], # mutable-ok: BaseSearchConfig.transform_search_request signature+ optional_params: dict[str, object], # mutable-ok: base signature+ **kwargs: object, # kwargs-ok: BaseSearchConfig.transform_search_request signature+ ) -> dict[str, object]: # mutable-ok: the http handler passes this straight to httpx as the JSON body+ """+ Transform Search request to Nimble API format.++ Nimble already uses the Perplexity unified spec's names, so this is close to a pass-through:+ - query -> query (a list is joined with spaces; Nimble takes a single string)+ - max_results -> max_results (sent unclamped so Nimble's own 1-100 validation reports the error)+ - country -> country, upper-cased to the ISO form Nimble documents+ - search_domain_filter -> include_domains, with `-`-prefixed entries going to exclude_domains+ - max_tokens_per_page -> dropped (no Nimble equivalent)++ Everything else is forwarded as-is, so the rest of Nimble's surface stays reachable+ without LiteLLM tracking it.+ """+ unified_params: Final = self.get_supported_perplexity_optional_params()+ country: Final = optional_params.get("country")++ # Spread after the derived domain filters so an explicitly supplied `include_domains`+ # or `exclude_domains` wins over anything read out of `search_domain_filter`.+ passthrough: Final = MappingProxyType(+ {param: value for param, value in optional_params.items() if param not in unified_params}+ )++ return { # mutable-ok: httpx requires a plain dict for the JSON body+ **_domain_filters(optional_params.get("search_domain_filter")),+ **passthrough,+ "query": " ".join(query) if isinstance(query, list) else query,+ **_optional("max_results", optional_params.get("max_results")),+ **_optional("country", country.upper() if isinstance(country, str) else None),+ }++ def transform_search_response(+ self,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ **kwargs: object, # kwargs-ok: BaseSearchConfig.transform_search_response signature+ ) -> SearchResponse:+ """+ Transform Nimble API response to LiteLLM unified SearchResponse format.++ `date` carries only the absolute `publish_date`. News results often carry a relative+ `publish_date_raw` ("1 day ago") instead, which is not a date, so the whole+ `additional_data` object rides through as an extra on `SearchResult` and nothing is lost.++ Nimble ranks results itself via metadata.position, so the order is preserved as received.+ A body that does not match the documented schema raises an attributed error rather than+ being reported as a successful empty search. Parsing the response bytes rather than+ `.json()` covers the non-JSON case through that same path.+ """+ try:+ parsed: Final = _NimbleSearchResponse.model_validate_json(raw_response.content)+ except ValidationError as e:+ raise self.get_error_class(+ error_message=f"response does not match the documented /v2/search schema: {e}",+ status_code=raw_response.status_code,+ headers=dict(raw_response.headers), # mutable-ok: BaseSearchConfig.get_error_class signature+ )++ return SearchResponse(+ results=[ # mutable-ok: SearchResponse.results is declared list[SearchResult]+ SearchResult(+ title=result.title or "",+ url=result.url or "",+ snippet=result.content or result.description or "",+ date=_publish_date(result.additional_data),+ last_updated=None,+ **_optional("additional_data", result.additional_data),+ )+ for result in parsed.results+ ],+ object="search",+ )++ def get_error_class(+ self,+ error_message: str,+ status_code: int,+ headers: dict[str, str], # mutable-ok: BaseSearchConfig.get_error_class signature+ ) -> Exception:+ detail: Final = _unwrap_error_detail(error_message).rstrip(". ")+ return BaseLLMException(+ status_code=status_code,+ message=f"Nimble Search: {detail}. See {_NIMBLE_DOCS_URL} for details.",+ headers=headers,+ )+++def _unwrap_error_detail(error_message: str) -> str:+ """+ Surface the human-readable message inside Nimble's error envelopes.++ Falls back to the raw body for anything else (CDN HTML pages, plain text, other shapes).+ """+ try:+ body: Final = _ErrorEnvelope.model_validate_json(error_message)+ except ValidationError:+ return error_message+ return body.detail or body.message or error_message+++def _domain_filters(search_domain_filter: object) -> Mapping[str, object]:+ """+ Split the unified `search_domain_filter` into Nimble's include/exclude lists.++ Follows the Perplexity unified spec, where a `-` prefix means "exclude this domain".+ Anything that is not a list of strings is ignored rather than raising, since it only+ ever narrows a search that is otherwise valid.+ """+ try:+ domains: Final = _DomainListAdapter.validate_python(search_domain_filter)+ except ValidationError:+ return _NOTHING+ return MappingProxyType(+ {+ key: value+ for key, value in (+ ("include_domains", tuple(d for d in domains if d and not d.startswith("-"))),+ ("exclude_domains", tuple(d[1:] for d in domains if d.startswith("-") and len(d) > 1)),+ )+ if value+ }+ )+++def _publish_date(additional_data: object) -> str | None:+ try:+ return _AdditionalData.model_validate(additional_data).publish_date+ except ValidationError:+ return Nonediff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex b288269b0a2..0eb9f6119ff 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -16295,6 +16295,14 @@"notes": "TinyFish Search API"}},+ "nimble/search": {+ "input_cost_per_query": 0.005,+ "litellm_provider": "nimble",+ "mode": "search",+ "metadata": {+ "notes": "Nimble Search API pay-as-you-go list price: $5 per 1,000 searches, up to 100 results per search. Volume plans price differently."+ }+ },"elevenlabs/scribe_v1": {"input_cost_per_second": 6.11e-05,"litellm_provider": "elevenlabs",diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex d9ef538d530..220826ccbca 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -3758,6 +3758,7 @@ class SearchProviders(str, Enum):YOU_COM = "you_com"APISERPENT = "apiserpent"TINYFISH = "tinyfish"+ NIMBLE = "nimble"# Create a set of all search provider values for quick lookupdiff --git a/litellm/utils.py b/litellm/utils.pyindex 79372f00284..f011c1ff62f 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -9064,6 +9064,7 @@ class ProviderConfigManager:from litellm.llms.firecrawl.search.transformation import FirecrawlSearchConfigfrom litellm.llms.google_pse.search.transformation import GooglePSESearchConfigfrom litellm.llms.linkup.search.transformation import LinkupSearchConfig+ from litellm.llms.nimble.search.transformation import NimbleSearchConfigfrom litellm.llms.parallel_ai.search.transformation import (ParallelAISearchConfig,)@@ -9093,6 +9094,7 @@ class ProviderConfigManager:SearchProviders.YOU_COM: YouComSearchConfig,SearchProviders.APISERPENT: APISerpentSearchConfig,SearchProviders.TINYFISH: TinyfishSearchConfig,+ SearchProviders.NIMBLE: NimbleSearchConfig,}config_class: Final = PROVIDER_TO_CONFIG_MAP.get(provider, None)if config_class is None:diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex b288269b0a2..0eb9f6119ff 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -16295,6 +16295,14 @@"notes": "TinyFish Search API"}},+ "nimble/search": {+ "input_cost_per_query": 0.005,+ "litellm_provider": "nimble",+ "mode": "search",+ "metadata": {+ "notes": "Nimble Search API pay-as-you-go list price: $5 per 1,000 searches, up to 100 results per search. Volume plans price differently."+ }+ },"elevenlabs/scribe_v1": {"input_cost_per_second": 6.11e-05,"litellm_provider": "elevenlabs",diff --git a/provider_endpoints_support.json b/provider_endpoints_support.jsonindex 65db63dc045..0712e8e383d 100644--- a/provider_endpoints_support.json+++ b/provider_endpoints_support.json@@ -2423,6 +2423,13 @@"search": true}},+ "nimble": {+ "display_name": "Nimble (`nimble`)",+ "url": "https://docs.nimbleway.com/api-reference/search/search",+ "endpoints": {+ "search": true+ }+ },"triton": {"display_name": "Triton (`triton`)","url": "https://docs.litellm.ai/docs/providers/triton-inference-server",diff --git a/tests/code_coverage_tests/enforce_llms_folder_style.py b/tests/code_coverage_tests/enforce_llms_folder_style.pyindex 2cbd445365e..04a95b45196 100644--- a/tests/code_coverage_tests/enforce_llms_folder_style.py+++ b/tests/code_coverage_tests/enforce_llms_folder_style.py@@ -22,6 +22,7 @@ SEARCH_PROVIDERS = ["serper","apiserpent","tinyfish",+ "nimble",]ALLOWED_FILES_IN_LLMS_FOLDER = [diff --git a/tests/search_tests/test_nimble_search.py b/tests/search_tests/test_nimble_search.pynew file mode 100644index 00000000000..c83b7236a09--- /dev/null+++ b/tests/search_tests/test_nimble_search.py@@ -0,0 +1,155 @@+"""+Tests for Nimble Search API integration.+"""++import json+import os+import sys+from unittest.mock import AsyncMock, Mock, patch++import pytest++sys.path.insert(0, os.path.abspath("../.."))++import litellm+from tests.search_tests.base_search_unit_tests import BaseSearchTest++MOCK_NIMBLE_RESPONSE = {+ "request_id": "0f8b3a1c-1d2e-4f5a-9b0c-6d7e8f9a0b1c",+ "total_results": 2,+ "results": [+ {+ "title": "Nimble Web API",+ "description": "Short SERP description",+ "url": "https://nimbleway.com/",+ "content": "Full markdown content for the first result",+ "metadata": {"position": 1, "entity_type": "organic", "country": "US", "locale": "en"},+ "additional_data": {"publish_date": "2026-07-15"},+ },+ {+ "title": "Nimble Docs",+ "description": "Only a description here",+ "url": "https://docs.nimbleway.com/",+ "content": "",+ "metadata": {"position": 2, "entity_type": "organic"},+ "additional_data": None,+ },+ ],+ "serp_data": None,+}+++def _mock_response():+ response = Mock()+ response.status_code = 200+ response.headers = {}+ response.content = json.dumps(MOCK_NIMBLE_RESPONSE).encode()+ return response++[email protected](reason="Local only tested search providers")+class TestNimbleSearch(BaseSearchTest):+ """+ E2E tests for Nimble Search functionality that make real API calls.+ Inherits from BaseSearchTest to run standard search tests.+ """++ def get_search_provider(self) -> str:+ return "nimble"+++class TestNimbleSearchTransformation:+ """+ Full-stack tests through `litellm.search` / `litellm.asearch` with the HTTP layer mocked.+ Transformation details are unit-tested in tests/test_litellm/llms/nimble/search/.+ """++ @pytest.fixture(autouse=True)+ def _server_key(self, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("NIMBLE_API_KEY", "test-api-key")+ monkeypatch.delenv("NIMBLE_API_BASE", raising=False)++ def test_nimble_search_request_and_response(self):+ with patch(+ "litellm.llms.custom_httpx.http_handler.HTTPHandler.post",+ return_value=_mock_response(),+ ) as mock_post:+ response = litellm.search(+ query="nimble web scraping",+ search_provider="nimble",+ max_results=2,+ country="us",+ search_domain_filter=["nimbleway.com", "-spam.example"],+ )++ assert mock_post.called+ call_kwargs = mock_post.call_args.kwargs+ assert call_kwargs["url"] == "https://sdk.nimbleway.com/v2/search"+ assert call_kwargs["headers"]["Authorization"] == "Bearer test-api-key"+ assert call_kwargs["headers"]["X-Client-Source"] == "litellm"++ request_body = call_kwargs["json"]+ assert request_body["query"] == "nimble web scraping"+ assert request_body["max_results"] == 2+ assert request_body["country"] == "US"+ assert request_body["include_domains"] == ("nimbleway.com",)+ assert request_body["exclude_domains"] == ("spam.example",)++ assert response.object == "search"+ assert len(response.results) == 2+ assert response.results[0].title == "Nimble Web API"+ assert response.results[0].url == "https://nimbleway.com/"+ assert response.results[0].snippet == "Full markdown content for the first result"+ assert response.results[0].date == "2026-07-15"+ # Second result has no `content`, so the SERP description is the snippet.+ assert response.results[1].snippet == "Only a description here"+ assert response.results[1].date is None++ def test_provider_specific_params_survive_to_the_wire(self):+ """Nimble-native params must not be eaten by `filter_out_litellm_params`."""+ with patch(+ "litellm.llms.custom_httpx.http_handler.HTTPHandler.post",+ return_value=_mock_response(),+ ) as mock_post:+ litellm.search(+ query="test query",+ search_provider="nimble",+ focus="news",+ search_depth="deep",+ time_range="week",+ locale="fr",+ output_format="plain_text",+ max_subagents=5,+ )++ request_body = mock_post.call_args.kwargs["json"]+ assert request_body["focus"] == "news"+ assert request_body["search_depth"] == "deep"+ assert request_body["time_range"] == "week"+ assert request_body["locale"] == "fr"+ assert request_body["output_format"] == "plain_text"+ assert request_body["max_subagents"] == 5++ @pytest.mark.asyncio+ async def test_nimble_asearch(self):+ with patch(+ "litellm.llms.custom_httpx.http_handler.AsyncHTTPHandler.post",+ new=AsyncMock(return_value=_mock_response()),+ ) as mock_post:+ response = await litellm.asearch(+ query="latest ai developments",+ search_provider="nimble",+ focus="news",+ )++ assert mock_post.call_args.kwargs["json"]["focus"] == "news"+ assert len(response.results) == 2++ def test_nimble_search_tracks_cost(self):+ with patch(+ "litellm.llms.custom_httpx.http_handler.HTTPHandler.post",+ return_value=_mock_response(),+ ):+ response = litellm.search(query="pricing check", search_provider="nimble")++ assert response._hidden_params["response_cost"] == pytest.approx(0.005)diff --git a/tests/test_litellm/llms/base_llm/search/test_base_search_transformation.py b/tests/test_litellm/llms/base_llm/search/test_base_search_transformation.pyindex a1353d57038..b93ffdb0b44 100644--- a/tests/test_litellm/llms/base_llm/search/test_base_search_transformation.py+++ b/tests/test_litellm/llms/base_llm/search/test_base_search_transformation.py@@ -27,6 +27,7 @@ from litellm.llms.fastcrw.search.transformation import FastCRWSearchConfigfrom litellm.llms.firecrawl.search.transformation import FirecrawlSearchConfigfrom litellm.llms.google_pse.search.transformation import GooglePSESearchConfigfrom litellm.llms.linkup.search.transformation import LinkupSearchConfig+from litellm.llms.nimble.search.transformation import NimbleSearchConfigfrom litellm.llms.parallel_ai.search.transformation import ParallelAISearchConfigfrom litellm.llms.perplexity.search.transformation import PerplexitySearchConfigfrom litellm.llms.searchapi.search.transformation import SearchAPIConfig@@ -57,6 +58,7 @@ _BASE_ENV_VARS = ("DATAFORSEO_API_BASE","TINYFISH_API_BASE","CRW_API_BASE",+ "NIMBLE_API_BASE",)@@ -96,6 +98,7 @@ PROVIDERS: Tuple[ProviderSpec, ...] = (),(TinyfishSearchConfig, {"TINYFISH_API_KEY": "srv"}, "caller-key", {}),(FastCRWSearchConfig, {"CRW_API_KEY": "srv"}, "caller-key", {}),+ (NimbleSearchConfig, {"NIMBLE_API_KEY": "srv"}, "caller-key", {}),)_IDS = tuple(spec[0].__name__ for spec in PROVIDERS)diff --git a/tests/test_litellm/llms/nimble/search/test_nimble_search_transformation.py b/tests/test_litellm/llms/nimble/search/test_nimble_search_transformation.pynew file mode 100644index 00000000000..d6292c9cf3e--- /dev/null+++ b/tests/test_litellm/llms/nimble/search/test_nimble_search_transformation.py@@ -0,0 +1,251 @@+import json+from unittest.mock import Mock++import pytest++from litellm.llms.nimble.search.transformation import NimbleSearchConfig+++def _config() -> NimbleSearchConfig:+ return NimbleSearchConfig()+++def _resp(payload, status_code: int = 200):+ r = Mock()+ r.status_code = status_code+ r.headers = {}+ r.content = (payload if isinstance(payload, str) else json.dumps(payload)).encode()+ return r+++def _result(**overrides):+ base = {+ "title": "Test Title",+ "description": "Test description",+ "url": "https://example.com",+ "content": "Test content",+ "metadata": {"position": 1, "entity_type": "organic"},+ "additional_data": None,+ }+ return {**base, **overrides}+++def test_ui_friendly_name():+ assert _config().ui_friendly_name() == "Nimble"+++def test_validate_environment_with_explicit_key():+ headers = _config().validate_environment({}, api_key="explicit-key")+ assert headers["Authorization"] == "Bearer explicit-key"+ assert headers["Content-Type"] == "application/json"+ assert headers["X-Client-Source"] == "litellm"+++def test_validate_environment_reads_env_key(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("NIMBLE_API_KEY", "env-key")+ assert _config().validate_environment({})["Authorization"] == "Bearer env-key"+++def test_validate_environment_missing_key_raises(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("NIMBLE_API_KEY", raising=False)+ with pytest.raises(ValueError, match="NIMBLE_API_KEY"):+ _config().validate_environment({})+++def test_validate_environment_does_not_mutate_and_is_idempotent():+ """The http handler re-runs validate_environment after search/main.py already did."""+ config = _config()+ caller_headers = {"X-Custom": "keep-me"}++ once = config.validate_environment(caller_headers, api_key="k")+ twice = config.validate_environment(once, api_key="k")++ assert caller_headers == {"X-Custom": "keep-me"}+ assert once == twice+ assert once["X-Custom"] == "keep-me"+++def test_get_complete_url_default_base(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.delenv("NIMBLE_API_BASE", raising=False)+ assert _config().get_complete_url(None, {}) == "https://sdk.nimbleway.com/v2/search"+++def test_get_complete_url_reads_env_base(monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setenv("NIMBLE_API_BASE", "https://env-base.local/v2")+ assert _config().get_complete_url(None, {}) == "https://env-base.local/v2/search"+++ "api_base",+ [+ "https://self-hosted.local/v2",+ "https://self-hosted.local/v2/",+ "https://self-hosted.local/v2/search",+ "https://self-hosted.local/v2/search/",+ ],+)+def test_get_complete_url_appends_search_exactly_once(api_base: str):+ assert _config().get_complete_url(api_base, {}) == "https://self-hosted.local/v2/search"+++def test_transform_search_request_joins_list_query():+ assert _config().transform_search_request(["foo", "bar"], {})["query"] == "foo bar"+++def test_transform_search_request_max_results_is_not_clamped():+ """Nimble validates 1-100 itself; a clearer error beats silently rewriting the request."""+ assert _config().transform_search_request("q", {"max_results": 500})["max_results"] == 500+++def test_transform_search_request_uppercases_country():+ assert _config().transform_search_request("q", {"country": "us"})["country"] == "US"+++def test_transform_search_request_drops_max_tokens_per_page():+ assert "max_tokens_per_page" not in _config().transform_search_request("q", {"max_tokens_per_page": 1024})+++def test_transform_search_request_splits_domain_filter():+ data = _config().transform_search_request("q", {"search_domain_filter": ["arxiv.org", "-spam.com", "nature.com"]})+ assert data["include_domains"] == ("arxiv.org", "nature.com")+ assert data["exclude_domains"] == ("spam.com",)+++def test_transform_search_request_omits_empty_domain_lists():+ data = _config().transform_search_request("q", {"search_domain_filter": ["arxiv.org"]})+ assert data["include_domains"] == ("arxiv.org",)+ assert "exclude_domains" not in data+++def test_transform_search_request_ignores_non_list_domain_filter():+ assert "include_domains" not in _config().transform_search_request("q", {"search_domain_filter": "arxiv.org"})++[email protected]("native_key", ["include_domains", "exclude_domains"])+def test_transform_search_request_native_domains_win(native_key: str):+ """An explicit provider-native value must not be silently clobbered by the unified param."""+ data = _config().transform_search_request(+ "q",+ {"search_domain_filter": ["derived.com", "-derived-ex.com"], native_key: ["native.com"]},+ )+ assert data[native_key] == ["native.com"]+++def test_transform_search_response_prefers_content():+ resp = _config().transform_search_response(_resp({"results": [_result()]}), logging_obj=Mock())+ assert resp.results[0].snippet == "Test content"+++def test_transform_search_response_falls_back_to_description():+ resp = _config().transform_search_response(_resp({"results": [_result(content="")]}), logging_obj=Mock())+ assert resp.results[0].snippet == "Test description"+++def test_transform_search_response_reads_publish_date():+ resp = _config().transform_search_response(+ _resp({"results": [_result(additional_data={"publish_date": "2026-08-01"})]}),+ logging_obj=Mock(),+ )+ assert resp.results[0].date == "2026-08-01"++[email protected]("additional_data", [{}, "not-a-dict"])+def test_transform_search_response_date_is_none_without_usable_publish_date(additional_data):+ resp = _config().transform_search_response(+ _resp({"results": [_result(additional_data=additional_data)]}), logging_obj=Mock()+ )+ assert resp.results[0].date is None+++def test_transform_search_response_keeps_additional_data():+ """News results often carry only a relative `publish_date_raw`, which is not a date;+ it must still reach the caller rather than being dropped on the floor."""+ resp = _config().transform_search_response(+ _resp({"results": [_result(additional_data={"publish_date_raw": "1 day ago"})]}),+ logging_obj=Mock(),+ )+ assert resp.results[0].date is None+ assert resp.results[0].additional_data == {"publish_date_raw": "1 day ago"}+++def test_transform_search_response_omits_additional_data_when_absent():+ resp = _config().transform_search_response(_resp({"results": [_result()]}), logging_obj=Mock())+ assert not hasattr(resp.results[0], "additional_data")+++def test_transform_search_response_preserves_order():+ resp = _config().transform_search_response(+ _resp({"results": [_result(title=t) for t in ("first", "second", "third")]}),+ logging_obj=Mock(),+ )+ assert [r.title for r in resp.results] == ["first", "second", "third"]+++def test_transform_search_response_degraded_result_does_not_fail_the_call():+ resp = _config().transform_search_response(+ _resp({"results": [{"url": "https://example.com"}, _result()]}), logging_obj=Mock()+ )+ assert len(resp.results) == 2+ assert resp.results[0].title == ""+ assert resp.results[0].snippet == ""+ assert resp.results[1].title == "Test Title"+++def test_transform_search_response_zero_hits():+ """A search with no hits really does come back as `"results": []`."""+ payload = {"request_id": "abc", "total_results": 0, "results": []}+ assert _config().transform_search_response(_resp(payload), logging_obj=Mock()).results == []+++ "body",+ [+ "<html>502 Bad Gateway</html>", # non-JSON body+ '{"results": ["garbage"]}', # right key, wrong element shape+ '{"results": {"unexpected": "shape"}}',+ '{"results": null}', # must not degrade to a successful empty search+ "{}", # ditto for an absent key+ ],+)+def test_transform_search_response_malformed_body_raises_instead_of_reporting_empty(body: str):+ """A body LiteLLM cannot parse must not be reported as a successful zero-result search."""+ with pytest.raises(Exception, match="Nimble Search"):+ _config().transform_search_response(_resp(body, status_code=502), logging_obj=Mock())+++def test_get_error_class_attributes_the_provider():+ error = _config().get_error_class(error_message="quota exceeded", status_code=429, headers={})+ assert error.status_code == 429+ assert "Nimble Search: quota exceeded" in str(error)+ assert "docs.nimbleway.com" in str(error)+++def test_get_error_class_unwraps_nimble_detail_envelope():+ """Verbatim body from a live 422; the raw JSON envelope should not reach the user."""+ error = _config().get_error_class(+ error_message='{"detail":"search_depth=\'fast\' is only supported with focus=\'general\'."}',+ status_code=422,+ headers={},+ )+ assert (+ str(error) == "Nimble Search: search_depth='fast' is only supported with focus='general'. "+ "See https://docs.nimbleway.com/api-reference/search/search for details."+ )+++def test_get_error_class_unwraps_nimble_message_envelope():+ """Verbatim body from a live collection failure, which uses a different envelope."""+ error = _config().get_error_class(+ error_message='{"success":"false","task_id":"4f74af04","message":"can\'t download the query response"}',+ status_code=500,+ headers={},+ )+ assert (+ str(error) == "Nimble Search: can't download the query response. "+ "See https://docs.nimbleway.com/api-reference/search/search for details."+ )++[email protected]("body", ["<html>502 Bad Gateway</html>", '{"detail": null}'])+def test_get_error_class_falls_back_to_the_raw_body(body: str):+ assert f"Nimble Search: {body}." in str(_config().get_error_class(body, status_code=500, headers={}))diff --git a/ui/litellm-dashboard/public/assets/logos/nimble.png b/ui/litellm-dashboard/public/assets/logos/nimble.pngnew file mode 100644index 00000000000..6ad2ff611e7Binary files /dev/null and b/ui/litellm-dashboard/public/assets/logos/nimble.png differdiff --git a/ui/litellm-dashboard/src/app/(dashboard)/search-tools/_components/CreateSearchTools.tsx b/ui/litellm-dashboard/src/app/(dashboard)/search-tools/_components/CreateSearchTools.tsxindex 1eeff00cb1b..6c8cef0b1a1 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/search-tools/_components/CreateSearchTools.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/search-tools/_components/CreateSearchTools.tsx@@ -12,6 +12,7 @@ import { AvailableSearchProvider, SearchTool } from "./types";import dataforseoLogo from "../../../../../public/assets/logos/dataforseo.png";import exaAiLogo from "../../../../../public/assets/logos/exa_ai.png";import googlePseLogo from "../../../../../public/assets/logos/google_pse.png";+import nimbleLogo from "../../../../../public/assets/logos/nimble.png";import parallelAiLogo from "../../../../../public/assets/logos/parallel_ai.png";import perplexityLogo from "../../../../../public/assets/logos/perplexity.png";import tavilyLogo from "../../../../../public/assets/logos/tavily.png";@@ -25,6 +26,7 @@ const searchProviderLogoMap: Record<string, string> = {exa_ai: exaAiLogo.src,google_pse: googlePseLogo.src,dataforseo: dataforseoLogo.src,+ nimble: nimbleLogo.src,};interface SearchProviderLabelProps {