Unit_3_Agentic_RAG / tools.py
PRONGS-CHIRAG
Changed to langgraph
cb1a7f5
from langchain.tools import StructuredTool
from typing import Optional
import random
import os
from huggingface_hub import list_models
import requests
# Get the OpenWeatherMap API key from environment variable
OPENWEATHERMAP_API_KEY = os.getenv("OPENWEATHERMAP_API_KEY")
def get_weather_info(location: str) -> str:
if not OPENWEATHERMAP_API_KEY:
return "API key for OpenWeatherMap not found. Please set OPENWEATHERMAP_API_KEY."
try:
url = "http://api.openweathermap.org/data/2.5/weather"
params = {
"q": location,
"appid": OPENWEATHERMAP_API_KEY,
"units": "metric"
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
description = data["weather"][0]["description"].capitalize()
temp = data["main"]["temp"]
city = data["name"]
country = data["sys"]["country"]
return f"Current weather in {city}, {country}: {description}, {temp:.1f}°C"
except requests.exceptions.HTTPError as http_err:
return f"HTTP error occurred while fetching weather for {location}: {http_err}"
except Exception as e:
return f"Error fetching weather for {location}: {str(e)}"
WeatherInfoTool = StructuredTool.from_function(
name="weather_info",
description="Fetches real-time weather information for a given location using OpenWeatherMap.",
func=get_weather_info
)
# -- Hugging Face Hub Stats Tool --
def get_hub_stats(author: str) -> str:
try:
models = list(list_models(author=author, sort="downloads", direction=-1, limit=1))
if models:
model = models[0]
return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads."
else:
return f"No models found for author {author}."
except Exception as e:
return f"Error fetching models for {author}: {str(e)}"
HubStatsTool = StructuredTool.from_function(
name="hub_stats",
description="Fetches the most downloaded model from a specific author on Hugging Face Hub.",
func=get_hub_stats
)
# -- DuckDuckGo Search Tool (simple version) --
def duckduckgo_search(query: str) -> str:
try:
response = requests.get("https://api.duckduckgo.com/", params={
"q": query,
"format": "json",
"no_redirect": "1",
"no_html": "1"
})
data = response.json()
abstract = data.get("AbstractText") or data.get("RelatedTopics", [{}])[0].get("Text", "")
return abstract if abstract else "No good answer found from DuckDuckGo."
except Exception as e:
return f"Search failed: {str(e)}"
DuckDuckGoSearchTool = StructuredTool.from_function(
name="duckduckgo_search",
description="Searches DuckDuckGo for a given query.",
func=duckduckgo_search
)