Create tools.py
Browse files
tools.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from smolagents import Tool
|
| 2 |
+
import requests
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class SerperSearchTool(Tool):
|
| 7 |
+
name = "serper_search"
|
| 8 |
+
description = "Performs a web search using Serper.dev and returns the top result."
|
| 9 |
+
inputs = {
|
| 10 |
+
"query": {
|
| 11 |
+
"type": "string",
|
| 12 |
+
"description": "The search query to look up on the web."
|
| 13 |
+
}
|
| 14 |
+
}
|
| 15 |
+
output_type = "string"
|
| 16 |
+
|
| 17 |
+
def forward(self, query: str) -> str:
|
| 18 |
+
headers = {
|
| 19 |
+
"X-API-KEY": os.environ['SERPER_API_KEY'],
|
| 20 |
+
"Content-Type": "application/json"
|
| 21 |
+
}
|
| 22 |
+
payload = {
|
| 23 |
+
"q": query
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
response = requests.post("https://google.serper.dev/search", headers=headers, json=payload)
|
| 27 |
+
data = response.json()
|
| 28 |
+
|
| 29 |
+
if "organic" in data and data["organic"]:
|
| 30 |
+
top = data["organic"][0]
|
| 31 |
+
return f"{top['title']}: {top['link']}"
|
| 32 |
+
return "No relevant results found."
|