| | 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() |