Aktraiser's picture
Update app.py
66984de verified
raw
history blame
3.66 kB
from smolagents import CodeAgent, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""
A tool that fetches the current local time in a specified timezone.
Args:
timezone: A valid timezone string (e.g., '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)}"
@tool
def get_nba_matches() -> str:
"""
A tool that retrieves upcoming NBA matches using TheRundown API.
Uses the /openers endpoint for the specified date.
Returns:
A human-readable string listing the upcoming NBA matches.
"""
import requests
import datetime
# Utilisez la date d'aujourd'hui ou une date spécifique
today = datetime.date.today().strftime("%Y-%m-%d")
# Construisez l'URL avec des paramètres corrects (ici offset=0 et include=scores)
url = f"https://api.apilayer.com/therundown/sports/4/openers/{today}?offset=0&include=scores"
headers = {
"apikey": "7k4hKSUeWkbigKxZiNV5CQ8RSlEd72Cj"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
matches = []
# Parcourez la liste des événements retournés par l'API
for event in data.get("events", []):
# Utilisez la clé "event_date" au lieu de "start_time"
event_date = event.get("event_date", "Unknown date")
teams = event.get("teams", [])
if len(teams) >= 2:
team1 = teams[0].get("name", "Team1 N/A")
team2 = teams[1].get("name", "Team2 N/A")
else:
team1, team2 = "Team1 N/A", "Team2 N/A"
matches.append(f"{event_date}: {team1} vs {team2}")
if matches:
return "\n".join(matches)
else:
return "No NBA matches found."
else:
return f"Error retrieving NBA matches: {response.status_code}"
@tool
def predict_nba_match(match_info: str) -> str:
"""
A tool that generates a prediction for an NBA match.
Args:
match_info: A string containing match details in the format "TeamA vs TeamB".
Returns:
A string with the prediction (e.g., "The prediction is that TeamA will win.").
"""
import random
teams = match_info.split(" vs ")
if len(teams) == 2:
prediction = random.choice(teams)
return f"The prediction is that {prediction} will win."
else:
return "Invalid match format. Please provide details in the format 'TeamA vs TeamB'."
# Instantiate the final_answer tool.
final_answer = FinalAnswerTool()
# Configure the model.
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
# Load prompt templates.
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
# Initialize the agent with all necessary tools.
agent = CodeAgent(
model=model,
tools=[final_answer, get_current_time_in_timezone, get_nba_matches, predict_nba_match],
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()