Source code for langchain_community.utilities.duckduckgo_search
"""Util that calls DuckDuckGo Search.No setup required. Free.https://pypi.org/project/duckduckgo-search/"""fromtypingimportDict,List,Optionalfromlangchain_core.pydantic_v1importBaseModel,root_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="api"""" Options: api, html, lite """source:str="text"""" Options: text, news """classConfig:extra="forbid"@root_validator(pre=True)defvalidate_environment(cls,values:Dict)->Dict:"""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,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,safesearch=self.safesearch,timelimit=self.time,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)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)]else:results=[]ifresultsisNone:results=[{"Result":"No good DuckDuckGo Search Result was found"}]returnresults