File size: 5,629 Bytes
6522974 9b5b26a 8fe992b 6522974 9b5b26a 6522974 9b5b26a ca2d90d 6522974 9b5b26a 6522974 9b5b26a ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 6522974 ca2d90d 9b5b26a 6522974 9b5b26a 6522974 9b5b26a 9b20d4a 9b5b26a 8c01ffb 6aae614 ae7a494 e121372 6522974 13d500a 8c01ffb 6522974 8fe992b 6522974 9b20d4a 46e5e42 6522974 8fe992b 8c01ffb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | import os
import datetime
import requests
import pytz
from smolagents import ToolCallingAgent, HfApiModel, tool
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
DEFAULT_TIMEOUT = 20
def safe_request_json(url: str, *, params=None, headers=None, timeout=DEFAULT_TIMEOUT):
try:
response = requests.get(url, params=params, headers=headers, timeout=timeout)
response.raise_for_status()
return response.json()
except requests.exceptions.Timeout:
raise RuntimeError("The request timed out. Please try again later.")
except requests.exceptions.HTTPError as e:
status_code = getattr(e.response, "status_code", "unknown")
body = ""
try:
body = e.response.text[:300]
except Exception:
pass
raise RuntimeError(f"HTTP {status_code} error. {body}")
except requests.exceptions.RequestException as e:
raise RuntimeError(f"Network request failed: {str(e)}")
except ValueError:
raise RuntimeError("The server returned invalid JSON data.")
@tool
def get_weather(location: str) -> str:
"""Get the current weather for a specified city or region.
Args:
location: A city, region, or country name, such as Beijing, Tokyo, Shanghai, or New York.
"""
try:
url = f"https://wttr.in/{location}"
params = {"format": "j1"}
data = safe_request_json(url, params=params, timeout=20)
current_list = data.get("current_condition", [])
if not current_list:
return f"Could not find weather data for '{location}'."
current = current_list[0]
temp_c = current.get("temp_C", "Unknown")
feels_like_c = current.get("FeelsLikeC", "Unknown")
humidity = current.get("humidity", "Unknown")
wind_kph = current.get("windspeedKmph", "Unknown")
weather_desc = current.get("weatherDesc", [{}])[0].get("value", "Unknown")
weather_days = data.get("weather", [])
high_c = low_c = "Unknown"
if weather_days:
high_c = weather_days[0].get("maxtempC", "Unknown")
low_c = weather_days[0].get("mintempC", "Unknown")
return (
f"Current weather in {location}:\n"
f"- Condition: {weather_desc}\n"
f"- Temperature: {temp_c}°C\n"
f"- Feels like: {feels_like_c}°C\n"
f"- Humidity: {humidity}%\n"
f"- Wind speed: {wind_kph} km/h\n"
f"- Today's high / low: {high_c}°C / {low_c}°C"
)
except Exception as e:
return f"Error fetching weather for '{location}': {str(e)}"
@tool
def get_nba_games(date: str) -> str:
"""Get NBA game results for a specific date.
Args:
date: A date in YYYY-MM-DD format, for example '2026-03-08'.
"""
api_key = os.getenv("BALLDONTLIE_API_KEY")
if not api_key:
return (
"BALLDONTLIE_API_KEY is not set. Please add your BALLDONTLIE API key "
"as an environment variable or Hugging Face Secret."
)
try:
url = "https://api.balldontlie.io/nba/v1/games"
headers = {"Authorization": api_key}
params = {
"dates[]": date,
"per_page": 100,
}
data = safe_request_json(url, params=params, headers=headers, timeout=20)
games = data.get("data", [])
if not games:
return f"No NBA games found for {date}."
results = [f"NBA games on {date}:"]
for game in games:
home_team = game.get("home_team", {}).get("full_name", "Unknown Home Team")
visitor_team = game.get("visitor_team", {}).get("full_name", "Unknown Visitor Team")
home_score = game.get("home_team_score", 0)
visitor_score = game.get("visitor_team_score", 0)
status = game.get("status", "Unknown")
if isinstance(home_score, int) and isinstance(visitor_score, int):
if home_score > visitor_score:
winner = home_team
elif visitor_score > home_score:
winner = visitor_team
else:
winner = "Tie / Not finished"
else:
winner = "Unknown"
results.append(
f"- {visitor_team} {visitor_score} : {home_score} {home_team} "
f"(Status: {status}, Winner: {winner})"
)
return "\n".join(results)
except Exception as e:
return f"Error fetching NBA games for '{date}': {str(e)}"
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""Get the current local time in a specified timezone.
Args:
timezone: A valid timezone string, such as Asia/Shanghai or America/New_York.
"""
try:
tz = pytz.timezone(timezone)
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
final_answer = FinalAnswerTool()
model = HfApiModel(
max_tokens=2048,
temperature=0.2,
model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
custom_role_conversions=None,
)
agent = ToolCallingAgent(
model=model,
tools=[
final_answer,
get_weather,
get_nba_games,
get_current_time_in_timezone,
],
max_steps=4,
planning_interval=None,
name="Chen_Qiang",
description="An agent for weather, NBA results, and timezone queries.",
)
GradioUI(agent).launch() |