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 /search endpoint on LiteLLM Gateway (#15780)
Ishaan Jafff5a80110c172
diff --git a/docs/my-website/docs/generateContent.md b/docs/my-website/docs/generateContent.mdindex e6823ebf05d..4453e5ce06d 100644--- a/docs/my-website/docs/generateContent.md+++ b/docs/my-website/docs/generateContent.md@@ -1,7 +1,7 @@import Tabs from '@theme/Tabs';import TabItem from '@theme/TabItem';-# Google AI generateContent+# /generateContentUse LiteLLM to call Google AI's generateContent endpoints for text generation, multimodal interactions, and streaming responses.diff --git a/docs/my-website/docs/search.md b/docs/my-website/docs/search.mdnew file mode 100644index 00000000000..e270df69a3b--- /dev/null+++ b/docs/my-website/docs/search.md@@ -0,0 +1,559 @@+# /search++| Feature | Supported |+|---------|-----------|+| Supported Providers | `perplexity`, `tavily`, `parallel_ai`, `exa_ai` |+| Cost Tracking | ❌ |+| Logging | ✅ |+| Load Balancing | ❌ |++:::tip++LiteLLM follows the [Perplexity API request/response for the Search API](https://docs.perplexity.ai/api-reference/search-post)++:::++:::info++Supported from LiteLLM v1.78.7++:::++## **LiteLLM Python SDK Usage**+### Quick Start++```python showLineNumbers title="Basic Search"+from litellm import search+import os++os.environ["PERPLEXITYAI_API_KEY"] = "pplx-..."++response = search(+ query="latest AI developments in 2024",+ search_provider="perplexity",+ max_results=5+)++# Access search results+for result in response.results:+ print(f"{result.title}: {result.url}")+ print(f"Snippet: {result.snippet}\n")+```++### Async Usage++```python showLineNumbers title="Async Search"+from litellm import asearch+import os, asyncio++os.environ["PERPLEXITYAI_API_KEY"] = "pplx-..."++async def search_async():+ response = await asearch(+ query="machine learning research papers",+ search_provider="perplexity",+ max_results=10,+ search_domain_filter=["arxiv.org", "nature.com"]+ )++ # Access search results+ for result in response.results:+ print(f"{result.title}: {result.url}")+ print(f"Snippet: {result.snippet}")++asyncio.run(search_async())+```++### Optional Parameters++```python showLineNumbers title="Search with Options"+response = search(+ query="AI developments",+ search_provider="perplexity",+ # Unified parameters (work across all providers)+ max_results=10, # Maximum number of results (1-20)+ search_domain_filter=["arxiv.org"], # Filter to specific domains+ country="US", # Country code filter+ max_tokens_per_page=1024 # Max tokens per page+)+```++## **LiteLLM AI Gateway Usage**++LiteLLM provides a Perplexity API compatible `/search` endpoint for search calls.++**Setup**++Add this to your litellm proxy 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: perplexity-search+ litellm_params:+ search_provider: perplexity+ api_key: os.environ/PERPLEXITYAI_API_KEY++ - search_tool_name: tavily-search+ litellm_params:+ search_provider: tavily+ api_key: os.environ/TAVILY_API_KEY+```++Start litellm++```bash+litellm --config /path/to/config.yaml++# RUNNING on http://0.0.0.0:4000+```++### Test Request++**Option 1: Search tool name in URL (Recommended - keeps body Perplexity-compatible)**++```bash showLineNumbers title="cURL Request"+curl http://0.0.0.0:4000/v1/search/perplexity-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments 2024",+ "max_results": 5,+ "search_domain_filter": ["arxiv.org", "nature.com"],+ "country": "US"+ }'+```++**Option 2: Search tool name in body**++```bash showLineNumbers title="cURL Request with search_tool_name in body"+curl http://0.0.0.0:4000/v1/search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "search_tool_name": "perplexity-search",+ "query": "latest AI developments 2024",+ "max_results": 5+ }'+```++### Load Balancing++Configure multiple search providers for automatic load balancing and fallbacks:++```yaml showLineNumbers title="config.yaml with load balancing"+search_tools:+ - search_tool_name: my-search+ litellm_params:+ search_provider: perplexity+ api_key: os.environ/PERPLEXITYAI_API_KEY++ - search_tool_name: my-search+ litellm_params:+ search_provider: tavily+ api_key: os.environ/TAVILY_API_KEY++ - search_tool_name: my-search+ litellm_params:+ search_provider: exa_ai+ api_key: os.environ/EXA_API_KEY++router_settings:+ routing_strategy: simple-shuffle # or 'least-busy', 'latency-based-routing'+```++Test with load balancing:++```bash+curl http://0.0.0.0:4000/v1/search/my-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "AI developments",+ "max_results": 10+ }'+```++## **Request/Response Format**++:::info++LiteLLM follows the **Perplexity Search API specification**.++See the [official Perplexity Search documentation](https://docs.perplexity.ai/api-reference/search-post) for complete details.++:::++### Example Request++```json showLineNumbers title="Search Request"+{+ "query": "latest AI developments 2024",+ "max_results": 10,+ "search_domain_filter": ["arxiv.org", "nature.com"],+ "country": "US",+ "max_tokens_per_page": 1024+}+```++### Request Parameters++| 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_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) |+| `max_tokens_per_page` | integer | No | Maximum tokens per page to process. Default: 1024 |+| `country` | string | No | Country code filter (e.g., `"US"`, `"GB"`, `"DE"`) |++**Query Format Examples:**++```python+# Single query+query = "AI developments"++# Multiple queries+query = ["AI developments", "machine learning trends"]+```++### Response Format++The response follows Perplexity's search format with the following structure:++```json showLineNumbers title="Search Response"+{+ "object": "search",+ "results": [+ {+ "title": "Latest Advances in Artificial Intelligence",+ "url": "https://arxiv.org/paper/example",+ "snippet": "This paper discusses recent developments in AI...",+ "date": "2024-01-15"+ },+ {+ "title": "Machine Learning Breakthroughs",+ "url": "https://nature.com/articles/ml-breakthrough",+ "snippet": "Researchers have achieved new milestones...",+ "date": "2024-01-10"+ }+ ]+}+```++#### Response Fields++| Field | Type | Description |+|-------|------|-------------|+| `object` | string | Always `"search"` for search responses |+| `results` | array | List of search results |+| `results[].title` | string | Title of the search result |+| `results[].url` | string | URL of the search result |+| `results[].snippet` | string | Text snippet from the result |+| `results[].date` | string | Optional publication or last updated date |++## **Supported Providers**++| Provider | Environment Variable | `search_provider` Value |+|----------|---------------------|------------------------|+| Perplexity AI | `PERPLEXITYAI_API_KEY` | `perplexity` |+| Tavily | `TAVILY_API_KEY` | `tavily` |+| Exa AI | `EXA_API_KEY` | `exa_ai` |+| Parallel AI | `PARALLEL_AI_API_KEY` | `parallel_ai` |++### Perplexity AI++**Get API Key:** [https://www.perplexity.ai/settings/api](https://www.perplexity.ai/settings/api)++#### LiteLLM Python SDK++```python showLineNumbers title="Perplexity Search"+import os+from litellm import search++os.environ["PERPLEXITYAI_API_KEY"] = "pplx-..."++response = search(+ query="latest AI developments",+ search_provider="perplexity",+ max_results=5+)+```++#### 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: perplexity-search+ litellm_params:+ search_provider: perplexity+ api_key: os.environ/PERPLEXITYAI_API_KEY+```++**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/perplexity-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments",+ "max_results": 5+ }'+```++### Tavily++**Get API Key:** [https://tavily.com](https://tavily.com)++#### LiteLLM Python SDK++```python showLineNumbers title="Tavily Search"+import os+from litellm import search++os.environ["TAVILY_API_KEY"] = "tvly-..."++response = search(+ query="latest AI developments",+ search_provider="tavily",+ max_results=5+)+```++#### 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: tavily-search+ litellm_params:+ search_provider: tavily+ api_key: os.environ/TAVILY_API_KEY+```++**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/tavily-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments",+ "max_results": 5+ }'+```++### Exa AI++**Get API Key:** [https://exa.ai](https://exa.ai)++#### LiteLLM Python SDK++```python showLineNumbers title="Exa AI Search"+import os+from litellm import search++os.environ["EXA_API_KEY"] = "exa-..."++response = search(+ query="latest AI developments",+ search_provider="exa_ai",+ max_results=5+)+```++#### 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: exa-search+ litellm_params:+ search_provider: exa_ai+ api_key: os.environ/EXA_API_KEY+```++**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/exa-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments",+ "max_results": 5+ }'+```++### Parallel AI++**Get API Key:** [https://www.parallel.ai](https://www.parallel.ai)++#### LiteLLM Python SDK++```python showLineNumbers title="Parallel AI Search"+import os+from litellm import search++os.environ["PARALLEL_AI_API_KEY"] = "..."++response = search(+ query="latest AI developments",+ search_provider="parallel_ai",+ max_results=5+)+```++#### 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: parallel-search+ litellm_params:+ search_provider: parallel_ai+ api_key: os.environ/PARALLEL_AI_API_KEY+```++**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/parallel-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments",+ "max_results": 5+ }'+```++++## Provider-specific parameters++Sending provider-specific parameters is supported for all providers, you just need to pass them in the request body.++#### Tavily Search++```python showLineNumbers title="Tavily Search"+import os+from litellm import search++os.environ["TAVILY_API_KEY"] = "tvly-..."++response = search(+ query="latest tech news",+ search_provider="tavily",+ max_results=5,+ # Tavily-specific parameters+ topic="news", # 'general', 'news', 'finance'+ search_depth="advanced", # 'basic', 'advanced'+ include_answer=True, # Include AI-generated answer+ include_raw_content=True # Include raw HTML content+)+```++#### Exa AI Search++```python showLineNumbers title="Exa AI Search"+import os+from litellm import search++os.environ["EXA_API_KEY"] = "exa-..."++response = search(+ query="AI research papers",+ search_provider="exa_ai",+ max_results=10,+ search_domain_filter=["arxiv.org"],+ # Exa-specific parameters+ type="neural", # 'neural', 'keyword', or 'auto'+ contents={"text": True}, # Request text content+ use_autoprompt=True # Enable Exa's autoprompt+)+```++#### Parallel AI Search++```python showLineNumbers title="Parallel AI Search"+import os+from litellm import search++os.environ["PARALLEL_AI_API_KEY"] = "..."++response = search(+ query="latest developments in quantum computing",+ search_provider="parallel_ai",+ max_results=5,+ # Parallel AI-specific parameters+ processor="pro", # 'base' or 'pro'+ max_chars_per_result=500 # Max characters per result+)+```diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.jsindex 18d53257e4e..83e0b432385 100644--- a/docs/my-website/sidebars.js+++ b/docs/my-website/sidebars.js@@ -308,6 +308,7 @@ const sidebars = {],},"text_completion",+ "bedrock_converse","embedding/supported_embedding",{type: "category",@@ -327,6 +328,7 @@ const sidebars = {},"generateContent","apply_guardrail",+ "bedrock_invoke",{type: "category",label: "/images",@@ -347,9 +349,8 @@ const sidebars = {"mcp_guardrail",]},+ "anthropic_unified","moderation",- "bedrock_invoke",- "bedrock_converse","ocr",{type: "category",@@ -380,7 +381,7 @@ const sidebars = {"realtime","rerank","response_api",- "anthropic_unified",+ "search",{type: "category",label: "/vector_stores",diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex a8376d89440..226395f5115 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -323,6 +323,14 @@ class LiteLLMRoutes(enum.Enum):"/v1/vector_stores","/vector_stores/{vector_store_id}/search","/v1/vector_stores/{vector_store_id}/search",++ # search+ "/search",+ "/v1/search",++ # OCR+ "/ocr",+ "/v1/ocr",]mapped_pass_through_routes = [diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex a256eae0325..8c87622ad6e 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -311,6 +311,7 @@ class ProxyBaseLLMRequestProcessing:"avector_store_search","avector_store_create","aocr",+ "asearch",],version: Optional[str] = None,user_model: Optional[str] = None,@@ -402,6 +403,7 @@ class ProxyBaseLLMRequestProcessing:"avector_store_search","avector_store_create","aocr",+ "asearch",],proxy_logging_obj: ProxyLogging,general_settings: dict,diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 995f3159bf3..e311aac341c 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -1,7 +1,20 @@model_list:- - model_name: openai-gpt-4o-realtime-audio+ - model_name: aws/anthropic/bedrock-claude-3-5-sonnet-v1litellm_params:- model: openai/gpt-4o-realtime-preview-2024-10-01- api_key: os.environ/OPENAI_API_KEY- model_info:- mode: realtime\ No newline at end of file+ model: bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0+ aws_region_name: us-east-1+ custom_llm_provider: bedrock+ - model_name: aws/anthropic/bedrock-claude-3-5-sonnet-v1+ litellm_params:+ model: bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0+ aws_region_name: us-west-2+ custom_llm_provider: bedrock+++# like MCPs/vector stores+search_tools:+ - search_tool_name: litellm-search+ litellm_params:+ search_provider: perplexity+ api_key: os.environ/PERPLEXITYAI_API_KEY+diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 1360433e321..784f69caaa2 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -262,7 +262,9 @@ from litellm.proxy.management_endpoints.customer_endpoints import (from litellm.proxy.management_endpoints.internal_user_endpoints import (router as internal_user_router,)-from litellm.proxy.management_endpoints.internal_user_endpoints import user_update+from litellm.proxy.management_endpoints.internal_user_endpoints import (+ user_update,+)from litellm.proxy.management_endpoints.key_management_endpoints import (delete_verification_tokens,duration_in_seconds,@@ -310,7 +312,9 @@ from litellm.proxy.ocr_endpoints.endpoints import router as ocr_routerfrom litellm.proxy.openai_files_endpoints.files_endpoints import (router as openai_files_router,)-from litellm.proxy.openai_files_endpoints.files_endpoints import set_files_config+from litellm.proxy.openai_files_endpoints.files_endpoints import (+ set_files_config,+)from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import (passthrough_endpoint_router,)@@ -331,6 +335,7 @@ from litellm.proxy.public_endpoints import router as public_endpoints_routerfrom litellm.proxy.rerank_endpoints.endpoints import router as rerank_routerfrom litellm.proxy.response_api_endpoints.endpoints import router as response_routerfrom litellm.proxy.route_llm_request import route_request+from litellm.proxy.search_endpoints.endpoints import router as search_routerfrom litellm.proxy.spend_tracking.cloudzero_endpoints import router as cloudzero_routerfrom litellm.proxy.spend_tracking.spend_management_endpoints import (router as spend_management_router,@@ -394,7 +399,11 @@ from litellm.types.proxy.management_endpoints.ui_sso import (from litellm.types.realtime import RealtimeQueryParamsfrom litellm.types.router import DeploymentTypedDictfrom litellm.types.router import ModelInfo as RouterModelInfo-from litellm.types.router import RouterGeneralSettings, updateDeployment+from litellm.types.router import (+ RouterGeneralSettings,+ SearchToolTypedDict,+ updateDeployment,+)from litellm.types.scheduler import DefaultPrioritiesfrom litellm.types.secret_managers.main import (KeyManagementSettings,@@ -1870,6 +1879,45 @@ class ProxyConfig:credential_list = [CredentialItem(**cred) for cred in credential_list_dict]return credential_list+ def parse_search_tools(self, config: dict) -> Optional[List[SearchToolTypedDict]]:+ """+ Parse and validate search tools from config.+ Loads environment variables and casts to SearchToolTypedDict.++ Args:+ config: Config dictionary containing search_tools++ Returns:+ List of validated SearchToolTypedDict or None if not configured+ """+ search_tools_raw = config.get("search_tools", None)+ if not search_tools_raw:+ return None++ search_tools_parsed: List[SearchToolTypedDict] = []++ print( # noqa+ "\033[32mLiteLLM: Proxy initialized with Search Tools:\033[0m"+ ) # noqa++ for search_tool in search_tools_raw:+ # Display loaded search tool+ search_tool_name = search_tool.get("search_tool_name", "")+ search_provider = search_tool.get("litellm_params", {}).get("search_provider", "")+ print(f"\033[32m {search_tool_name} ({search_provider})\033[0m") # noqa++ # Cast to SearchToolTypedDict for type safety+ try:+ search_tool_typed: SearchToolTypedDict = SearchToolTypedDict(**search_tool) # type: ignore+ search_tools_parsed.append(search_tool_typed)+ except Exception as e:+ verbose_proxy_logger.error(+ f"Error parsing search tool {search_tool_name}: {str(e)}"+ )+ continue++ return search_tools_parsed if search_tools_parsed else None+def _load_environment_variables(self, config: dict):## ENVIRONMENT VARIABLESglobal premium_user@@ -2372,6 +2420,9 @@ class ProxyConfig:assistant_settings["litellm_params"][k] = vassistants_config = AssistantsTypedDict(**assistant_settings) # type: ignore+ ## SEARCH TOOLS SETTINGS+ search_tools: Optional[List[SearchToolTypedDict]] = self.parse_search_tools(config)+## /fine_tuning/jobs endpoints configfinetuning_config = config.get("finetune_settings", None)set_fine_tuning_config(config=finetuning_config)@@ -2391,10 +2442,11 @@ class ProxyConfig:if router_settings and isinstance(router_settings, dict):arg_spec = inspect.getfullargspec(litellm.Router)- # model list already set+ # model list and search_tools already setexclude_args = {"self","model_list",+ "search_tools",}available_args = [x for x in arg_spec.args if x not in exclude_args]@@ -2405,6 +2457,7 @@ class ProxyConfig:router = litellm.Router(**router_params,assistants_config=assistants_config,+ search_tools=search_tools,router_general_settings=RouterGeneralSettings(async_only_mode=True # only init async clients),@@ -9800,6 +9853,7 @@ app.include_router(batches_router)app.include_router(public_endpoints_router)app.include_router(rerank_router)app.include_router(ocr_router)+app.include_router(search_router)app.include_router(image_router)app.include_router(fine_tuning_router)app.include_router(vector_store_router)diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.pyindex f7b4cf0cbe1..3afe564f7a1 100644--- a/litellm/proxy/route_llm_request.py+++ b/litellm/proxy/route_llm_request.py@@ -26,6 +26,7 @@ ROUTE_ENDPOINT_MAPPING = {"aimage_edit": "/images/edits","acancel_responses": "/responses/{response_id}/cancel","aocr": "/ocr",+ "asearch": "/search",}@@ -100,6 +101,7 @@ async def route_request("avector_store_search","avector_store_create","aocr",+ "asearch",],):"""@@ -182,6 +184,7 @@ async def route_request("alist_input_items","avector_store_create","avector_store_search",+ "asearch"]:# moderation endpoint does not require `model` parameterreturn getattr(llm_router, f"{route_type}")(**data)diff --git a/litellm/proxy/search_endpoints/__init__.py b/litellm/proxy/search_endpoints/__init__.pynew file mode 100644index 00000000000..51c8c64dcbe--- /dev/null+++ b/litellm/proxy/search_endpoints/__init__.py@@ -0,0 +1,2 @@+# litellm/proxy/search_endpoints/__init__.py+diff --git a/litellm/proxy/search_endpoints/endpoints.py b/litellm/proxy/search_endpoints/endpoints.pynew file mode 100644index 00000000000..da5388f389d--- /dev/null+++ b/litellm/proxy/search_endpoints/endpoints.py@@ -0,0 +1,162 @@+#### Search Endpoints #####++import orjson+from fastapi import APIRouter, Depends, Request, Response+from fastapi.responses import ORJSONResponse++from litellm.proxy._types import *+from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth, user_api_key_auth+from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing++router = APIRouter()+++ "/v1/search/{search_tool_name}",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["search"],+)+ "/search/{search_tool_name}",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["search"],+)+ "/v1/search",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["search"],+)+ "/search",+ dependencies=[Depends(user_api_key_auth)],+ response_class=ORJSONResponse,+ tags=["search"],+)+async def search(+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth = Depends(user_api_key_auth),+ search_tool_name: Optional[str] = None,+):+ """+ Search endpoint for performing web searches.++ Follows the Perplexity Search API spec:+ https://docs.perplexity.ai/api-reference/search-post++ The search_tool_name can be passed either:+ 1. In the URL path: /v1/search/{search_tool_name}+ 2. In the request body: {"search_tool_name": "..."}++ Example with search_tool_name in URL (recommended - keeps body Perplexity-compatible):+ ```bash+ curl -X POST "http://localhost:4000/v1/search/litellm-search" \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments 2024",+ "max_results": 5,+ "search_domain_filter": ["arxiv.org", "nature.com"],+ "country": "US"+ }'+ ```++ Example with search_tool_name in body:+ ```bash+ curl -X POST "http://localhost:4000/v1/search" \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "search_tool_name": "litellm-search",+ "query": "latest AI developments 2024",+ "max_results": 5,+ "search_domain_filter": ["arxiv.org", "nature.com"],+ "country": "US"+ }'+ ```++ Request Body Parameters (when search_tool_name not in URL):+ - search_tool_name (str, required if not in URL): Name of the search tool configured in router+ - query (str or list[str], required): Search query+ - max_results (int, optional): Maximum number of results (1-20), default 10+ - search_domain_filter (list[str], optional): List of domains to filter (max 20)+ - max_tokens_per_page (int, optional): Max tokens per page, default 1024+ - country (str, optional): Country code filter (e.g., 'US', 'GB', 'DE')++ When using URL path parameter, only Perplexity-compatible parameters are needed in body:+ - query (str or list[str], required): Search query+ - max_results (int, optional): Maximum number of results (1-20), default 10+ - search_domain_filter (list[str], optional): List of domains to filter (max 20)+ - max_tokens_per_page (int, optional): Max tokens per page, default 1024+ - country (str, optional): Country code filter (e.g., 'US', 'GB', 'DE')++ Response follows Perplexity Search API format:+ ```json+ {+ "object": "search",+ "results": [+ {+ "title": "Result title",+ "url": "https://example.com",+ "snippet": "Result snippet...",+ "date": "2024-01-01",+ "last_updated": "2024-01-01"+ }+ ]+ }+ ```+ """+ from litellm.proxy.proxy_server import (+ general_settings,+ llm_router,+ proxy_config,+ proxy_logging_obj,+ select_data_generator,+ user_api_base,+ user_max_tokens,+ user_model,+ user_request_timeout,+ user_temperature,+ version,+ )++ # Read request body+ body = await request.body()+ data = orjson.loads(body)++ # If search_tool_name is provided in URL path, use it (takes precedence over body)+ if search_tool_name is not None:+ data["search_tool_name"] = search_tool_name++ # Process request using ProxyBaseLLMRequestProcessing+ processor = ProxyBaseLLMRequestProcessing(data=data)+ try:+ return await processor.base_process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type="asearch",+ proxy_logging_obj=proxy_logging_obj,+ llm_router=llm_router,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ model=None,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ )+ except Exception as e:+ raise await processor._handle_llm_api_exception(+ e=e,+ user_api_key_dict=user_api_key_dict,+ proxy_logging_obj=proxy_logging_obj,+ version=version,+ )+diff --git a/litellm/router.py b/litellm/router.pyindex 1d768415ff5..18499cd6ac0 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -140,6 +140,7 @@ from litellm.types.router import (RouterRateLimitError,RouterRateLimitErrorBasic,RoutingStrategy,+ SearchToolTypedDict,)from litellm.types.services import ServiceTypesfrom litellm.types.utils import (@@ -204,6 +205,8 @@ class Router:] = None,## ASSISTANTS API ##assistants_config: Optional[AssistantsTypedDict] = None,+ ## SEARCH API ##+ search_tools: Optional[List[SearchToolTypedDict]] = None,## CACHING ##redis_url: Optional[str] = None,redis_host: Optional[str] = None,@@ -363,6 +366,7 @@ class Router:)self.assistants_config = assistants_config+ self.search_tools = search_tools or []self.deployment_names: List = ([]) # names of models under litellm_params. ex. azure/chatgpt-v-2@@ -879,6 +883,13 @@ class Router:self.aocr = self.factory_function(aocr, call_type="aocr")self.ocr = self.factory_function(ocr, call_type="ocr")+ # Search routes+ #########################################################+ from litellm.search import asearch, search++ self.asearch = self.factory_function(asearch, call_type="asearch")+ self.search = self.factory_function(search, call_type="search")+def validate_fallbacks(self, fallback_param: Optional[List]):"""Validate the fallbacks parameter.@@ -2705,6 +2716,37 @@ class Router:self.fail_calls[model] += 1raise e+ async def _asearch_with_fallbacks(+ self, original_function: Callable, **kwargs+ ):+ """+ Helper function to make a search API call through the router with load balancing and fallbacks.+ Reuses the router's retry/fallback infrastructure.+ """+ from litellm.router_utils.search_api_router import SearchAPIRouter++ return await SearchAPIRouter.async_search_with_fallbacks(+ router_instance=self,+ original_function=original_function,+ **kwargs,+ )++ async def _asearch_with_fallbacks_helper(+ self, model: str, original_generic_function: Callable, **kwargs+ ):+ """+ Helper function for search API calls - selects a search tool and calls the original function.+ Called by async_function_with_fallbacks for each retry attempt.+ """+ from litellm.router_utils.search_api_router import SearchAPIRouter++ return await SearchAPIRouter.async_search_with_fallbacks_helper(+ router_instance=self,+ model=model,+ original_generic_function=original_generic_function,+ **kwargs,+ )+async def _ageneric_api_call_with_fallbacks(self, model: str, original_function: Callable, **kwargs):@@ -3580,6 +3622,8 @@ class Router:"vector_store_create","aocr","ocr",+ "asearch",+ "search","aadapter_generate_content"] = "assistants",):@@ -3598,6 +3642,7 @@ class Router:"vector_store_search","vector_store_create","ocr",+ "search",):def sync_wrapper(@@ -3628,6 +3673,11 @@ class Router:return await self._pass_through_moderation_endpoint_factory(original_function=original_function, **kwargs)+ elif call_type in ("asearch", "search"):+ return await self._asearch_with_fallbacks(+ original_function=original_function,+ **kwargs,+ )elif call_type in ("anthropic_messages","aresponses",diff --git a/litellm/router_utils/search_api_router.py b/litellm/router_utils/search_api_router.pynew file mode 100644index 00000000000..fbad1c39122--- /dev/null+++ b/litellm/router_utils/search_api_router.py@@ -0,0 +1,171 @@+"""+Router utilities for Search API integration.++Handles search tool selection, load balancing, and fallback logic for search requests.+"""++import asyncio+import random+import traceback+from functools import partial+from typing import Any, Callable++from litellm._logging import verbose_router_logger+++class SearchAPIRouter:+ """+ Static utility class for routing search API calls through the LiteLLM router.++ Provides methods for search tool selection, load balancing, and fallback handling.+ """++ @staticmethod+ def get_matching_search_tools(+ router_instance: Any,+ search_tool_name: str,+ ) -> list:+ """+ Get all search tools matching the given name.++ Args:+ router_instance: The Router instance+ search_tool_name: Name of the search tool to find++ Returns:+ List of matching search tool configurations++ Raises:+ ValueError: If no matching search tools are found+ """+ matching_tools = [+ tool for tool in router_instance.search_tools+ if tool.get("search_tool_name") == search_tool_name+ ]++ if not matching_tools:+ raise ValueError(f"Search tool '{search_tool_name}' not found in router.search_tools")++ return matching_tools++ @staticmethod+ async def async_search_with_fallbacks(+ router_instance: Any,+ original_function: Callable,+ **kwargs,+ ):+ """+ Helper function to make a search API call through the router with load balancing and fallbacks.+ Reuses the router's retry/fallback infrastructure.++ Args:+ router_instance: The Router instance+ original_function: The original litellm.asearch function+ **kwargs: Search parameters including search_tool_name, query, etc.++ Returns:+ SearchResponse from the search API+ """+ try:+ search_tool_name = kwargs.get("search_tool_name", kwargs.get("model"))++ if not search_tool_name:+ raise ValueError("search_tool_name or model parameter is required for search")++ # Set up kwargs for the fallback system+ kwargs["model"] = search_tool_name # Use model field for compatibility with fallback system+ kwargs["original_generic_function"] = original_function+ # Bind router_instance to the helper method using partial+ kwargs["original_function"] = partial(+ SearchAPIRouter.async_search_with_fallbacks_helper,+ router_instance=router_instance,+ )++ # Update kwargs before fallbacks (for logging, metadata, etc)+ router_instance._update_kwargs_before_fallbacks(+ model=search_tool_name, kwargs=kwargs, metadata_variable_name="litellm_metadata"+ )++ verbose_router_logger.debug(+ f"Inside SearchAPIRouter.async_search_with_fallbacks() - search_tool_name: {search_tool_name}; kwargs: {kwargs}"+ )++ # Use the existing retry/fallback infrastructure+ response = await router_instance.async_function_with_fallbacks(**kwargs)+ return response++ except Exception as e:+ from litellm.router_utils.handle_error import send_llm_exception_alert++ asyncio.create_task(+ send_llm_exception_alert(+ litellm_router_instance=router_instance,+ request_kwargs=kwargs,+ error_traceback_str=traceback.format_exc(),+ original_exception=e,+ )+ )+ raise e++ @staticmethod+ async def async_search_with_fallbacks_helper(+ router_instance: Any,+ model: str,+ original_generic_function: Callable,+ **kwargs,+ ):+ """+ Helper function for search API calls - selects a search tool and calls the original function.+ Called by async_function_with_fallbacks for each retry attempt.++ Args:+ router_instance: The Router instance+ model: The search tool name (passed as model for compatibility)+ original_generic_function: The original litellm.asearch function+ **kwargs: Search parameters++ Returns:+ SearchResponse from the selected search provider+ """+ search_tool_name = model # model field contains the search_tool_name++ try:+ # Find matching search tools+ matching_tools = SearchAPIRouter.get_matching_search_tools(+ router_instance=router_instance,+ search_tool_name=search_tool_name,+ )++ # Simple random selection for load balancing across multiple providers with same name+ # For search tools, we use simple random choice since they don't have TPM/RPM constraints+ selected_tool = random.choice(matching_tools)++ # Extract search provider and other params from litellm_params+ litellm_params = selected_tool.get("litellm_params", {})+ search_provider = litellm_params.get("search_provider")+ api_key = litellm_params.get("api_key")+ api_base = litellm_params.get("api_base")++ if not search_provider:+ raise ValueError(f"search_provider not found in litellm_params for search tool '{search_tool_name}'")++ verbose_router_logger.debug(+ f"Selected search tool with provider: {search_provider}"+ )++ # Call the original search function with the provider config+ response = await original_generic_function(+ search_provider=search_provider,+ api_key=api_key,+ api_base=api_base,+ **kwargs,+ )++ return response++ except Exception as e:+ verbose_router_logger.error(+ f"Error in SearchAPIRouter.async_search_with_fallbacks_helper for {search_tool_name}: {str(e)}"+ )+ raise e+diff --git a/litellm/search/main.py b/litellm/search/main.pyindex e0d5f5841f2..157bfd241c3 100644--- a/litellm/search/main.py+++ b/litellm/search/main.py@@ -14,6 +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 SearchProviderfrom litellm.utils import ProviderConfigManager, client####### ENVIRONMENT VARIABLES ###################@@ -56,7 +57,7 @@ def _build_search_optional_params(@clientasync def asearch(query: Union[str, List[str]],- search_provider: str,+ search_provider: SearchProvider,max_results: Optional[int] = None,search_domain_filter: Optional[List[str]] = None,max_tokens_per_page: Optional[int] = None,@@ -160,7 +161,7 @@ async def asearch(@clientdef search(query: Union[str, List[str]],- search_provider: str,+ search_provider: SearchProvider,max_results: Optional[int] = None,search_domain_filter: Optional[List[str]] = None,max_tokens_per_page: Optional[int] = None,diff --git a/litellm/types/router.py b/litellm/types/router.pyindex 3482df19c37..8790d0d5589 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -17,6 +17,7 @@ from .completion import CompletionRequestfrom .embedding import EmbeddingRequestfrom .llms.openai import OpenAIFileObjectfrom .llms.vertex_ai import VERTEX_CREDENTIALS_TYPES+from .search import SearchProviderfrom .utils import CustomPricingLiteLLMParams, ModelResponse@@ -601,6 +602,35 @@ class AssistantsTypedDict(TypedDict):litellm_params: LiteLLMParamsTypedDict+class SearchToolLiteLLMParams(TypedDict, total=False):+ """+ LiteLLM params for search tools.+ Search tools don't require a 'model' field like regular deployments.+ """+ search_provider: Required[SearchProvider]+ api_key: Optional[str]+ api_base: Optional[str]+ timeout: Optional[Union[float, str, httpx.Timeout]]+ max_retries: Optional[int]+++class SearchToolTypedDict(TypedDict):+ """+ Configuration for a search tool in the router.++ Example:+ {+ "search_tool_name": "litellm-search",+ "litellm_params": {+ "search_provider": "perplexity",+ "api_key": "os.environ/PERPLEXITYAI_API_KEY"+ }+ }+ """+ search_tool_name: Required[str]+ litellm_params: Required[SearchToolLiteLLMParams]++class FineTuningConfig(BaseModel):custom_llm_provider: Literal["azure", "openai"]diff --git a/litellm/types/search.py b/litellm/types/search.pynew file mode 100644index 00000000000..0b54f23e38e--- /dev/null+++ b/litellm/types/search.py@@ -0,0 +1,18 @@+"""+LiteLLM Search API Types++This module defines types for the unified search API across different providers.+"""++from typing import Literal++# Supported search providers+SearchProvider = Literal[+ "perplexity",+ "tavily",+ "parallel_ai",+ "exa_ai",+]++__all__ = ["SearchProvider"]+diff --git a/tests/router_unit_tests/test_router_helper_utils.py b/tests/router_unit_tests/test_router_helper_utils.pyindex c2339d9eec5..fe86d0abe72 100644--- a/tests/router_unit_tests/test_router_helper_utils.py+++ b/tests/router_unit_tests/test_router_helper_utils.py@@ -1753,3 +1753,185 @@ def test_get_metadata_variable_name_from_kwargs(model_list):}result = router._get_metadata_variable_name_from_kwargs(kwargs_other)assert result == "metadata"+++def search_tools():+ """Fixture for search tools configuration"""+ return [+ {+ "search_tool_name": "test-search-tool",+ "litellm_params": {+ "search_provider": "perplexity",+ "api_key": "test-api-key",+ "api_base": "https://api.perplexity.ai",+ }+ },+ {+ "search_tool_name": "test-search-tool",+ "litellm_params": {+ "search_provider": "perplexity",+ "api_key": "test-api-key-2",+ "api_base": "https://api.perplexity.ai",+ }+ }+ ]+++async def test_asearch_with_fallbacks(search_tools):+ """+ Test _asearch_with_fallbacks method of Router.++ Tests that the _asearch_with_fallbacks method correctly:+ - Accepts search parameters+ - Calls async_function_with_fallbacks with correct configuration+ - Returns SearchResponse+ """+ from litellm.llms.base_llm.search.transformation import SearchResponse, SearchResult++ router = Router(search_tools=search_tools)++ # Create a mock search response+ mock_response = SearchResponse(+ object="search",+ results=[+ SearchResult(+ title="Test Result",+ url="https://example.com",+ snippet="Test snippet content"+ )+ ]+ )++ # Mock the async_function_with_fallbacks to return our mock response+ with patch.object(router, 'async_function_with_fallbacks', new_callable=AsyncMock) as mock_fallbacks:+ mock_fallbacks.return_value = mock_response++ # Mock original function+ async def mock_asearch(**kwargs):+ return mock_response++ # Call _asearch_with_fallbacks+ response = await router._asearch_with_fallbacks(+ original_function=mock_asearch,+ search_tool_name="test-search-tool",+ query="test query",+ max_results=5+ )++ # Verify async_function_with_fallbacks was called+ assert mock_fallbacks.called++ # Verify the response+ assert isinstance(response, SearchResponse)+ assert response.object == "search"+ assert len(response.results) == 1+ assert response.results[0].title == "Test Result"+++async def test_asearch_with_fallbacks_helper(search_tools):+ """+ Test _asearch_with_fallbacks_helper method of Router.++ Tests that the _asearch_with_fallbacks_helper method correctly:+ - Selects a search tool from available options+ - Calls the original search function with correct provider parameters+ - Returns SearchResponse+ """+ from litellm.llms.base_llm.search.transformation import SearchResponse, SearchResult++ router = Router(search_tools=search_tools)++ # Create a mock search response+ mock_response = SearchResponse(+ object="search",+ results=[+ SearchResult(+ title="Helper Test Result",+ url="https://example.com/helper",+ snippet="Helper test snippet"+ )+ ]+ )++ # Mock the original generic function+ async def mock_original_function(**kwargs):+ # Verify correct parameters are passed+ assert "search_provider" in kwargs+ assert kwargs["search_provider"] == "perplexity"+ assert "api_key" in kwargs+ assert kwargs["query"] == "helper test query"+ return mock_response++ # Call _asearch_with_fallbacks_helper+ response = await router._asearch_with_fallbacks_helper(+ model="test-search-tool",+ original_generic_function=mock_original_function,+ query="helper test query",+ max_results=3+ )++ # Verify the response+ assert isinstance(response, SearchResponse)+ assert response.object == "search"+ assert len(response.results) == 1+ assert response.results[0].title == "Helper Test Result"+ assert response.results[0].url == "https://example.com/helper"+++async def test_asearch_with_fallbacks_helper_missing_search_tool():+ """+ Test _asearch_with_fallbacks_helper raises error when search tool not found.++ Tests that the helper method raises a ValueError when the requested+ search tool name doesn't exist in the router's search_tools configuration.+ """+ # Create router with no search tools+ router = Router(model_list=[])++ async def mock_original_function(**kwargs):+ return None++ # Should raise ValueError for missing search tool+ with pytest.raises(ValueError, match="Search tool 'nonexistent-tool' not found"):+ await router._asearch_with_fallbacks_helper(+ model="nonexistent-tool",+ original_generic_function=mock_original_function,+ query="test query"+ )+++async def test_asearch_with_fallbacks_helper_missing_search_provider():+ """+ Test _asearch_with_fallbacks_helper raises error when search_provider not configured.++ Tests that the helper method raises a ValueError when a search tool+ is found but doesn't have search_provider in its litellm_params.+ """+ # Create router with misconfigured search tool (missing search_provider)+ search_tools_bad = [+ {+ "search_tool_name": "bad-tool",+ "litellm_params": {+ "api_key": "test-key"+ # Missing search_provider+ }+ }+ ]++ router = Router(search_tools=search_tools_bad)++ async def mock_original_function(**kwargs):+ return None++ # Should raise ValueError for missing search_provider+ with pytest.raises(ValueError, match="search_provider not found in litellm_params"):+ await router._asearch_with_fallbacks_helper(+ model="bad-tool",+ original_generic_function=mock_original_function,+ query="test query"+ )diff --git a/tests/search_tests/test_perplexity_search.py b/tests/search_tests/test_perplexity_search.pyindex 3db2be59e83..0c35dd88baa 100644--- a/tests/search_tests/test_perplexity_search.py+++ b/tests/search_tests/test_perplexity_search.py@@ -23,3 +23,65 @@ class TestPerplexitySearch(BaseSearchTest):"""return "perplexity"++class TestRouterSearch:+ """+ Tests for Router Search functionality.+ """++ @pytest.mark.asyncio+ async def test_router_search_with_search_tools(self):+ """+ Test router's asearch method with search_tools configuration.+ """+ from litellm import Router+ import litellm++ litellm._turn_on_debug()++ # Create router with search_tools config+ router = Router(+ search_tools=[+ {+ "search_tool_name": "litellm-search",+ "litellm_params": {+ "search_provider": "perplexity",+ "api_key": os.environ.get("PERPLEXITYAI_API_KEY"),+ }+ }+ ]+ )++ # Test the search+ response = await router.asearch(+ query="latest AI developments",+ search_tool_name="litellm-search",+ max_results=3+ )++ print(f"\n{'='*80}")+ print(f"Router Search Test Results:")+ print(f"Response type: {type(response)}")+ print(f"Response object: {response.object}")+ print(f"Number of results: {len(response.results)}")++ # Validate response structure+ assert hasattr(response, "results"), "Response should have 'results' attribute"+ assert hasattr(response, "object"), "Response should have 'object' attribute"+ assert response.object == "search", f"Expected object='search', got '{response.object}'"+ assert isinstance(response.results, list), "results should be a list"+ assert len(response.results) > 0, "Should have at least one result"+ assert len(response.results) <= 3, "Should return at most 3 results"++ # Validate first result+ first_result = response.results[0]+ assert hasattr(first_result, "title"), "Result should have 'title' attribute"+ assert hasattr(first_result, "url"), "Result should have 'url' attribute"+ assert hasattr(first_result, "snippet"), "Result should have 'snippet' attribute"++ print(f"First result title: {first_result.title}")+ print(f"First result URL: {first_result.url}")+ print(f"{'='*80}\n")++ print("✅ Router search test passed!")+