Free and does not require any setup of API keys
This module provides web search capabilities using DuckDuckGo's search API without requiring API keys.
Overview
The DuckDuckGo search module offers:
- Free Search API: No API keys or authentication required
- Privacy Focused: Uses DuckDuckGo's privacy-first search engine
- Multiple Result Formats: Both text summaries and structured metadata
- Configurable Parameters: Region, safety, time filters, and result limits
- LangChain Integration: Ready for use as a tool in agent workflows
Key Features
- Zero-setup web search functionality
- Customizable search parameters (region, time, safety)
- Structured result metadata extraction
- Error handling for failed searches
- Integration with AGI and agent systems
from typing import Dict, List, Optional
from pydantic import BaseModel, Extra
from pydantic.class_validators import root_validator
class DuckDuckGoSearchAPIWrapper(BaseModel):
"""Wrapper for DuckDuckGo Search API.
Free and does not require any setup
"""
k: int = 10
region: Optional[str] = "wt-wt"
safesearch: str = "moderate"
time: Optional[str] = "y"
max_results: int = 5
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator()
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that python package exists in environment."""
try:
from duckduckgo_search import ddg # noqa: F401
except ImportError:
raise ValueError(
"Could not import duckduckgo-search python package. "
"Please install it with `pip install duckduckgo-search`."
)
return values
def run(self, query: str) -> str:
from duckduckgo_search import ddg
"""Run query through DuckDuckGo and return results."""
results = ddg(
query,
region=self.region,
safesearch=self.safesearch,
time=self.time,
max_results=self.max_results,
)
if results is None or len(results) == 0:
return f'No suitable DuckDuckGo search results found for "{query}": {{{results}}}'
snippets = '\n'.join([result['body'] for result in results])
return (
f'Results for the DuckDuckGo search "{query}": {{\n'
f'{snippets}\n'
f'}}'
)
def results(self, query: str, num_results: int) -> List[Dict]:
"""Run query through DuckDuckGo and return metadata.
Args:
query: The query to search for.
num_results: The number of results to return.
Returns:
A list of dictionaries with the following keys:
snippet - The description of the result.
title - The title of the result.
link - The link to the result.
"""
from duckduckgo_search import ddg
results = ddg(
query,
region=self.region,
safesearch=self.safesearch,
time=self.time,
max_results=num_results,
)
if results is None or len(results) == 0:
return [{"Result": f'No good {{DuckDuckGo Search Result: {results}}} was found for query: {query}'}]
def to_metadata(result: Dict) -> Dict:
return {
"snippet": result["body"],
"title": result["title"],
"link": result["href"],
}
return [to_metadata(result) for result in results]