| 24 | class SearchAPIEngine(): |
| 25 | |
| 26 | def search(self, query: str, item_num: int = 3): |
| 27 | try: |
| 28 | url = "https://www.searchapi.io/api/v1/search" |
| 29 | params = { |
| 30 | "engine": "google", |
| 31 | "q": query, |
| 32 | "api_key": os.getenv("SEARCHAPI_API_KEY") |
| 33 | } |
| 34 | |
| 35 | response = ast.literal_eval(requests.get(url, params = params).text) |
| 36 | |
| 37 | except: |
| 38 | return '' |
| 39 | |
| 40 | if 'knowledge_graph' in response.keys() and 'description' in response['knowledge_graph'].keys(): |
| 41 | return response['knowledge_graph']['description'] |
| 42 | if 'organic_results' in response.keys() and len(response['organic_results']) > 0: |
| 43 | |
| 44 | return '\n'.join([res['snippet'] for res in response['organic_results'][:item_num]]) |
| 45 | return '' |
| 46 | |
| 47 | |
| 48 | |