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
Add duckcukgo in model map
Sameer Kankute0ea8249e96a4
diff --git a/litellm/llms/duckduckgo/search/transformation.py b/litellm/llms/duckduckgo/search/transformation.pyindex 39c0a64e8f9..509d69041fb 100644--- a/litellm/llms/duckduckgo/search/transformation.py+++ b/litellm/llms/duckduckgo/search/transformation.py@@ -4,6 +4,7 @@ Calls DuckDuckGo's Instant Answer API to search the web.DuckDuckGo API Reference: https://duckduckgo.com/api"""from typing import Dict, List, Literal, Optional, TypedDict, Union+from urllib.parse import urlencodeimport httpx@@ -78,21 +79,11 @@ class DuckDuckGoSearchConfig(BaseSearchConfig):"""api_base = api_base or get_secret_str("DUCKDUCKGO_API_BASE") or self.DUCKDUCKGO_API_BASE- # Ensure URL ends without trailing slash for query parameters- if api_base.endswith("/"):- api_base = api_base.rstrip("/")-- # Construct URL with query parameters- if data and isinstance(data, dict):- query_params = []- for key, value in data.items():- if isinstance(value, list):- # Join list values with commas- value = ",".join(str(v) for v in value)- query_params.append(f"{key}={value}")-- if query_params:- api_base = f"{api_base}/?{'&'.join(query_params)}"+ # Build query parameters from the transformed request body+ if data and isinstance(data, dict) and "_duckduckgo_params" in data:+ params = data["_duckduckgo_params"]+ query_string = urlencode(params, doseq=True)+ return f"{api_base}/?{query_string}"return api_base@@ -128,14 +119,11 @@ class DuckDuckGoSearchConfig(BaseSearchConfig):"format": "json", # Always use JSON format}- # Store max_results for response filtering if provided- if "max_results" in optional_params:- # DuckDuckGo API doesn't support max_results directly- # We'll filter the results in transform_search_response- pass-# Convert to dict before dynamic key assignmentsresult_data = dict(request_data)++ if "max_results" in optional_params:+ result_data["_max_results"] = optional_params["max_results"]# Pass through DuckDuckGo-specific parametersddg_params = ["pretty", "no_redirect", "no_html", "skip_disambig"]@@ -143,7 +131,9 @@ class DuckDuckGoSearchConfig(BaseSearchConfig):if param in optional_params:result_data[param] = optional_params[param]- return result_data+ return {+ "_duckduckgo_params": result_data,+ }def transform_search_response(self,@@ -169,6 +159,15 @@ class DuckDuckGoSearchConfig(BaseSearchConfig):"""response_json = raw_response.json()+ # Extract max_results from the request URL params+ query_params = raw_response.request.url.params if raw_response.request else {}+ max_results = None+ if "_max_results" in query_params:+ try:+ max_results = int(query_params["_max_results"])+ except (ValueError, TypeError):+ pass+# Transform results to SearchResult objectsresults = []@@ -189,12 +188,13 @@ class DuckDuckGoSearchConfig(BaseSearchConfig):# Process RelatedTopicsrelated_topics = response_json.get("RelatedTopics", [])for topic in related_topics:- # RelatedTopics can contain nested topics or direct results+ # Stop if we've reached max_results+ if max_results is not None and len(results) >= max_results:+ break+if isinstance(topic, dict):# Check if it's a direct resultif "FirstURL" in topic and "Text" in topic:- # Extract title and snippet from Text- # Text format is usually "Title - Snippet"text = topic.get("Text", "")url = topic.get("FirstURL", "")@@ -220,6 +220,10 @@ class DuckDuckGoSearchConfig(BaseSearchConfig):elif "Topics" in topic:nested_topics = topic.get("Topics", [])for nested_topic in nested_topics:+ # Stop if we've reached max_results+ if max_results is not None and len(results) >= max_results:+ break+if "FirstURL" in nested_topic and "Text" in nested_topic:text = nested_topic.get("Text", "")url = nested_topic.get("FirstURL", "")@@ -242,11 +246,6 @@ class DuckDuckGoSearchConfig(BaseSearchConfig):)results.append(search_result)- # Apply max_results filtering if provided in kwargs- max_results = kwargs.get("max_results")- if max_results is not None and isinstance(max_results, int):- results = results[:max_results]-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 9a9acb91986..04183e398eb 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -37270,5 +37270,13 @@"search_context_size_low": 0.01,"search_context_size_medium": 0.01}+ },+ "duckduckgo/search": {+ "litellm_provider": "duckduckgo",+ "mode": "search",+ "input_cost_per_query": 0.0,+ "metadata": {+ "notes": "DuckDuckGo Instant Answer API is free and does not require an API key."+ }}}\ No newline at end of filediff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 9a9acb91986..04183e398eb 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -37270,5 +37270,13 @@"search_context_size_low": 0.01,"search_context_size_medium": 0.01}+ },+ "duckduckgo/search": {+ "litellm_provider": "duckduckgo",+ "mode": "search",+ "input_cost_per_query": 0.0,+ "metadata": {+ "notes": "DuckDuckGo Instant Answer API is free and does not require an API key."+ }}}\ No newline at end of filediff --git a/proxy_server_config.yaml b/proxy_server_config.yamlindex 8ed728c5b28..234f2cd87c5 100644--- a/proxy_server_config.yaml+++ b/proxy_server_config.yaml@@ -1,231 +1,25 @@model_list:- - model_name: gpt-3.5-turbo-end-user-test+ - model_name: sonnet-4.6litellm_params:- model: gpt-3.5-turbo- region_name: "eu"- model_info:- id: "1"- - model_name: gpt-3.5-turbo-end-user-test- litellm_params:- model: openai/gpt-4.1-mini- api_key: os.environ/OPENAI_API_KEY # The `os.environ/` prefix tells litellm to read this from the env. See https://docs.litellm.ai/docs/simple_proxy#load-api-keys-from-vault- - model_name: gpt-3.5-turbo- litellm_params:- model: openai/gpt-4.1-mini- api_key: os.environ/OPENAI_API_KEY # The `os.environ/` prefix tells litellm to read this from the env. See https://docs.litellm.ai/docs/simple_proxy#load-api-keys-from-vault- - model_name: gpt-3.5-turbo-large- litellm_params:- model: "gpt-3.5-turbo-1106"- api_key: os.environ/OPENAI_API_KEY- rpm: 480- timeout: 300- stream_timeout: 60- - model_name: gpt-4- litellm_params:- model: openai/gpt-4.1-mini- api_key: os.environ/OPENAI_API_KEY # The `os.environ/` prefix tells litellm to read this from the env. See https://docs.litellm.ai/docs/simple_proxy#load-api-keys-from-vault- rpm: 480- timeout: 300- stream_timeout: 60- - model_name: sagemaker-completion-model- litellm_params:- model: sagemaker/berri-benchmarking-Llama-2-70b-chat-hf-4- input_cost_per_second: 0.000420- - model_name: text-embedding-ada-002- litellm_params:- model: openai/text-embedding-ada-002- api_key: os.environ/OPENAI_API_KEY- model_info:- mode: embedding- base_model: text-embedding-ada-002- - model_name: dall-e-2 # some tests use dall-e-2 which is now deprecated, alias to dall-e-3- litellm_params:- model: openai/dall-e-3- - model_name: openai-dall-e-3- litellm_params:- model: dall-e-3- - model_name: fake-openai-endpoint- litellm_params:- model: openai/gpt-3.5-turbo-0301- api_key: fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/- - model_name: fake-openai-endpoint-2- litellm_params:- model: openai/my-fake-model- api_key: my-fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/- stream_timeout: 0.001- rpm: 1- - model_name: fake-openai-endpoint-3- litellm_params:- model: openai/my-fake-model- api_key: my-fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/- stream_timeout: 0.001- rpm: 1000- - model_name: fake-openai-endpoint-4- litellm_params:- model: openai/my-fake-model- api_key: my-fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/- num_retries: 50- - model_name: fake-openai-endpoint-3- litellm_params:- model: openai/my-fake-model-2- api_key: my-fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/- stream_timeout: 0.001- rpm: 1000- - model_name: bad-model- litellm_params:- model: openai/bad-model- api_key: os.environ/OPENAI_API_KEY- api_base: https://exampleopenaiendpoint-production.up.railway.app/- mock_timeout: True- timeout: 60- rpm: 1000- model_info:- health_check_timeout: 1- - model_name: good-model- litellm_params:- model: openai/bad-model- api_key: os.environ/OPENAI_API_KEY- api_base: https://exampleopenaiendpoint-production.up.railway.app/- rpm: 1000- model_info:- health_check_timeout: 1- - model_name: "*"- litellm_params:- model: openai/*- api_key: os.environ/OPENAI_API_KEY- - model_name: realtime-v1- litellm_params:- model: azure/gpt-realtime-20250828-standard- api_version: "2025-08-28"- realtime_protocol: GA # Possible values: "GA"/ "v1", "beta"-- - model_name: realtime-beta- litellm_params:- model: azure/gpt-realtime-20250828-standard- api_version: 2025-04-01-preview--- # provider specific wildcard routing- - model_name: "anthropic/*"- litellm_params:- model: "anthropic/*"+ model: anthropic/claude-sonnet-4-6api_key: os.environ/ANTHROPIC_API_KEY- - model_name: "bedrock/*"- litellm_params:- model: "bedrock/*"- - model_name: "groq/*"- litellm_params:- model: "groq/*"- api_key: os.environ/GROQ_API_KEY- - model_name: mistral-embed- litellm_params:- model: mistral/mistral-embed- - model_name: gpt-instruct # [PROD TEST] - tests if `/health` automatically infers this to be a text completion model- litellm_params:- model: text-completion-openai/gpt-3.5-turbo-instruct- - model_name: fake-openai-endpoint-5- litellm_params:- model: openai/my-fake-model- api_key: my-fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.app/- timeout: 1- - model_name: badly-configured-openai-endpoint- litellm_params:- model: openai/my-fake-model- api_key: my-fake-key- api_base: https://exampleopenaiendpoint-production.up.railway.appxxxx/- - model_name: gemini-1.5-flash- litellm_params:- model: gemini/gemini-1.5-flash- api_key: os.environ/GOOGLE_API_KEY- - model_name: gpt-4o- litellm_params:- model: gpt-4o- api_key: os.environ/OPENAI_API_KEY---litellm_settings:- # set_verbose: True # Uncomment this if you want to see verbose logs; not recommended in production- drop_params: True- success_callback: ["prometheus"]- # max_budget: 100- # budget_duration: 30d- num_retries: 5- request_timeout: 600- telemetry: False- context_window_fallbacks: [{"gpt-3.5-turbo": ["gpt-3.5-turbo-large"]}]- default_team_settings:- - team_id: team-1- success_callback: ["langfuse"]- failure_callback: ["langfuse"]- langfuse_public_key: os.environ/LANGFUSE_PROJECT1_PUBLIC # Project 1- langfuse_secret: os.environ/LANGFUSE_PROJECT1_SECRET # Project 1- - team_id: team-2- success_callback: ["langfuse"]- failure_callback: ["langfuse"]- langfuse_public_key: os.environ/LANGFUSE_PROJECT2_PUBLIC # Project 2- langfuse_secret: os.environ/LANGFUSE_PROJECT2_SECRET # Project 2- langfuse_host: https://us.cloud.langfuse.com- # cache: true # [OPTIONAL] use for caching responses- # enable_caching_on_provider_specific_optional_params: True # Include provider-specific params in cache keys- # cache_params: # And for shared health check- # type: redis- # host: localhost- # port: 6379--# For /fine_tuning/jobs endpoints-finetune_settings:- - custom_llm_provider: azure- api_base: os.environ/AZURE_API_BASE- api_key: os.environ/AZURE_API_KEY- api_version: "2023-03-15-preview"- - custom_llm_provider: openai- api_key: os.environ/OPENAI_API_KEY--# for /files endpoints-files_settings:- - custom_llm_provider: azure- api_base: os.environ/AZURE_API_BASE- api_key: os.environ/AZURE_API_KEY- api_version: "2023-03-15-preview"- - custom_llm_provider: openai- api_key: os.environ/OPENAI_API_KEY--router_settings:- routing_strategy: usage-based-routing-v2- redis_host: os.environ/REDIS_HOST- redis_password: os.environ/REDIS_PASSWORD- redis_port: os.environ/REDIS_PORT- enable_pre_call_checks: true- model_group_alias: {"my-special-fake-model-alias-name": "fake-openai-endpoint-3"}--general_settings:- master_key: sk-1234 # [OPTIONAL] Use to enforce auth on proxy. See - https://docs.litellm.ai/docs/proxy/virtual_keys- store_model_in_db: True- proxy_budget_rescheduler_min_time: 60- proxy_budget_rescheduler_max_time: 64- proxy_batch_write_at: 1- database_connection_pool_limit: 10- # background_health_checks: true- # use_shared_health_check: true- # health_check_interval: 30- # database_url: "postgresql://<user>:<password>@<host>:<port>/<dbname>" # [OPTIONAL] use for token-based auth to proxy-- pass_through_endpoints:- - path: "/v1/rerank" # route you want to add to LiteLLM Proxy Server- target: "https://api.cohere.com/v1/rerank" # URL this route should forward requests to- headers: # headers to forward to this URL- content-type: application/json # (Optional) Extra Headers to pass to this endpoint- accept: application/json- forward_headers: True--# environment_variables:- # settings for using redis caching- # REDIS_HOST: redis-16337.c322.us-east-1-2.ec2.cloud.redislabs.com- # REDIS_PORT: "16337"- # REDIS_PASSWORD:\ No newline at end of file+ - model_name: gemini-2.5-flash-lite+ litellm_params:+ model: gemini/gemini-2.5-flash-lite+ - model_name: azure-fake-gpt-5-batch-2025-08-07+ litellm_params:+ model: azure/gpt-5+ api_key: asasas+ api_base: http://0.0.0.0:8090++# litellm_settings:+# success_callback: ["s3_v2"]+# s3_callback_params:+# s3_bucket_name: logs-bucket-litellm+# s3_region_name: us-west-2+# s3_aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID+# s3_aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY+# s3_endpoint_url: http://0.0.0.0:8090 # Your custom endpoint URL++# general_settings:+# proxy_batch_polling_interval: 1000\ No newline at end of filediff --git a/tests/search_tests/test_duckduckgo_search.py b/tests/search_tests/test_duckduckgo_search.pyindex a0e5e8ea8ba..13df1cff9d4 100644--- a/tests/search_tests/test_duckduckgo_search.py+++ b/tests/search_tests/test_duckduckgo_search.py@@ -24,7 +24,103 @@ class TestDuckDuckGoSearch(BaseSearchTest):Return search_provider for DuckDuckGo Search."""return "duckduckgo"++ @pytest.mark.asyncio+ async def test_basic_search(self):+ """+ Test basic search functionality with a simple query.+ """+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"+ litellm.model_cost = litellm.get_model_cost_map(url="")+ litellm._turn_on_debug()+ search_provider = self.get_search_provider()+ print("Search Provider=", search_provider)++ try:+ response = await litellm.asearch(+ query="india",+ search_provider=search_provider,+ )+ print("Search response=", response.model_dump_json(indent=4))++ print(f"\n{'='*80}")+ print(f"Response type: {type(response)}")+ print(f"Response object: {response.object if hasattr(response, 'object') else 'N/A'}")++ # Check if response has expected Search format+ 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}'"++ # Validate results structure+ assert isinstance(response.results, list), "results should be a list"+ assert len(response.results) > 0, "Should have at least one result"++ # Check first result structure+ 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"Total results: {len(response.results)}")+ print(f"First result title: {first_result.title}")+ print(f"First result URL: {first_result.url}")+ print(f"First result snippet: {first_result.snippet[:100]}...")+ print(f"{'='*80}\n")++ assert len(first_result.title) > 0, "Title should not be empty"+ assert len(first_result.url) > 0, "URL should not be empty"+ assert len(first_result.snippet) > 0, "Snippet should not be empty"++ # Validate cost tracking in _hidden_params+ assert hasattr(response, "_hidden_params"), "Response should have '_hidden_params' attribute"+ hidden_params = response._hidden_params+ assert "response_cost" in hidden_params, "_hidden_params should contain 'response_cost'"++ response_cost = hidden_params["response_cost"]+ assert response_cost is not None, "response_cost should not be None"+ assert isinstance(response_cost, (int, float)), "response_cost should be a number"+ assert response_cost == 0, "response_cost should be 0"++ print(f"Cost tracking: ${response_cost:.6f}")++ except Exception as e:+ pytest.fail(f"Search call failed: {str(e)}")++ def test_search_response_structure(self):+ """+ Test that the Search response has the correct structure.+ """+ litellm.set_verbose = True+ search_provider = self.get_search_provider()++ response = litellm.search(+ query="india",+ search_provider=search_provider,+ )++ # Validate response structure+ assert hasattr(response, "results"), "Response should have 'results' attribute"+ assert hasattr(response, "object"), "Response should have 'object' attribute"++ assert isinstance(response.results, list), "results should be a list"+ assert len(response.results) > 0, "Should have at least one result"+ assert response.object == "search", "object should be 'search'"++ # Validate first result structure+ 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"+ assert isinstance(first_result.title, str), "title should be a string"+ assert isinstance(first_result.url, str), "url should be a string"+ assert isinstance(first_result.snippet, str), "snippet should be a string"++ print(f"\nResponse structure validated:")+ print(f" - object: {response.object}")+ print(f" - results: {len(response.results)}")+ print(f" - first result has all required fields")class TestDuckDuckGoSearchMocked:"""@@ -156,10 +252,11 @@ class TestDuckDuckGoSearchMocked:# Get the actual call argumentscall_args = mock_get.call_args- # Verify URL contains the query+ # Verify URL contains the query with proper URL encodingurl = call_args.kwargs["url"]assert "api.duckduckgo.com" in url- assert "q=python" in url or "q=python%20programming" in url+ # URL should be properly encoded with %20 for spaces+ assert ("q=python+programming" in url or "q=python%20programming" in url)assert "format=json" in url# Verify response structure