Source code for langchain_community.utilities.duckduckgo_search
"""Util that calls DuckDuckGo Search.No setup required. Free.https://pypi.org/project/duckduckgo-search/"""fromtypingimportAny,Dict,List,OptionalfrompydanticimportBaseModel,ConfigDict,model_validator
[docs]classDuckDuckGoSearchAPIWrapper(BaseModel):"""Wrapper for DuckDuckGo Search API. Free and does not require any setup. """region:Optional[str]="wt-wt"""" See https://pypi.org/project/duckduckgo-search/#regions """safesearch:str="moderate"""" Options: strict, moderate, off """time:Optional[str]="y"""" Options: d, w, m, y """max_results:int=5backend:str="auto"""" Options: auto, html, lite """source:str="text"""" Options: text, news, images """model_config=ConfigDict(extra="forbid",)@model_validator(mode="before")@classmethoddefvalidate_environment(cls,values:Dict)->Any:"""Validate that python package exists in environment."""try:fromduckduckgo_searchimportDDGS# noqa: F401exceptImportError:raiseImportError("Could not import duckduckgo-search python package. ""Please install it with `pip install -U duckduckgo-search`.")returnvaluesdef_ddgs_text(self,query:str,max_results:Optional[int]=None)->List[Dict[str,str]]:"""Run query through DuckDuckGo text search and return results."""fromduckduckgo_searchimportDDGSwithDDGS()asddgs:ddgs_gen=ddgs.text(query,region=self.region,# type: ignore[arg-type]safesearch=self.safesearch,timelimit=self.time,max_results=max_resultsorself.max_results,backend=self.backend,)ifddgs_gen:return[rforrinddgs_gen]return[]def_ddgs_news(self,query:str,max_results:Optional[int]=None)->List[Dict[str,str]]:"""Run query through DuckDuckGo news search and return results."""fromduckduckgo_searchimportDDGSwithDDGS()asddgs:ddgs_gen=ddgs.news(query,region=self.region,# type: ignore[arg-type]safesearch=self.safesearch,timelimit=self.time,max_results=max_resultsorself.max_results,)ifddgs_gen:return[rforrinddgs_gen]return[]def_ddgs_images(self,query:str,max_results:Optional[int]=None)->List[Dict[str,str]]:"""Run query through DuckDuckGo image search and return results."""fromduckduckgo_searchimportDDGSwithDDGS()asddgs:ddgs_gen=ddgs.images(query,region=self.region,# type: ignore[arg-type]safesearch=self.safesearch,max_results=max_resultsorself.max_results,)ifddgs_gen:return[rforrinddgs_gen]return[]
[docs]defrun(self,query:str)->str:"""Run query through DuckDuckGo and return concatenated results."""ifself.source=="text":results=self._ddgs_text(query)elifself.source=="news":results=self._ddgs_news(query)elifself.source=="images":results=self._ddgs_images(query)else:results=[]ifnotresults:return"No good DuckDuckGo Search Result was found"return" ".join(r["body"]forrinresults)
[docs]defresults(self,query:str,max_results:int,source:Optional[str]=None)->List[Dict[str,str]]:"""Run query through DuckDuckGo and return metadata. Args: query: The query to search for. max_results: The number of results to return. source: The source to look from. 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. """source=sourceorself.sourceifsource=="text":results=[{"snippet":r["body"],"title":r["title"],"link":r["href"]}forrinself._ddgs_text(query,max_results=max_results)]elifsource=="news":results=[{"snippet":r["body"],"title":r["title"],"link":r["url"],"date":r["date"],"source":r["source"],}forrinself._ddgs_news(query,max_results=max_results)]elifsource=="images":results=[{"title":r["title"],"thumbnail":r["thumbnail"],"image":r["image"],"url":r["url"],"height":r["height"],"width":r["width"],"source":r["source"],}forrinself._ddgs_images(query,max_results=max_results)]else:results=[]ifresultsisNone:results=[{"Result":"No good DuckDuckGo Search Result was found"}]returnresults