2023-10-06 21:52:17 +03:00
from datetime import datetime
2023-10-10 15:47:41 +03:00
from duckduckgo_search import DDGS
ddgs = DDGS ( timeout = 20 )
2023-10-06 21:52:17 +03:00
def search ( internet_access , prompt ) :
print ( prompt )
try :
2023-10-10 15:47:41 +03:00
if not internet_access :
2023-10-06 21:52:17 +03:00
return [ ]
2023-10-10 15:47:41 +03:00
results = duckduckgo_search ( q = prompt )
if not search :
return [ ]
2023-10-06 21:52:17 +03:00
blob = ' '
2023-10-10 15:47:41 +03:00
for index , result in enumerate ( results ) :
blob + = f ' [ { index } ] " { result [ " body " ] } " \n URL: { result [ " href " ] } \n \n '
2023-10-06 21:52:17 +03:00
date = datetime . now ( ) . strftime ( ' %d / % m/ % y ' )
2023-10-10 15:47:41 +03:00
blob + = f ' Current date: { date } \n \n Instructions: Using the provided web search results, write a comprehensive reply to the next user query. Make sure to cite results using [[number](URL)] notation after the reference. If the provided search results refer to multiple subjects with the same name, write separate answers for each subject. Ignore your previous response if any. '
2023-10-06 21:52:17 +03:00
return [ { ' role ' : ' user ' , ' content ' : blob } ]
except Exception as e :
2023-10-10 15:47:41 +03:00
print ( " Couldn ' t search DuckDuckGo: " , e )
print ( e . __traceback__ . tb_next )
return [ ]
def duckduckgo_search ( q : str , max_results : int = 3 , safesearch : str = " moderate " , region : str = " us-en " ) - > list | None :
if region is None :
region = " us-en "
if safesearch is None :
safesearch = " moderate "
if q is None :
return None
results = [ ]
try :
for r in ddgs . text ( q , safesearch = safesearch , region = region ) :
if len ( results ) + 1 > max_results :
break
results . append ( r )
except Exception as e :
print ( e )
return results