Fix : web search

This commit is contained in:
martin legrand
2025-03-11 12:27:19 +01:00
parent ed02a4dad0
commit 479bc2769b
7 changed files with 32 additions and 10 deletions
+14 -7
View File
@@ -6,9 +6,13 @@ import dotenv
dotenv.load_dotenv()
if __name__ == "__main__":
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from utility import animate_thinking, pretty_print
from tools import Tools
else:
from sources.tools.tools import Tools
from sources.utility import animate_thinking, pretty_print
class webSearch(Tools):
def __init__(self, api_key: str = None):
@@ -24,6 +28,7 @@ class webSearch(Tools):
return "Error: No SerpApi key provided."
for block in blocks:
query = block.strip()
pretty_print(f"Searching for: {query}", color="status")
if not query:
return "Error: No search query provided."
@@ -32,19 +37,21 @@ class webSearch(Tools):
params = {
"q": query,
"api_key": self.api_key,
"num": 1,
"num": 100,
"output": "json"
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
results = []
if "organic_results" in data and len(data["organic_results"]) > 0:
first_result = data["organic_results"][0]
title = first_result.get("title", "No title")
snippet = first_result.get("snippet", "No snippet available")
link = first_result.get("link", "No link available")
return f"Title: {title}\nSnippet: {snippet}\nLink: {link}"
for result in data["organic_results"][:50]:
title = result.get("title", "No title")
snippet = result.get("snippet", "No snippet available")
link = result.get("link", "No link available")
results.append(f"Title: {title}\nSnippet: {snippet}\nLink: {link}")
return "\n\n".join(results)
else:
return "No results found for the query."
except requests.RequestException as e:
@@ -65,6 +72,6 @@ class webSearch(Tools):
if __name__ == "__main__":
search_tool = webSearch(api_key=os.getenv("SERPAPI_KEY"))
query = "when did covid start"
result = search_tool.execute(query, safety=True)
result = search_tool.execute([query], safety=True)
feedback = search_tool.interpreter_feedback(result)
print(feedback)