-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch_tools.py
34 lines (32 loc) · 1.14 KB
/
search_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import json
import os
import requests
from langchain.tools import tool
class SearchTools:
@tool("Search internet")
def search_internet(query):
"""Useful to search the internet about a given topic and return relevant results."""
return SearchTools.search(query)
@staticmethod
def search(query, n_results=5):
url = "https://google.serper.dev/search"
payload = json.dumps({"q": query})
headers = {
'X-API-KEY': os.environ['SERPER_API_KEY'],
'content-type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data=payload)
results = response.json().get('organic', [])
string = []
for result in results[:n_results]:
try:
string.append('\n'.join([
f"Title: {result['title']}",
f"Link: {result['link']}",
f"Snippet: {result['snippet']}",
"\n-----------------"
]))
except KeyError:
continue
content = '\n'.join(string)
return f"\nSearch result: {content}\n"