AGAZO_Final_Assignment / internet_search_tool.py
Alexandre Gazola
codigo agente
f66d8b7
raw
history blame
1.62 kB
from duckduckgo_search import DDGS
from utils import clean_text
from langchain_core.tools import tool
@tool
def internet_search(query: str, max_results: int = 10) -> list[dict]:
"""
Search the Internet for the given query and return a list of results.
Args:
query (str): The search query string.
max_results (int, optional): Maximum number of search results to return. Default is 10.
Returns:
list[dict]: A list of dictionaries containing search results. Each dictionary typically includes:
- 'title': The title of the result.
- 'href': The URL of the result.
- 'body': A short snippet or description.
Raises:
ValueError: If the query is empty or only whitespace.
"""
if not query.strip():
raise ValueError("Query must not be empty.")
results = []
with DDGS() as ddgs:
for r in ddgs.text(query):
results.append(r)
if len(results) >= max_results:
break
return results
if __name__ == "__main__":
query = 'Alexandre Gazola'
try:
results = internet_search.invoke(
{
"query": query,
"max_results": 5
}
)
for i, result in enumerate(results, 1):
print(f"\nResult {i}:")
print(f"Title: {clean_text(result.get('title'))}")
print(f"URL: {clean_text(result.get('href'))}")
print(f"Snippet: {clean_text(result.get('body'))}")
except ValueError as e:
print(f"Error: {e}")