MeghanaNanuvala's picture
Update tools.py
cf9696d verified
# tools.py
from smolagents import Tool
import random
from huggingface_hub import list_models
# ---- Web search (DuckDuckGo) as a smolagents Tool ----
# Requires: pip install duckduckgo-search
from duckduckgo_search import DDGS
class DDGSearchTool(Tool):
name = "web_search"
description = (
"Search the web with DuckDuckGo. "
"Returns a short list of titles + links + snippets."
)
inputs = {
"query": {
"type": "string",
"description": "What to search for on the web."
}
}
output_type = "string"
def forward(self, query: str) -> str:
# fetch top results
with DDGS() as ddgs:
results = list(ddgs.text(query, max_results=5))
if not results:
return "No results found."
lines = []
for i, r in enumerate(results[:5], 1):
title = r.get("title", "").strip()
href = r.get("href", "").strip()
body = r.get("body", "").strip()
lines.append(f"{i}. {title}\n{href}\n{body}")
return "\n\n".join(lines)
# ---- Weather (dummy) ----
class WeatherInfoTool(Tool):
name = "weather_info"
description = "Fetches dummy weather information for a given location"
inputs = {
"location": {
"type": "string",
"description": "The location to get weather information for."
}
}
output_type = "string"
def forward(self, location: str) -> str:
weather_conditions = [
{"condition": "Rainy", "temp_c": 15},
{"condition": "Clear", "temp_c": 25},
{"condition": "Windy", "temp_c": 20},
]
data = random.choice(weather_conditions)
return f"Weather in {location}: {data['condition']}, {data['temp_c']}C"
# ---- HF Hub stats ----
class HubStatsTool(Tool):
name = "hub_stats"
description = "Fetches the most downloaded model from a specified author on the Hugging Face Hub"
inputs = {
"author": {
"type": "string",
"description": "The username/org to list models from."
}
}
output_type = "string"
def forward(self, author: str) -> str:
try:
models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
if models:
m = models[0]
# Some older hubs might not expose downloads; guard just in case.
downloads = getattr(m, "downloads", None)
if downloads is None:
return f"The most downloaded model by {author} is {m.id}."
return f"The most downloaded model by {author} is {m.id} with {downloads:,} downloads."
return f"No models found for author {author}."
except Exception as e:
return f"Error fetching models for {author}: {e}"
# Instances you can import in app.py
search_tool = DDGSearchTool()
weather_info_tool = WeatherInfoTool()
hub_stats_tool = HubStatsTool()