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] Add DataforSEO Search API (#15817)
Ishaan Jaffad62a6d3d1d8
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.mdindex f953763af84..d27875da58f 100644--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@ -457,6 +457,7 @@ router_settings:| DEFAULT_CLIENT_DISCONNECT_CHECK_TIMEOUT_SECONDS | Timeout in seconds for checking client disconnection. Default is 1| DEFAULT_COOLDOWN_TIME_SECONDS | Duration in seconds to cooldown a model after failures. Default is 5| DEFAULT_CRON_JOB_LOCK_TTL_SECONDS | Time-to-live for cron job locks in seconds. Default is 60 (1 minute)+| DEFAULT_DATAFORSEO_LOCATION_CODE | Default location code for DataForSEO search API. Default is 2250 (France)| DEFAULT_FAILURE_THRESHOLD_PERCENT | Threshold percentage of failures to cool down a deployment. Default is 0.5 (50%)| DEFAULT_FLUSH_INTERVAL_SECONDS | Default interval in seconds for flushing operations. Default is 5| DEFAULT_HEALTH_CHECK_INTERVAL | Default interval in seconds for health checks. Default is 300 (5 minutes)diff --git a/docs/my-website/docs/search.md b/docs/my-website/docs/search.mdindex e270df69a3b..0951c946165 100644--- a/docs/my-website/docs/search.md+++ b/docs/my-website/docs/search.md@@ -2,7 +2,7 @@| Feature | Supported ||---------|-----------|-| Supported Providers | `perplexity`, `tavily`, `parallel_ai`, `exa_ai` |+| Supported Providers | `perplexity`, `tavily`, `parallel_ai`, `exa_ai`, `google_pse`, `dataforseo` || Cost Tracking | ❌ || Logging | ✅ || Load Balancing | ❌ |@@ -205,7 +205,7 @@ See the [official Perplexity Search documentation](https://docs.perplexity.ai/ap| Parameter | Type | Required | Description ||-----------|------|----------|-------------|| `query` | string or array | Yes | Search query. Can be a single string or array of strings |-| `search_provider` | string | Yes (SDK) | The search provider to use: `"perplexity"`, `"tavily"`, `"parallel_ai"`, or `"exa_ai"` |+| `search_provider` | string | Yes (SDK) | The search provider to use: `"perplexity"`, `"tavily"`, `"parallel_ai"`, `"exa_ai"`, or `"google_pse"` || `search_tool_name` | string | Yes (Proxy) | Name of the search tool configured in `config.yaml` || `max_results` | integer | No | Maximum number of results to return (1-20). Default: 10 || `search_domain_filter` | array | No | List of domains to filter results (max 20 domains) |@@ -265,6 +265,8 @@ The response follows Perplexity's search format with the following structure:| Tavily | `TAVILY_API_KEY` | `tavily` || Exa AI | `EXA_API_KEY` | `exa_ai` || Parallel AI | `PARALLEL_AI_API_KEY` | `parallel_ai` |+| Google PSE | `GOOGLE_PSE_API_KEY`, `GOOGLE_PSE_ENGINE_ID` | `google_pse` |+| DataForSEO | `DATAFORSEO_LOGIN`, `DATAFORSEO_PASSWORD` | `dataforseo` |### Perplexity AI@@ -494,6 +496,153 @@ curl http://0.0.0.0:4000/v1/search/parallel-search \}'```+### Google Programmable Search Engine (PSE)++**Get API Key:** [Google Cloud Console](https://console.cloud.google.com/apis/credentials)+**Create Search Engine:** [Programmable Search Engine](https://programmablesearchengine.google.com/)++#### Setup++1. Go to [Google Developers Programmable Search Engine](https://programmablesearchengine.google.com/) and log in or create an account+2. Click the **Add** button in the control panel+3. Enter a search engine name and configure properties:+ - Choose which sites to search (entire web or specific sites)+ - Set language and other preferences+ - Verify you're not a robot+4. Click **Create** button+5. Once created, you'll see:+ - **Search engine ID (cx)** - Copy this for `GOOGLE_PSE_ENGINE_ID`+ - Instructions to get your API key+6. Generate API key:+ - Go to [Google Cloud Console - Credentials](https://console.cloud.google.com/apis/credentials)+ - Create a new API key or use existing one+ - Enable **Custom Search API** for your project+ - Copy the API key for `GOOGLE_PSE_API_KEY`++#### LiteLLM Python SDK++```python showLineNumbers title="Google PSE Search"+import os+from litellm import search++os.environ["GOOGLE_PSE_API_KEY"] = "AIza..."+os.environ["GOOGLE_PSE_ENGINE_ID"] = "your-search-engine-id"++response = search(+ query="latest AI developments",+ search_provider="google_pse",+ max_results=10+)+```++#### LiteLLM AI Gateway++**1. Setup config.yaml**++```yaml showLineNumbers title="config.yaml"+model_list:+ - model_name: gpt-4+ litellm_params:+ model: gpt-4+ api_key: os.environ/OPENAI_API_KEY++search_tools:+ - search_tool_name: google-search+ litellm_params:+ search_provider: google_pse+ api_key: os.environ/GOOGLE_PSE_API_KEY+ search_engine_id: os.environ/GOOGLE_PSE_ENGINE_ID+```++**2. Start the proxy**++```bash+litellm --config /path/to/config.yaml++# RUNNING on http://0.0.0.0:4000+```++**3. Test the search endpoint**++```bash showLineNumbers title="Test Request"+curl http://0.0.0.0:4000/v1/search/google-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments",+ "max_results": 10+ }'+```++### DataForSEO++**Get API Access:** [DataForSEO](https://dataforseo.com/)++#### Setup++1. Go to [DataForSEO](https://dataforseo.com/) and create an account+2. Navigate to your account dashboard+3. Generate API credentials:+ - You'll receive a **login** (username)+ - You'll receive a **password**+4. Set up your environment variables:+ - `DATAFORSEO_LOGIN` - Your DataForSEO login/username+ - `DATAFORSEO_PASSWORD` - Your DataForSEO password++#### LiteLLM Python SDK++```python showLineNumbers title="DataForSEO Search"+import os+from litellm import search++os.environ["DATAFORSEO_LOGIN"] = "your-login"+os.environ["DATAFORSEO_PASSWORD"] = "your-password"++response = search(+ query="latest AI developments",+ search_provider="dataforseo",+ max_results=10+)+```++#### LiteLLM AI Gateway++**1. Setup config.yaml**++```yaml showLineNumbers title="config.yaml"+model_list:+ - model_name: gpt-4+ litellm_params:+ model: gpt-4+ api_key: os.environ/OPENAI_API_KEY++search_tools:+ - search_tool_name: dataforseo-search+ litellm_params:+ search_provider: dataforseo+ api_key: "os.environ/DATAFORSEO_LOGIN:os.environ/DATAFORSEO_PASSWORD"+```++**2. Start the proxy**++```bash+litellm --config /path/to/config.yaml++# RUNNING on http://0.0.0.0:4000+```++**3. Test the search endpoint**++```bash showLineNumbers title="Test Request"+curl http://0.0.0.0:4000/v1/search/dataforseo-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments",+ "max_results": 10+ }'+```+## Provider-specific parameters@@ -557,3 +706,48 @@ response = search(max_chars_per_result=500 # Max characters per result)```++#### Google PSE Search++```python showLineNumbers title="Google PSE Search"+import os+from litellm import search++os.environ["GOOGLE_PSE_API_KEY"] = "AIza..."+os.environ["GOOGLE_PSE_ENGINE_ID"] = "your-search-engine-id"++response = search(+ query="latest AI research papers",+ search_provider="google_pse",+ max_results=10,+ search_domain_filter=["arxiv.org"],+ # Google PSE-specific parameters (use actual Google PSE API parameter names)+ dateRestrict="m6", # 'm6' = last 6 months, 'd7' = last 7 days+ lr="lang_en", # Language restriction (e.g., 'lang_en', 'lang_es')+ safe="active", # Search safety level ('active' or 'off')+ exactTerms="machine learning", # Phrase that all documents must contain+ fileType="pdf" # File type to restrict results to+)+```++#### DataForSEO Search++```python showLineNumbers title="DataForSEO Search"+import os+from litellm import search++os.environ["DATAFORSEO_LOGIN"] = "your-login"+os.environ["DATAFORSEO_PASSWORD"] = "your-password"++response = search(+ query="AI developments",+ search_provider="dataforseo",+ max_results=10,+ # DataForSEO-specific parameters+ country="United States", # Country name for location_name+ language_code="en", # Language code+ depth=20, # Number of results (max 700)+ device="desktop", # Device type ('desktop', 'mobile', 'tablet')+ os="windows" # Operating system+)+```diff --git a/litellm/__init__.py b/litellm/__init__.pyindex def05288600..d1ecc3c7678 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -89,7 +89,7 @@ from litellm.types.proxy.management_endpoints.ui_sso import (DefaultTeamSSOParams,LiteLLM_UpperboundKeyGenerateParams,)-from litellm.types.utils import StandardKeyGenerationConfig, LlmProviders+from litellm.types.utils import StandardKeyGenerationConfig, LlmProviders, SearchProvidersfrom litellm.types.utils import PriorityReservationSettingsfrom litellm.integrations.custom_logger import CustomLoggerfrom litellm.litellm_core_utils.logging_callback_manager import LoggingCallbackManagerdiff --git a/litellm/constants.py b/litellm/constants.pyindex c25977e2ee6..8553ca6ced6 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -274,6 +274,11 @@ ANTHROPIC_WEB_SEARCH_TOOL_MAX_USES = {}DEFAULT_IMAGE_ENDPOINT_MODEL = "dall-e-2"+### DATAFORSEO CONSTANTS ###+DEFAULT_DATAFORSEO_LOCATION_CODE = int(+ os.getenv("DEFAULT_DATAFORSEO_LOCATION_CODE", 2250)+) # Default to France (2250) - lower number, commonly used location+LITELLM_CHAT_PROVIDERS = ["openai","openai_like",diff --git a/litellm/llms/base_llm/search/transformation.py b/litellm/llms/base_llm/search/transformation.pyindex 20bfd5d7104..8dd66f43641 100644--- a/litellm/llms/base_llm/search/transformation.py+++ b/litellm/llms/base_llm/search/transformation.py@@ -1,7 +1,7 @@"""Base Search transformation configuration."""-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Unionimport httpxfrom pydantic import PrivateAttr@@ -48,6 +48,16 @@ class BaseSearchConfig:def __init__(self) -> None:pass++ def get_http_method(self) -> Literal["GET", "POST"]:+ """+ Get HTTP method for search requests.+ Override in provider-specific implementations if needed.++ Returns:+ HTTP method ('GET' or 'POST'). Default is 'POST'.+ """+ return "POST"@staticmethoddef get_supported_perplexity_optional_params() -> set:@@ -82,11 +92,26 @@ class BaseSearchConfig:self,api_base: Optional[str],optional_params: dict,+ data: Optional[Union[Dict, List[Dict]]] = None,**kwargs,) -> str:"""Get complete URL for Search endpoint.- Override in provider-specific implementations.++ Args:+ api_base: Base URL for the API+ optional_params: Optional parameters for the request+ data: Transformed request body from transform_search_request().+ Some providers (e.g., Google PSE) use GET requests and need+ the request body to construct query parameters in the URL.+ Can be a dict or list of dicts depending on provider.+ **kwargs: Additional keyword arguments++ Returns:+ Complete URL for the search endpoint++ Note:+ Override in provider-specific implementations."""raise NotImplementedError("get_complete_url must be implemented by provider")@@ -95,7 +120,7 @@ class BaseSearchConfig:query: Union[str, List[str]],optional_params: dict,**kwargs,- ) -> Dict:+ ) -> Union[Dict, List[Dict]]:"""Transform Search request to provider-specific format.Override in provider-specific implementations.diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 9c0f35c7397..f99310bbf0f 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -1593,11 +1593,7 @@ class BaseLLMHTTPHandler:headers=headers or {},)- # Get complete URL- complete_url = provider_config.get_complete_url(- api_base=api_base,- optional_params=optional_params,- )+# Transform the requestdata = provider_config.transform_search_request(@@ -1605,6 +1601,13 @@ class BaseLLMHTTPHandler:optional_params=optional_params,)+ # Get complete URL (pass data for providers that need request body for URL construction)+ complete_url = provider_config.get_complete_url(+ api_base=api_base,+ optional_params=optional_params,+ data=data,+ )+## LOGGINGlogging_obj.pre_call(input=query if isinstance(query, str) else str(query),@@ -1619,14 +1622,25 @@ class BaseLLMHTTPHandler:if client is None or not isinstance(client, HTTPHandler):client = _get_httpx_client()+ # Check HTTP method from provider config+ http_method = provider_config.get_http_method()+try:- # Make the POST request with JSON data- response = client.post(- url=complete_url,- headers=headers,- json=data,- timeout=timeout,- )+ if http_method == "GET":+ # Make GET request (URL already contains query params from get_complete_url)+ # Note: timeout is set on the client itself, not per-request for GET+ response = client.get(+ url=complete_url,+ headers=headers,+ )+ else:+ # Make POST request with JSON data+ response = client.post(+ url=complete_url,+ headers=headers,+ json=data,+ timeout=timeout,+ )except Exception as e:raise self._handle_error(e=e, provider_config=provider_config)@@ -1663,17 +1677,18 @@ class BaseLLMHTTPHandler:headers=headers or {},)- # Get complete URL- complete_url = provider_config.get_complete_url(- api_base=api_base,- optional_params=optional_params,- )-- # Transform the request+ # Transform the request firstdata = provider_config.transform_search_request(query=query,optional_params=optional_params,)++ # Get complete URL (pass data for providers that need request body for URL construction)+ complete_url = provider_config.get_complete_url(+ api_base=api_base,+ optional_params=optional_params,+ data=data,+ )## LOGGINGlogging_obj.pre_call(@@ -1687,20 +1702,33 @@ class BaseLLMHTTPHandler:)if client is None or not isinstance(client, AsyncHTTPHandler):+ # For search providers, use special Search provider type+ from litellm.types.llms.custom_http import httpxSpecialProviderasync_httpx_client = get_async_httpx_client(- llm_provider=litellm.LlmProviders(custom_llm_provider),+ llm_provider=httpxSpecialProvider.Search)else:async_httpx_client = client+ # Check HTTP method from provider config+ http_method = provider_config.get_http_method().upper()+try:- # Make the async POST request with JSON data- response = await async_httpx_client.post(- url=complete_url,- headers=headers,- json=data,- timeout=timeout,- )+ if http_method == "GET":+ # Make async GET request (URL already contains query params from get_complete_url)+ # Note: timeout is set on the client itself, not per-request for GET+ response = await async_httpx_client.get(+ url=complete_url,+ headers=headers,+ )+ else:+ # Make async POST request with JSON data+ response = await async_httpx_client.post(+ url=complete_url,+ headers=headers,+ json=data,+ timeout=timeout,+ )except Exception as e:raise self._handle_error(e=e, provider_config=provider_config)diff --git a/litellm/llms/dataforseo/search/__init__.py b/litellm/llms/dataforseo/search/__init__.pynew file mode 100644index 00000000000..28990c1af3e--- /dev/null+++ b/litellm/llms/dataforseo/search/__init__.py@@ -0,0 +1,11 @@+"""+DataForSEO Search Module++This module provides search functionality using DataForSEO's SERP API.+DataForSEO offers comprehensive search engine data with high accuracy.+"""++from .transformation import DataForSEOSearchConfig++__all__ = ["DataForSEOSearchConfig"]+diff --git a/litellm/llms/dataforseo/search/transformation.py b/litellm/llms/dataforseo/search/transformation.pynew file mode 100644index 00000000000..e245804a00c--- /dev/null+++ b/litellm/llms/dataforseo/search/transformation.py@@ -0,0 +1,205 @@+"""+Calls DataForSEO SERP API to search the web.++DataForSEO API Reference: https://docs.dataforseo.com/v3/serp/google/organic/live/advanced/?bash+"""+from typing import Any, Dict, List, Literal, Optional, Union++import httpx++from litellm.constants import DEFAULT_DATAFORSEO_LOCATION_CODE+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.base_llm.search.transformation import (+ BaseSearchConfig,+ SearchResponse,+ SearchResult,+)+from litellm.secret_managers.main import get_secret_str+++class DataForSEOSearchConfig(BaseSearchConfig):+ """+ Configuration for DataForSEO SERP API search.++ DataForSEO uses HTTP Basic Auth with login:password credentials.+ API endpoint: https://api.dataforseo.com/v3/serp/google/organic/live/advanced+ """++ DATAFORSEO_API_BASE = "https://api.dataforseo.com/v3/serp/google/organic/live/advanced"++ def get_http_method(self) -> Literal["GET", "POST"]:+ """+ DataForSEO uses POST requests with JSON body.+ """+ return "POST"++ def validate_environment(+ self,+ headers: Dict,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ **kwargs,+ ) -> Dict:+ """+ Validate DataForSEO environment and set up authentication.++ DataForSEO uses HTTP Basic Auth with login:password format.+ The credentials should be in DATAFORSEO_LOGIN and DATAFORSEO_PASSWORD env vars,+ or passed as api_key in "login:password" format.+ """+ import base64++ # Get login and password+ login = get_secret_str("DATAFORSEO_LOGIN")+ password = get_secret_str("DATAFORSEO_PASSWORD")++ # If api_key is provided in "login:password" format, use it+ if api_key and ":" in api_key:+ login, password = api_key.split(":", 1)++ if not login:+ raise ValueError("DATAFORSEO_LOGIN is not set. Set `DATAFORSEO_LOGIN` environment variable or pass credentials in api_key parameter.")++ if not password:+ raise ValueError("DATAFORSEO_PASSWORD is not set. Set `DATAFORSEO_PASSWORD` environment variable or pass credentials in api_key parameter.")++ # Create Basic Auth header+ credentials = f"{login}:{password}"+ encoded_credentials = base64.b64encode(credentials.encode()).decode()+ headers["Authorization"] = f"Basic {encoded_credentials}"+ headers["Content-Type"] = "application/json"++ return headers++ def get_complete_url(+ self,+ api_base: Optional[str],+ optional_params: dict,+ data: Optional[Union[Dict, List[Dict]]] = None,+ **kwargs,+ ) -> str:+ """+ Get complete URL for DataForSEO SERP API endpoint.++ DataForSEO uses POST requests, so no query parameters in URL.+ """+ return api_base or get_secret_str("DATAFORSEO_API_BASE") or self.DATAFORSEO_API_BASE++ def transform_search_request(+ self,+ query: Union[str, List[str]],+ optional_params: dict,+ api_key: Optional[str] = None,+ **kwargs,+ ) -> Union[Dict, List[Dict]]:+ """+ Transform Search request to DataForSEO SERP API format.++ Args:+ query: Search query (string or list of strings). DataForSEO supports single string queries.+ optional_params: Optional parameters for the request+ - max_results: Maximum number of search results → maps to `depth` (max 700)+ - country: Country name → maps to `location_name`+ - search_domain_filter: Domain to filter results → maps to `domain`+ - Plus any DataForSEO-specific parameters (location_code, language_code, device, os, etc.)+ api_key: DataForSEO credentials (login:password format)++ Returns:+ List[Dict]: Request body for DataForSEO API (array of task objects as required by API)+ """+ # DataForSEO expects an array of task objects+ task: Dict[str, Any] = {}++ # Convert query to string if it's a list+ if isinstance(query, list):+ query = query[0] if query else ""++ # Required field: keyword+ task["keyword"] = query++ # Map unified parameters to DataForSEO parameters+ if "max_results" in optional_params and optional_params["max_results"]:+ # DataForSEO uses 'depth' for number of results (max 700)+ depth = min(int(optional_params["max_results"]), 700)+ task["depth"] = depth++ if "country" in optional_params and optional_params["country"]:+ # DataForSEO uses location_code (e.g., 2840 for USA)+ # For simplicity, we'll use location_name which accepts country names+ task["location_name"] = optional_params["country"]++ if "search_domain_filter" in optional_params and optional_params["search_domain_filter"]:+ # DataForSEO uses 'domain' parameter to filter by domain+ task["domain"] = optional_params["search_domain_filter"]++ # Add defaults if not specified+ if "language_code" not in task and "language_name" not in task:+ task["language_code"] = "en"++ # DataForSEO requires a location - use default from constants if not specified+ if "location_code" not in task and "location_name" not in task:+ task["location_code"] = DEFAULT_DATAFORSEO_LOCATION_CODE++ # Pass through all other parameters as-is+ for param, value in optional_params.items():+ if param not in self.get_supported_perplexity_optional_params() and param not in task:+ task[param] = value++ # DataForSEO API expects an array of tasks+ return [task]++ def transform_search_response(+ self,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ **kwargs,+ ) -> SearchResponse:+ """+ Transform DataForSEO SERP API response to LiteLLM unified SearchResponse format.++ DataForSEO → LiteLLM mappings:+ - tasks[0].result[*].items[*].title → SearchResult.title+ - tasks[0].result[*].items[*].url → SearchResult.url+ - tasks[0].result[*].items[*].description → SearchResult.snippet+ - No date/last_updated fields in standard response (set to None)++ Args:+ raw_response: Raw httpx response from DataForSEO API+ logging_obj: Logging object for tracking++ Returns:+ SearchResponse with standardized format+ """+ response_json = raw_response.json()++ # Transform results to SearchResult objects+ results = []++ # DataForSEO wraps results in tasks array+ if "tasks" in response_json and len(response_json["tasks"]) > 0:+ task = response_json["tasks"][0]++ # Check if task was successful+ if task.get("status_code") == 20000 and "result" in task:+ # Result is an array, take first element+ if len(task["result"]) > 0:+ result = task["result"][0]++ # Items contain the actual search results+ for item in result.get("items", []):+ # Only process organic search results+ if item.get("type") == "organic":+ search_result = SearchResult(+ title=item.get("title", ""),+ url=item.get("url", ""),+ snippet=item.get("description", ""),+ date=None, # DataForSEO doesn't provide date in standard response+ last_updated=None,+ )+ results.append(search_result)++ return SearchResponse(+ results=results,+ object="search",+ )+diff --git a/litellm/llms/exa_ai/search/transformation.py b/litellm/llms/exa_ai/search/transformation.pyindex 3678d33bed4..e67cfba7cec 100644--- a/litellm/llms/exa_ai/search/transformation.py+++ b/litellm/llms/exa_ai/search/transformation.py@@ -67,6 +67,7 @@ class ExaAISearchConfig(BaseSearchConfig):self,api_base: Optional[str],optional_params: dict,+ data: Optional[dict] = None,**kwargs,) -> str:"""diff --git a/litellm/llms/google_pse/search/__init__.py b/litellm/llms/google_pse/search/__init__.pynew file mode 100644index 00000000000..cda3f360f9d--- /dev/null+++ b/litellm/llms/google_pse/search/__init__.py@@ -0,0 +1,8 @@+"""+Google Programmable Search Engine (PSE) API module.+"""+from litellm.llms.google_pse.search.transformation import GooglePSESearchConfig++__all__ = ["GooglePSESearchConfig"]++diff --git a/litellm/llms/google_pse/search/transformation.py b/litellm/llms/google_pse/search/transformation.pynew file mode 100644index 00000000000..a59274dd375--- /dev/null+++ b/litellm/llms/google_pse/search/transformation.py@@ -0,0 +1,238 @@+"""+Calls Google Programmable Search Engine (PSE) API to search the web.++Google PSE API Reference: https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list+"""+from typing import Dict, List, Literal, Optional, TypedDict, Union++import httpx++from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.base_llm.search.transformation import (+ BaseSearchConfig,+ SearchResponse,+ SearchResult,+)+from litellm.secret_managers.main import get_secret_str+++class _GooglePSESearchRequestRequired(TypedDict):+ """Required fields for Google PSE Search API request."""+ q: str # Required - search query+ cx: str # Required - Programmable Search Engine ID+ key: str # Required - API key+++class GooglePSESearchRequest(_GooglePSESearchRequestRequired, total=False):+ """+ Google Programmable Search Engine API request format.+ Based on: https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list+ """+ num: int # Optional - number of results (1-10), default 10+ start: int # Optional - index of first result (default 1)+ cr: str # Optional - country restrict (e.g., 'countryUS', 'countryGB')+ dateRestrict: str # Optional - restricts results by date (e.g., 'd[number]', 'w[number]', 'm[number]', 'y[number]')+ exactTerms: str # Optional - phrase that all documents must contain+ excludeTerms: str # Optional - word or phrase to exclude+ fileType: str # Optional - file type to restrict results to+ filter: str # Optional - controls duplicate content filtering ('0'=off, '1'=on)+ gl: str # Optional - geolocation of end user (2-letter country code)+ hq: str # Optional - append query terms to query+ imgSize: str # Optional - returns images of specified size+ imgType: str # Optional - returns images of specified type+ linkSite: str # Optional - specifies all search results should contain a link to a URL+ lr: str # Optional - language restrict (e.g., 'lang_en', 'lang_es')+ orTerms: str # Optional - provides additional search terms+ relatedSite: str # Optional - specifies all search results should be pages related to URL+ rights: str # Optional - filters based on licensing+ safe: str # Optional - search safety level ('active', 'off')+ searchType: str # Optional - specifies search type ('image')+ siteSearch: str # Optional - restricts results to URLs from specified site+ siteSearchFilter: str # Optional - controls whether to include or exclude siteSearch ('e'=exclude, 'i'=include)+ sort: str # Optional - sort expression+++class GooglePSESearchConfig(BaseSearchConfig):+ GOOGLE_PSE_API_BASE = "https://www.googleapis.com/customsearch/v1"++ def get_http_method(self) -> Literal["GET", "POST"]:+ """+ Google PSE uses GET requests with query parameters.+ """+ return "GET"++ def validate_environment(+ self,+ headers: Dict,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ **kwargs,+ ) -> Dict:+ """+ Validate environment and return headers.++ Google PSE uses API key as a query parameter, not in headers.+ This method is called but headers are not used for authentication.+ """+ api_key = api_key or get_secret_str("GOOGLE_PSE_API_KEY")+ if not api_key:+ raise ValueError("GOOGLE_PSE_API_KEY is not set. Set `GOOGLE_PSE_API_KEY` environment variable.")++ # Also check for search engine ID+ search_engine_id = kwargs.get("search_engine_id") or get_secret_str("GOOGLE_PSE_ENGINE_ID")+ if not search_engine_id:+ raise ValueError("GOOGLE_PSE_ENGINE_ID is not set. Set `GOOGLE_PSE_ENGINE_ID` environment variable or pass `search_engine_id` parameter.")++ headers["Content-Type"] = "application/json"+ return headers++ def get_complete_url(+ self,+ api_base: Optional[str],+ optional_params: dict,+ data: Optional[dict] = None,+ **kwargs,+ ) -> str:+ """+ Get complete URL for Search endpoint with query parameters.++ Google PSE uses GET requests, so we build the full URL with query params here.+ The transformed request body (data) contains the parameters needed for the URL.+ """+ from urllib.parse import urlencode++ api_base = api_base or get_secret_str("GOOGLE_PSE_API_BASE") or self.GOOGLE_PSE_API_BASE++ # Build query parameters from the transformed request body+ if data and "_google_pse_params" in data:+ params = data["_google_pse_params"]+ query_string = urlencode(params)+ return f"{api_base}?{query_string}"++ return api_base+++ def transform_search_request(+ self,+ query: Union[str, List[str]],+ optional_params: dict,+ api_key: Optional[str] = None,+ search_engine_id: Optional[str] = None,+ **kwargs,+ ) -> Dict:+ """+ Transform Search request to Google PSE API format.++ Transforms Perplexity unified spec parameters:+ - query → q (same)+ - max_results → num+ - search_domain_filter → siteSearch+ - country → gl+ - max_tokens_per_page → (not applicable, ignored)++ All other Google PSE-specific parameters are passed through as-is.++ Args:+ query: Search query (string or list of strings). Google PSE supports single string queries.+ optional_params: Optional parameters for the request+ api_key: Google API key+ search_engine_id: Google Programmable Search Engine ID (cx parameter)++ Returns:+ Dict with typed request data following GooglePSESearchRequest spec+ """+ if isinstance(query, list):+ # Google PSE only supports single string queries+ query = " ".join(query)++ # Get API credentials+ api_key = api_key or get_secret_str("GOOGLE_PSE_API_KEY")+ search_engine_id = search_engine_id or get_secret_str("GOOGLE_PSE_ENGINE_ID")++ if not api_key:+ raise ValueError("GOOGLE_PSE_API_KEY is required")+ if not search_engine_id:+ raise ValueError("GOOGLE_PSE_ENGINE_ID is required")++ request_data: GooglePSESearchRequest = {+ "q": query,+ "cx": search_engine_id,+ "key": api_key,+ }++ # Transform unified spec parameters to Google PSE format+ if "max_results" in optional_params:+ # Google PSE supports 1-10 results per request+ num_results = min(optional_params["max_results"], 10)+ request_data["num"] = num_results++ if "search_domain_filter" in optional_params:+ # Convert list to single domain (take first if multiple)+ domains = optional_params["search_domain_filter"]+ if isinstance(domains, list) and len(domains) > 0:+ request_data["siteSearch"] = domains[0]+ request_data["siteSearchFilter"] = "i" # include+ elif isinstance(domains, str):+ request_data["siteSearch"] = domains+ request_data["siteSearchFilter"] = "i" # include++ if "country" in optional_params:+ # Google PSE uses 2-letter country codes for gl parameter+ request_data["gl"] = optional_params["country"].upper()++ # Convert to dict before dynamic key assignments+ result_data = dict(request_data)++ # Pass through all other parameters as-is+ for param, value in optional_params.items():+ if param not in self.get_supported_perplexity_optional_params() and param not in result_data:+ result_data[param] = value++ # Store params in special key for URL building (Google PSE uses GET not POST)+ # Return a wrapper dict that stores params for get_complete_url to use+ return {+ "_google_pse_params": result_data,+ }++ def transform_search_response(+ self,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ **kwargs,+ ) -> SearchResponse:+ """+ Transform Google PSE API response to LiteLLM unified SearchResponse format.++ Google PSE → LiteLLM mappings:+ - items[].title → SearchResult.title+ - items[].link → SearchResult.url+ - items[].snippet → SearchResult.snippet+ - No date/last_updated fields in Google PSE response (set to None)++ Args:+ raw_response: Raw httpx response from Google PSE API+ logging_obj: Logging object for tracking++ Returns:+ SearchResponse with standardized format+ """+ response_json = raw_response.json()++ # Transform results to SearchResult objects+ results = []+ for item in response_json.get("items", []):+ search_result = SearchResult(+ title=item.get("title", ""),+ url=item.get("link", ""),+ snippet=item.get("snippet", ""),+ date=None, # Google PSE doesn't provide date in standard response+ last_updated=None, # Google PSE doesn't provide last_updated in response+ )+ results.append(search_result)++ return SearchResponse(+ results=results,+ object="search",+ )++diff --git a/litellm/llms/parallel_ai/search/transformation.py b/litellm/llms/parallel_ai/search/transformation.pyindex fa8ac9262c4..83e54f66ed2 100644--- a/litellm/llms/parallel_ai/search/transformation.py+++ b/litellm/llms/parallel_ai/search/transformation.py@@ -67,6 +67,7 @@ class ParallelAISearchConfig(BaseSearchConfig):self,api_base: Optional[str],optional_params: dict,+ data: Optional[Union[Dict, List[Dict]]] = None,**kwargs,) -> str:"""diff --git a/litellm/llms/perplexity/search/transformation.py b/litellm/llms/perplexity/search/transformation.pyindex ef1ab9daad3..2c4ff3f446c 100644--- a/litellm/llms/perplexity/search/transformation.py+++ b/litellm/llms/perplexity/search/transformation.py@@ -54,6 +54,7 @@ class PerplexitySearchConfig(BaseSearchConfig):self,api_base: Optional[str],optional_params: dict,+ data: Optional[Union[Dict, List[Dict]]] = None,**kwargs,) -> str:"""diff --git a/litellm/llms/tavily/search/transformation.py b/litellm/llms/tavily/search/transformation.pyindex dda10679242..ac96964b3b9 100644--- a/litellm/llms/tavily/search/transformation.py+++ b/litellm/llms/tavily/search/transformation.py@@ -66,6 +66,7 @@ class TavilySearchConfig(BaseSearchConfig):self,api_base: Optional[str],optional_params: dict,+ data: Optional[dict] = None,**kwargs,) -> str:"""diff --git a/litellm/search/main.py b/litellm/search/main.pyindex 157bfd241c3..410c3f24f34 100644--- a/litellm/search/main.py+++ b/litellm/search/main.py@@ -14,7 +14,7 @@ from litellm.constants import request_timeoutfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.llms.base_llm.search.transformation import BaseSearchConfig, SearchResponsefrom litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler-from litellm.types.search import SearchProvider+from litellm.types.utils import SearchProvidersfrom litellm.utils import ProviderConfigManager, client####### ENVIRONMENT VARIABLES ###################@@ -57,7 +57,7 @@ def _build_search_optional_params(@clientasync def asearch(query: Union[str, List[str]],- search_provider: SearchProvider,+ search_provider: str,max_results: Optional[int] = None,search_domain_filter: Optional[List[str]] = None,max_tokens_per_page: Optional[int] = None,@@ -161,7 +161,7 @@ async def asearch(@clientdef search(query: Union[str, List[str]],- search_provider: SearchProvider,+ search_provider: str,max_results: Optional[int] = None,search_domain_filter: Optional[List[str]] = None,max_tokens_per_page: Optional[int] = None,@@ -241,7 +241,7 @@ def search(# Get provider configsearch_provider_config: Optional[BaseSearchConfig] = (ProviderConfigManager.get_provider_search_config(- provider=litellm.LlmProviders(search_provider),+ provider=SearchProviders(search_provider),))@@ -262,9 +262,13 @@ def search(country=country,)+ # Internal LiteLLM parameters that should not be passed to providers+ litellm_internal_params = {"litellm_call_id", "litellm_logging_obj", "litellm_params"}+# Add remaining kwargs to optional_params (for provider-specific params)+ # Filter out internal LiteLLM parametersfor key, value in kwargs.items():- if key not in optional_params:+ if key not in optional_params and key not in litellm_internal_params:optional_params[key] = valueverbose_logger.debug(f"Search optional_params: {optional_params}")diff --git a/litellm/types/llms/custom_http.py b/litellm/types/llms/custom_http.pyindex 8759dedec6a..e7d2b9dabcc 100644--- a/litellm/types/llms/custom_http.py+++ b/litellm/types/llms/custom_http.py@@ -20,6 +20,7 @@ class httpxSpecialProvider(str, Enum):PassThroughEndpoint = "pass_through_endpoint"PromptFactory = "prompt_factory"SSO_HANDLER = "sso_handler"+ Search = "search"VerifyTypes = Union[str, bool, ssl.SSLContext]diff --git a/litellm/types/search.py b/litellm/types/search.pyindex 0b54f23e38e..19349893d38 100644--- a/litellm/types/search.py+++ b/litellm/types/search.py@@ -4,15 +4,10 @@ LiteLLM Search API TypesThis module defines types for the unified search API across different providers."""-from typing import Literal+from litellm.types.utils import SearchProviders-# Supported search providers-SearchProvider = Literal[- "perplexity",- "tavily",- "parallel_ai",- "exa_ai",-]+# Re-export SearchProviders as SearchProvider for backwards compatibility+SearchProvider = SearchProviders-__all__ = ["SearchProvider"]+__all__ = ["SearchProvider", "SearchProviders"]diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 45267f8c011..789212347f4 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -2513,9 +2513,6 @@ class LlmProviders(str, Enum):LANGFUSE = "langfuse"HUMANLOOP = "humanloop"TOPAZ = "topaz"- TAVILY = "tavily"- PARALLEL_AI = "parallel_ai"- EXA_AI = "exa_ai"ASSEMBLYAI = "assemblyai"GITHUB_COPILOT = "github_copilot"SNOWFLAKE = "snowflake"@@ -2541,6 +2538,23 @@ class LlmProviders(str, Enum):LlmProvidersSet = {provider.value for provider in LlmProviders}+class SearchProviders(str, Enum):+ """+ Enum for search provider types.+ Separate from LlmProviders for semantic clarity.+ """+ PERPLEXITY = "perplexity"+ TAVILY = "tavily"+ PARALLEL_AI = "parallel_ai"+ EXA_AI = "exa_ai"+ GOOGLE_PSE = "google_pse"+ DATAFORSEO = "dataforseo"+++# Create a set of all search provider values for quick lookup+SearchProvidersSet = {provider.value for provider in SearchProviders}++class LiteLLMLoggingBaseClass:"""Base class for logging pre and post calldiff --git a/litellm/utils.py b/litellm/utils.pyindex 9afddd6bb6d..d21c09c69f5 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -197,6 +197,7 @@ from litellm.types.utils import (ProviderField,ProviderSpecificModelInfo,RawRequestTypedDict,+ SearchProviders,SelectTokenizerResponse,StreamingChoices,TextChoices,@@ -7622,14 +7623,20 @@ class ProviderConfigManager:@staticmethoddef get_provider_search_config(- provider: LlmProviders,+ provider: "SearchProviders",) -> Optional["BaseSearchConfig"]:"""Get Search configuration for a given provider."""+ from litellm.llms.dataforseo.search.transformation import (+ DataForSEOSearchConfig,+ )from litellm.llms.exa_ai.search.transformation import (ExaAISearchConfig,)+ from litellm.llms.google_pse.search.transformation import (+ GooglePSESearchConfig,+ )from litellm.llms.parallel_ai.search.transformation import (ParallelAISearchConfig,)@@ -7641,10 +7648,12 @@ class ProviderConfigManager:)PROVIDER_TO_CONFIG_MAP = {- litellm.LlmProviders.PERPLEXITY: PerplexitySearchConfig,- litellm.LlmProviders.TAVILY: TavilySearchConfig,- litellm.LlmProviders.PARALLEL_AI: ParallelAISearchConfig,- litellm.LlmProviders.EXA_AI: ExaAISearchConfig,+ SearchProviders.PERPLEXITY: PerplexitySearchConfig,+ SearchProviders.TAVILY: TavilySearchConfig,+ SearchProviders.PARALLEL_AI: ParallelAISearchConfig,+ SearchProviders.EXA_AI: ExaAISearchConfig,+ SearchProviders.GOOGLE_PSE: GooglePSESearchConfig,+ SearchProviders.DATAFORSEO: DataForSEOSearchConfig,}config_class = PROVIDER_TO_CONFIG_MAP.get(provider, None)if config_class is None:diff --git a/tests/code_coverage_tests/enforce_llms_folder_style.py b/tests/code_coverage_tests/enforce_llms_folder_style.pyindex 0d3f36f69c6..b8ac177ff6a 100644--- a/tests/code_coverage_tests/enforce_llms_folder_style.py+++ b/tests/code_coverage_tests/enforce_llms_folder_style.py@@ -6,6 +6,14 @@ sys.path.insert(0, os.path.abspath("../.."))import litellm+SEARCH_PROVIDERS = [+ "tavily",+ "dataforseo",+ "google_pse",+ "parallel_ai",+ "exa_ai",+]+ALLOWED_FILES_IN_LLMS_FOLDER = ["__init__","base",@@ -13,7 +21,7 @@ ALLOWED_FILES_IN_LLMS_FOLDER = ["custom_httpx","custom_llm","deprecated_providers",-]+] + SEARCH_PROVIDERSdef get_unique_names_from_llms_dir(base_dir: str):diff --git a/tests/search_tests/test_dataforseo_search.py b/tests/search_tests/test_dataforseo_search.pynew file mode 100644index 00000000000..59955323908--- /dev/null+++ b/tests/search_tests/test_dataforseo_search.py@@ -0,0 +1,26 @@+"""+Unit tests for DataForSEO Search functionality.++These tests verify that the DataForSEO search provider integration works correctly+with LiteLLM's unified search interface.+"""++import sys+import os++# Add the parent directory to the path so we can import litellm+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))++from tests.search_tests.base_search_unit_tests import BaseSearchTest+++class TestDataForSEOSearch(BaseSearchTest):+ """+ Test suite for DataForSEO search provider.+ Inherits all test cases from BaseSearchTest.+ """++ def get_search_provider(self) -> str:+ """Return the search provider name for DataForSEO."""+ return "dataforseo"+diff --git a/tests/search_tests/test_google_pse_search.py b/tests/search_tests/test_google_pse_search.pynew file mode 100644index 00000000000..c8a46798cca--- /dev/null+++ b/tests/search_tests/test_google_pse_search.py@@ -0,0 +1,26 @@+"""+Tests for Google Programmable Search Engine (PSE) API integration.+"""+import os+import sys+import pytest++sys.path.insert(+ 0, os.path.abspath("../..")+)++from tests.search_tests.base_search_unit_tests import BaseSearchTest+++class TestGooglePSESearch(BaseSearchTest):+ """+ Tests for Google PSE Search functionality.+ """++ def get_search_provider(self) -> str:+ """+ Return search_provider for Google PSE Search.+ """+ return "google_pse"++