The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat] /search API - add firecrawl search API support (#16257)
Ishaan Jaffaf78a93ecf5c
diff --git a/docs/my-website/docs/search/firecrawl.md b/docs/my-website/docs/search/firecrawl.mdnew file mode 100644index 00000000000..aae097a2d53--- /dev/null+++ b/docs/my-website/docs/search/firecrawl.md@@ -0,0 +1,137 @@+# Firecrawl Search++**Get API Key:** [https://firecrawl.dev](https://firecrawl.dev)++## LiteLLM Python SDK++```python showLineNumbers title="Firecrawl Search"+import os+from litellm import search++os.environ["FIRECRAWL_API_KEY"] = "fc-..."++response = search(+ query="latest AI developments",+ search_provider="firecrawl",+ 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: firecrawl-search+ litellm_params:+ search_provider: firecrawl+ api_key: os.environ/FIRECRAWL_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/firecrawl-search \+ -H "Authorization: Bearer sk-1234" \+ -H "Content-Type: application/json" \+ -d '{+ "query": "latest AI developments",+ "max_results": 5+ }'+```++## Provider-specific Parameters++```python showLineNumbers title="Firecrawl Search with Provider-specific Parameters"+import os+from litellm import search++os.environ["FIRECRAWL_API_KEY"] = "fc-..."++response = search(+ query="machine learning research",+ search_provider="firecrawl",+ max_results=10,+ country="US",+ # Firecrawl-specific parameters+ sources=["web", "news"], # Search multiple sources+ categories=[{"type": "github"}, {"type": "research"}], # Filter by categories+ tbs="qdr:m", # Time-based search (past month)+ location="San Francisco,California,United States", # Geo-targeting+ ignoreInvalidURLs=True, # Exclude invalid URLs+ scrapeOptions={ # Scraping options for results+ "formats": ["markdown"],+ "onlyMainContent": True,+ "removeBase64Images": True+ }+)+```++## Features++Firecrawl combines web search with powerful scraping capabilities:++### Multiple Sources+Search across different sources simultaneously:+- `web` - Web search results (default)+- `images` - Image search results+- `news` - News search results with dates++### Category Filtering+Filter results by specific categories:+- `github` - Search within GitHub repositories, code, issues, and documentation+- `research` - Search academic and research websites (arXiv, Nature, IEEE, PubMed, etc.)+- `pdf` - Search for PDFs++### Time-Based Search+Use the `tbs` parameter to filter by time periods:+- `qdr:h` - Past hour+- `qdr:d` - Past day+- `qdr:w` - Past week+- `qdr:m` - Past month+- `qdr:y` - Past year++### Content Scraping+Firecrawl automatically scrapes full page content for search results when `scrapeOptions` is specified. By default, LiteLLM requests markdown format with main content only.++### Geo-Targeting+Combine `location` and `country` parameters for geo-targeted results:+```python+response = search(+ query="restaurants",+ search_provider="firecrawl",+ country="DE",+ location="Berlin,Germany"+)+```++## Supported Query Operators++Firecrawl supports advanced search operators:++| Operator | Functionality | Example |+| ----------- | --------------------------------------------------------- | ------------------------------- |+| "" | Non-fuzzy matches a string of text | "Firecrawl" |+| \- | Excludes certain keywords | \-bad, \-site:example.com |+| site: | Only returns results from a specified website | site:firecrawl.dev |+| inurl: | Only returns results that include a word in the URL | inurl:firecrawl |+| allinurl: | Only returns results that include multiple words in URL | allinurl:git firecrawl |+| intitle: | Only returns results with a word in the title | intitle:Firecrawl |+| allintitle: | Only returns results with multiple words in the title | allintitle:firecrawl playground |+| related: | Only returns results related to a specific domain | related:firecrawl.dev |+diff --git a/docs/my-website/docs/search/index.md b/docs/my-website/docs/search/index.mdindex 1a54d323e0b..62df4aa9c9d 100644--- a/docs/my-website/docs/search/index.md+++ b/docs/my-website/docs/search/index.md@@ -2,7 +2,7 @@| Feature | Supported ||---------|-----------|-| Supported Providers | `perplexity`, `tavily`, `parallel_ai`, `exa_ai`, `google_pse`, `dataforseo` |+| Supported Providers | `perplexity`, `tavily`, `parallel_ai`, `exa_ai`, `google_pse`, `dataforseo`, `firecrawl` || 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"`, `"exa_ai"`, or `"google_pse"` |+| `search_provider` | string | Yes (SDK) | The search provider to use: `"perplexity"`, `"tavily"`, `"parallel_ai"`, `"exa_ai"`, `"google_pse"`, `"dataforseo"`, or `"firecrawl"` || `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) |@@ -267,6 +267,7 @@ The response follows Perplexity's search format with the following structure:| 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` |+| Firecrawl | `FIRECRAWL_API_KEY` | `firecrawl` |See the individual provider documentation for detailed setup instructions and provider-specific parameters.diff --git a/litellm/llms/firecrawl/__init__.py b/litellm/llms/firecrawl/__init__.pynew file mode 100644index 00000000000..bacf1eac070--- /dev/null+++ b/litellm/llms/firecrawl/__init__.py@@ -0,0 +1,7 @@+"""+Firecrawl API integration module.+"""+from litellm.llms.firecrawl.search.transformation import FirecrawlSearchConfig++__all__ = ["FirecrawlSearchConfig"]+diff --git a/litellm/llms/firecrawl/search/__init__.py b/litellm/llms/firecrawl/search/__init__.pynew file mode 100644index 00000000000..999dce655d5--- /dev/null+++ b/litellm/llms/firecrawl/search/__init__.py@@ -0,0 +1,7 @@+"""+Firecrawl Search API module.+"""+from litellm.llms.firecrawl.search.transformation import FirecrawlSearchConfig++__all__ = ["FirecrawlSearchConfig"]+diff --git a/litellm/llms/firecrawl/search/transformation.py b/litellm/llms/firecrawl/search/transformation.pynew file mode 100644index 00000000000..af501a8eac0--- /dev/null+++ b/litellm/llms/firecrawl/search/transformation.py@@ -0,0 +1,207 @@+"""+Calls Firecrawl's /search endpoint to search the web.++Firecrawl API Reference: https://docs.firecrawl.dev/api-reference/endpoint/search+"""+from typing import Dict, List, 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 _FirecrawlSearchRequestRequired(TypedDict):+ """Required fields for Firecrawl Search API request."""+ query: str # Required - search query+++class FirecrawlSearchRequest(_FirecrawlSearchRequestRequired, total=False):+ """+ Firecrawl Search API request format.+ Based on: https://docs.firecrawl.dev/api-reference/endpoint/search+ """+ limit: int # Optional - maximum number of results to return (default 5, max 100)+ sources: List[str] # Optional - sources to search ('web', 'images', 'news'), default ['web']+ categories: List[Dict[str, str]] # Optional - categories to filter by (github, research, pdf)+ tbs: str # Optional - time-based search parameter+ location: str # Optional - location parameter for geo-targeting+ country: str # Optional - ISO country code (default 'US')+ timeout: int # Optional - timeout in milliseconds (default 60000)+ ignoreInvalidURLs: bool # Optional - exclude invalid URLs (default false)+ scrapeOptions: Dict # Optional - options for scraping search results+++class FirecrawlSearchConfig(BaseSearchConfig):+ FIRECRAWL_API_BASE = "https://api.firecrawl.dev/v2"++ @staticmethod+ def ui_friendly_name() -> str:+ return "Firecrawl"++ def validate_environment(+ self,+ headers: Dict,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ **kwargs,+ ) -> Dict:+ """+ Validate environment and return headers.+ """+ api_key = api_key or get_secret_str("FIRECRAWL_API_KEY")+ if not api_key:+ raise ValueError("FIRECRAWL_API_KEY is not set. Set `FIRECRAWL_API_KEY` environment variable.")+ headers["Authorization"] = f"Bearer {api_key}"+ 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 Search endpoint.+ """+ api_base = api_base or get_secret_str("FIRECRAWL_API_BASE") or self.FIRECRAWL_API_BASE++ # Append "/search" to the api base if it's not already there+ if not api_base.endswith("/search"):+ api_base = f"{api_base}/search"++ return api_base+++ def transform_search_request(+ self,+ query: Union[str, List[str]],+ optional_params: dict,+ **kwargs,+ ) -> Dict:+ """+ Transform Search request to Firecrawl API format.++ Transforms Perplexity unified spec parameters:+ - query → query (same)+ - max_results → limit+ - search_domain_filter → (not directly supported, can use scrapeOptions)+ - country → country+ - max_tokens_per_page → (not applicable, ignored)++ All other Firecrawl-specific parameters are passed through as-is.++ Args:+ query: Search query (string or list of strings). Firecrawl only supports single string queries.+ optional_params: Optional parameters for the request++ Returns:+ Dict with typed request data following FirecrawlSearchRequest spec+ """+ if isinstance(query, list):+ # Firecrawl only supports single string queries, join with spaces+ query = " ".join(query)++ request_data: FirecrawlSearchRequest = {+ "query": query,+ }++ # Transform Perplexity unified spec parameters to Firecrawl format+ if "max_results" in optional_params:+ request_data["limit"] = optional_params["max_results"]++ if "country" in optional_params:+ request_data["country"] = optional_params["country"]++ # 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++ # By default, request markdown content if not explicitly specified+ # Firecrawl doesn't return content unless explicitly requested via scrapeOptions+ if "scrapeOptions" not in result_data:+ result_data["scrapeOptions"] = {+ "formats": ["markdown"],+ "onlyMainContent": True+ }++ return result_data++ def transform_search_response(+ self,+ raw_response: httpx.Response,+ logging_obj: LiteLLMLoggingObj,+ **kwargs,+ ) -> SearchResponse:+ """+ Transform Firecrawl API response to LiteLLM unified SearchResponse format.++ Firecrawl → LiteLLM mappings:+ - data.web[].title → SearchResult.title+ - data.web[].url → SearchResult.url+ - data.web[].description OR data.web[].markdown → SearchResult.snippet+ - No date field in web results (set to None)+ - No last_updated field in Firecrawl response (set to None)++ Note: Firecrawl v2 returns results organized by source type (web, images, news).+ We primarily use web results for the unified format.++ Args:+ raw_response: Raw httpx response from Firecrawl API+ logging_obj: Logging object for tracking++ Returns:+ SearchResponse with standardized format+ """+ response_json = raw_response.json()++ # Transform results to SearchResult objects+ results = []++ # Process web results (primary source)+ data = response_json.get("data", {})+ web_results = data.get("web", [])++ for result in web_results:+ # Use markdown if available, otherwise fall back to description+ snippet = result.get("markdown") or result.get("description", "")++ search_result = SearchResult(+ title=result.get("title", ""),+ url=result.get("url", ""),+ snippet=snippet,+ date=None, # Web results don't include date+ last_updated=None, # Firecrawl doesn't provide last_updated in response+ )+ results.append(search_result)++ # Process news results if available (they have date field)+ news_results = data.get("news", [])+ for result in news_results:+ snippet = result.get("markdown") or result.get("snippet", "")++ search_result = SearchResult(+ title=result.get("title", ""),+ url=result.get("url", ""),+ snippet=snippet,+ date=result.get("date"), # News results include date+ last_updated=None,+ )+ results.append(search_result)++ return SearchResponse(+ results=results,+ object="search",+ )+diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex ce88f616e50..909fd0e77fb 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -7887,6 +7887,85 @@}]},+ "firecrawl/search": {+ "litellm_provider": "firecrawl",+ "mode": "search",+ "tiered_pricing": [+ {+ "input_cost_per_query": 1.66e-03,+ "max_results_range": [+ 1,+ 10+ ]+ },+ {+ "input_cost_per_query": 3.32e-03,+ "max_results_range": [+ 11,+ 20+ ]+ },+ {+ "input_cost_per_query": 4.98e-03,+ "max_results_range": [+ 21,+ 30+ ]+ },+ {+ "input_cost_per_query": 6.64e-03,+ "max_results_range": [+ 31,+ 40+ ]+ },+ {+ "input_cost_per_query": 8.3e-03,+ "max_results_range": [+ 41,+ 50+ ]+ },+ {+ "input_cost_per_query": 9.96e-03,+ "max_results_range": [+ 51,+ 60+ ]+ },+ {+ "input_cost_per_query": 11.62e-03,+ "max_results_range": [+ 61,+ 70+ ]+ },+ {+ "input_cost_per_query": 13.28e-03,+ "max_results_range": [+ 71,+ 80+ ]+ },+ {+ "input_cost_per_query": 14.94e-03,+ "max_results_range": [+ 81,+ 90+ ]+ },+ {+ "input_cost_per_query": 16.6e-03,+ "max_results_range": [+ 91,+ 100+ ]+ }+ ],+ "metadata": {+ "notes": "Firecrawl search pricing: $83 for 100,000 credits, 2 credits per 10 results. Cost = ceiling(limit/10) * 2 * $0.00083"+ }+ },"perplexity/search": {"input_cost_per_query": 5e-03,"litellm_provider": "perplexity",diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex bd5d7a763af..940241a9f4c 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -2594,6 +2594,7 @@ class SearchProviders(str, Enum):EXA_AI = "exa_ai"GOOGLE_PSE = "google_pse"DATAFORSEO = "dataforseo"+ FIRECRAWL = "firecrawl"# Create a set of all search provider values for quick lookupdiff --git a/litellm/utils.py b/litellm/utils.pyindex 6e8d6d10182..608bb36b1cc 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -7727,6 +7727,7 @@ class ProviderConfigManager:"""from litellm.llms.dataforseo.search.transformation import DataForSEOSearchConfigfrom litellm.llms.exa_ai.search.transformation import ExaAISearchConfig+ from litellm.llms.firecrawl.search.transformation import FirecrawlSearchConfigfrom litellm.llms.google_pse.search.transformation import GooglePSESearchConfigfrom litellm.llms.parallel_ai.search.transformation import (ParallelAISearchConfig,@@ -7741,6 +7742,7 @@ class ProviderConfigManager:SearchProviders.EXA_AI: ExaAISearchConfig,SearchProviders.GOOGLE_PSE: GooglePSESearchConfig,SearchProviders.DATAFORSEO: DataForSEOSearchConfig,+ SearchProviders.FIRECRAWL: FirecrawlSearchConfig,}config_class = PROVIDER_TO_CONFIG_MAP.get(provider, None)if config_class is None:diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex ce88f616e50..909fd0e77fb 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -7887,6 +7887,85 @@}]},+ "firecrawl/search": {+ "litellm_provider": "firecrawl",+ "mode": "search",+ "tiered_pricing": [+ {+ "input_cost_per_query": 1.66e-03,+ "max_results_range": [+ 1,+ 10+ ]+ },+ {+ "input_cost_per_query": 3.32e-03,+ "max_results_range": [+ 11,+ 20+ ]+ },+ {+ "input_cost_per_query": 4.98e-03,+ "max_results_range": [+ 21,+ 30+ ]+ },+ {+ "input_cost_per_query": 6.64e-03,+ "max_results_range": [+ 31,+ 40+ ]+ },+ {+ "input_cost_per_query": 8.3e-03,+ "max_results_range": [+ 41,+ 50+ ]+ },+ {+ "input_cost_per_query": 9.96e-03,+ "max_results_range": [+ 51,+ 60+ ]+ },+ {+ "input_cost_per_query": 11.62e-03,+ "max_results_range": [+ 61,+ 70+ ]+ },+ {+ "input_cost_per_query": 13.28e-03,+ "max_results_range": [+ 71,+ 80+ ]+ },+ {+ "input_cost_per_query": 14.94e-03,+ "max_results_range": [+ 81,+ 90+ ]+ },+ {+ "input_cost_per_query": 16.6e-03,+ "max_results_range": [+ 91,+ 100+ ]+ }+ ],+ "metadata": {+ "notes": "Firecrawl search pricing: $83 for 100,000 credits, 2 credits per 10 results. Cost = ceiling(limit/10) * 2 * $0.00083"+ }+ },"perplexity/search": {"input_cost_per_query": 5e-03,"litellm_provider": "perplexity",diff --git a/provider_endpoints_support.json b/provider_endpoints_support.jsonindex e1aaa2d2ece..fdc18d50ba6 100644--- a/provider_endpoints_support.json+++ b/provider_endpoints_support.json@@ -15,7 +15,8 @@"moderations": "Supports /moderations endpoint","batches": "Supports /batches endpoint","rerank": "Supports /rerank endpoint",- "ocr": "Supports /ocr endpoint"+ "ocr": "Supports /ocr endpoint",+ "search": "Supports /search endpoint"}}},@@ -454,6 +455,23 @@"rerank": false}},+ "dataforseo": {+ "display_name": "DataForSEO (`dataforseo`)",+ "url": "https://docs.litellm.ai/docs/search/dataforseo",+ "endpoints": {+ "chat_completions": false,+ "messages": false,+ "responses": false,+ "embeddings": false,+ "image_generations": false,+ "audio_transcriptions": false,+ "audio_speech": false,+ "moderations": false,+ "batches": false,+ "rerank": false,+ "search": true+ }+ },"datarobot": {"display_name": "DataRobot (`datarobot`)","url": "https://docs.litellm.ai/docs/providers/datarobot",@@ -534,6 +552,23 @@"rerank": false}},+ "exa_ai": {+ "display_name": "Exa AI (`exa_ai`)",+ "url": "https://docs.litellm.ai/docs/search/exa_ai",+ "endpoints": {+ "chat_completions": false,+ "messages": false,+ "responses": false,+ "embeddings": false,+ "image_generations": false,+ "audio_transcriptions": false,+ "audio_speech": false,+ "moderations": false,+ "batches": false,+ "rerank": false,+ "search": true+ }+ },"empower": {"display_name": "Empower (`empower`)","url": "https://docs.litellm.ai/docs/providers/empower",@@ -598,6 +633,23 @@"rerank": false}},+ "firecrawl": {+ "display_name": "Firecrawl (`firecrawl`)",+ "url": "https://docs.litellm.ai/docs/search/firecrawl",+ "endpoints": {+ "chat_completions": false,+ "messages": false,+ "responses": false,+ "embeddings": false,+ "image_generations": false,+ "audio_transcriptions": false,+ "audio_speech": false,+ "moderations": false,+ "batches": false,+ "rerank": false,+ "search": true+ }+ },"friendliai": {"display_name": "FriendliAI (`friendliai`)","url": "https://docs.litellm.ai/docs/providers/friendliai",@@ -1208,6 +1260,23 @@"rerank": false}},+ "parallel_ai": {+ "display_name": "Parallel AI (`parallel_ai`)",+ "url": "https://docs.litellm.ai/docs/search/parallel_ai",+ "endpoints": {+ "chat_completions": false,+ "messages": false,+ "responses": false,+ "embeddings": false,+ "image_generations": false,+ "audio_transcriptions": false,+ "audio_speech": false,+ "moderations": false,+ "batches": false,+ "rerank": false,+ "search": true+ }+ },"perplexity": {"display_name": "Perplexity AI (`perplexity`)","url": "https://docs.litellm.ai/docs/providers/perplexity",@@ -1221,7 +1290,8 @@"audio_speech": false,"moderations": false,"batches": false,- "rerank": false+ "rerank": false,+ "search": true}},"petals": {@@ -1400,6 +1470,23 @@"rerank": false}},+ "tavily": {+ "display_name": "Tavily (`tavily`)",+ "url": "https://docs.litellm.ai/docs/search/tavily",+ "endpoints": {+ "chat_completions": false,+ "messages": false,+ "responses": false,+ "embeddings": false,+ "image_generations": false,+ "audio_transcriptions": false,+ "audio_speech": false,+ "moderations": false,+ "batches": false,+ "rerank": false,+ "search": true+ }+ },"triton": {"display_name": "Triton (`triton`)","url": "https://docs.litellm.ai/docs/providers/triton-inference-server",diff --git a/tests/search_tests/test_firecrawl_search.py b/tests/search_tests/test_firecrawl_search.pynew file mode 100644index 00000000000..580f8e01569--- /dev/null+++ b/tests/search_tests/test_firecrawl_search.py@@ -0,0 +1,18 @@+import pytest+import litellm+from typing import List, Union++from tests.search_tests.base_search_unit_tests import BaseSearchTest+++class TestFirecrawlSearch(BaseSearchTest):+ """+ Tests for Firecrawl Search functionality.+ """++ def get_search_provider(self) -> str:+ """+ Return search_provider for Firecrawl Search.+ """+ return "firecrawl"+