litellm/litellm/search/main.py
Mateo Wang d4a791d650
refactor(types): replace Any with proven types in 157 files (#44798)
* refactor(types): replace Any with proven types in 299 files

Clears 871 basedpyright Any errors (reportAny 6,703 to 6,240, reportExplicitAny 1,651 to 1,243) without adding a cast, an ignore or a suppression, and without touching any budget file

Most edits are annotation-only: a parameter, return or local goes from Any to object, Mapping[str, object] or the concrete type the value always held. Fourteen files validate untyped JSON once where it enters, through a module-level pydantic TypeAdapter or model_validate, and then use real types

No HTTP status, error type or response shape changes. Mistral speech and fal.ai Bria image generation now report a pydantic ValidationError instead of an AttributeError when the provider answers 2xx with a body that is not a JSON object

* refactor(types): make the config locals fix effective and trim no-op edits

The Mapping[str, object] annotation on `locals().copy()` removed no error,
because the checker narrows the variable back to the dict[str, Any] the call
returns. 21 provider config constructors now build the same copy with
dict(locals()), which the checker infers as object values under that
annotation, so each file loses one reportAny.

The same annotation is reverted in 31 other config files where it stayed a
no-op, together with the tests that were added only to cover those lines, and
the one MCP server manager line that no CI coverage shard executes is
reverted too. The pull request drops from 345 to 297 changed files.

* refactor(types): accept only int in the proxy state setter

get_proxy_state_variable is annotated to return int, but
set_proxy_state_variable still took Any, so the checker could not hold
callers to the type the getter promises. The setter now takes int, which is
what its only caller already passes.

* refactor(types): index the proxy state key so the getter returns int

* refactor(types): keep public annotations and provider error text unchanged

Restore every public return, public method parameter, public attribute and exported
alias to its annotation on main so code that type-checks against the package keeps
type-checking, and take the Mistral speech and fal.ai Bria changes back out so no
provider error message differs from main

* refactor(types): leave the Vertex RAG chunking read as it is on main

Take the chunking format validation back out of the Vertex RAG ingestion path. It needs the vertexai SDK, a storage bucket and a RAG corpus to execute, so nothing here could run it end to end, and it cleared only two errors

* test(integration): pin the validated provider boundaries on a live proxy

* test(integration): give the held burst a client that outlasts the gate

The fault cell holds a burst at the upstream for up to 60 seconds while it kills a worker, but sent the burst through the shared 15 second client, so a slow box could time the survivors out before the gate opened. The burst now goes through its own client whose timeout is twice the gate, and the gate length is one named constant.

* refactor(types): keep the license reply handling and experimental MCP signatures as they were

The license check validated the whole reply as a mapping, which changed the error text logged for a reply that is not an object. It now validates only the verify value, so every reply is handled and logged exactly as before while the value is still typed.

Three files under the experimental MCP server changed annotations on public functions and methods (three returns and three parameters). They go back to their previous content so no public signature in the diff is narrowed.

* test(integration): answer the proxy's model-list call in the OpenAI stand-ins

Every 300 seconds each proxy worker asks an OpenAI deployment for GET /v1/models. Four new cells own an OpenAI stand-in that accepted only the call under test, so a refresh landing inside a cell failed it. The stand-ins now answer that call through the suite's own helper and the cells count only the provider calls they drive.
2026-10-06 15:31:54 +00:00

320 lines
10 KiB
Python

"""
Main Search function for LiteLLM.
"""
import asyncio
import contextvars
from collections.abc import Coroutine
from functools import partial
from typing import Any, Final
import httpx
import litellm
from litellm._logging import verbose_logger
from litellm.constants import request_timeout
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.base_llm.search.transformation import BaseSearchConfig, SearchResponse
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
from litellm.types.utils import SearchProviders
from litellm.utils import ProviderConfigManager, client, filter_out_litellm_params
####### ENVIRONMENT VARIABLES ###################
base_llm_http_handler = BaseLLMHTTPHandler()
#################################################
def _build_search_optional_params(
max_results: int | None = None,
search_domain_filter: list[str] | None = None,
max_tokens_per_page: int | None = None,
country: str | None = None,
) -> dict[str, object]:
"""
Helper function to build optional_params dict from Perplexity Search API parameters.
Args:
max_results: Maximum number of results (1-20)
search_domain_filter: List of domains to filter (max 20)
max_tokens_per_page: Max tokens per page
country: Country code filter
Returns:
Dict with non-None optional parameters
"""
optional_params: Final[dict[str, object]] = {}
if max_results is not None:
optional_params["max_results"] = max_results
if search_domain_filter is not None:
optional_params["search_domain_filter"] = search_domain_filter
if max_tokens_per_page is not None:
optional_params["max_tokens_per_page"] = max_tokens_per_page
if country is not None:
optional_params["country"] = country
return optional_params
@client
async def asearch(
query: str | list[str],
search_provider: str,
max_results: int | None = None,
search_domain_filter: list[str] | None = None,
max_tokens_per_page: int | None = None,
country: str | None = None,
api_key: str | None = None,
api_base: str | None = None,
timeout: float | httpx.Timeout | None = None,
extra_headers: dict[str, Any] | None = None,
**kwargs,
) -> SearchResponse:
"""
Async Search function.
Args:
query: Search query (string or list of strings)
search_provider: Provider name (e.g., "perplexity")
max_results: Optional maximum number of results (1-20), default 10
search_domain_filter: Optional list of domains to filter (max 20)
max_tokens_per_page: Optional max tokens per page, default 1024
country: Optional country code filter (e.g., 'US', 'GB', 'DE')
api_key: Optional API key
api_base: Optional API base URL
timeout: Optional timeout
extra_headers: Optional extra headers
**kwargs: Additional parameters
Returns:
SearchResponse with results list following Perplexity format
Example:
```python
import litellm
# Basic search
response = await litellm.asearch(
query="latest AI developments 2024",
search_provider="perplexity"
)
# Search with options
response = await litellm.asearch(
query="AI developments",
search_provider="perplexity",
max_results=10,
search_domain_filter=["arxiv.org", "nature.com"],
max_tokens_per_page=1024,
country="US"
)
# Access results
for result in response.results:
print(f"{result.title}: {result.url}")
print(f"Snippet: {result.snippet}")
```
"""
local_vars: Final = locals()
try:
loop: Final = asyncio.get_event_loop()
kwargs["asearch"] = True
func: Final = partial(
search,
query=query,
search_provider=search_provider,
max_results=max_results,
search_domain_filter=search_domain_filter,
max_tokens_per_page=max_tokens_per_page,
country=country,
api_key=api_key,
api_base=api_base,
timeout=timeout,
extra_headers=extra_headers,
**kwargs,
)
ctx: Final = contextvars.copy_context()
func_with_context: Final = partial(ctx.run, func)
init_response: Final = await loop.run_in_executor(None, func_with_context)
if asyncio.iscoroutine(init_response):
response = await init_response
else:
response = init_response
if response is None:
raise ValueError(f"Got an unexpected None response from the Search API: {response}")
return response
except Exception as e:
model_name: Final = f"{search_provider}/search"
raise litellm.exception_type(
model=model_name,
custom_llm_provider=search_provider,
original_exception=e,
completion_kwargs=local_vars,
extra_kwargs=kwargs,
)
@client
def search(
query: str | list[str],
search_provider: str,
max_results: int | None = None,
search_domain_filter: list[str] | None = None,
max_tokens_per_page: int | None = None,
country: str | None = None,
api_key: str | None = None,
api_base: str | None = None,
timeout: float | httpx.Timeout | None = None,
extra_headers: dict[str, Any] | None = None,
**kwargs,
) -> SearchResponse | Coroutine[Any, Any, SearchResponse]:
"""
Synchronous Search function.
Args:
query: Search query (string or list of strings)
search_provider: Provider name (e.g., "perplexity")
max_results: Optional maximum number of results (1-20), default 10
search_domain_filter: Optional list of domains to filter (max 20)
max_tokens_per_page: Optional max tokens per page, default 1024
country: Optional country code filter (e.g., 'US', 'GB', 'DE')
api_key: Optional API key
api_base: Optional API base URL
timeout: Optional timeout
extra_headers: Optional extra headers
**kwargs: Additional parameters
Returns:
SearchResponse with results list following Perplexity format
Example:
```python
import litellm
# Basic search
response = litellm.search(
query="latest AI developments 2024",
search_provider="perplexity"
)
# Search with options
response = litellm.search(
query="AI developments",
search_provider="perplexity",
max_results=10,
search_domain_filter=["arxiv.org", "nature.com"],
max_tokens_per_page=1024,
country="US"
)
# Multi-query search
response = litellm.search(
query=["AI developments", "machine learning trends"],
search_provider="perplexity"
)
# Access results
for result in response.results:
print(f"{result.title}: {result.url}")
print(f"Snippet: {result.snippet}")
if result.date:
print(f"Date: {result.date}")
```
"""
local_vars: Final = locals()
try:
litellm_logging_obj: Final[LiteLLMLoggingObj] = kwargs.pop("litellm_logging_obj")
litellm_call_id: Final[str | None] = kwargs.get("litellm_call_id", None)
_is_async: Final = kwargs.pop("asearch", False) is True
# Validate query parameter
if not isinstance(query, (str, list)):
raise ValueError(f"query must be a string or list of strings, got {type(query)}")
if isinstance(query, list) and not all(isinstance(q, str) for q in query):
raise ValueError("All items in query list must be strings")
# Get provider config
search_provider_config: Final[BaseSearchConfig | None] = ProviderConfigManager.get_provider_search_config(
provider=SearchProviders(search_provider),
)
if search_provider_config is None:
raise ValueError(f"Search is not supported for provider: {search_provider}")
verbose_logger.debug("Search call - provider: %s", search_provider)
# Build optional_params from explicit parameters
optional_params: Final = _build_search_optional_params(
max_results=max_results,
search_domain_filter=search_domain_filter,
max_tokens_per_page=max_tokens_per_page,
country=country,
)
# Filter out internal LiteLLM parameters from kwargs
filtered_kwargs: Final = filter_out_litellm_params(kwargs=kwargs)
# Add remaining kwargs to optional_params (for provider-specific params)
for key, value in filtered_kwargs.items():
if key not in optional_params:
optional_params[key] = value
verbose_logger.debug("Search optional_params: %s", optional_params)
# Validate environment and get headers
headers: Final = search_provider_config.validate_environment(
api_key=api_key,
api_base=api_base,
headers=extra_headers or {},
)
# Get complete URL
complete_url: Final = search_provider_config.get_complete_url(
api_base=api_base,
optional_params=optional_params,
api_key=api_key,
)
# Pre Call logging
model_name = f"{search_provider}/search"
litellm_logging_obj.update_from_kwargs(
kwargs=kwargs,
model=model_name,
optional_params=optional_params,
litellm_params={
"litellm_call_id": litellm_call_id,
"api_base": complete_url,
},
custom_llm_provider=search_provider,
)
# Call the handler
response: Final = base_llm_http_handler.search(
query=query,
optional_params=optional_params,
timeout=timeout or request_timeout,
logging_obj=litellm_logging_obj,
api_key=api_key,
api_base=complete_url,
custom_llm_provider=search_provider,
asearch=_is_async,
headers=headers,
provider_config=search_provider_config,
)
return response
except Exception as e:
model_name = f"{search_provider}/search"
raise litellm.exception_type(
model=model_name,
custom_llm_provider=search_provider,
original_exception=e,
completion_kwargs=local_vars,
extra_kwargs=kwargs,
)