from smolagents.tools import Tool import requests class PrimeiraLigaTeamStatsTool(Tool): name = "get_primeira_liga_team_stats" description = "Retrieve standing and last 3 match scores for a given Primeira Liga team." inputs = {'team_name': {'type': 'string', 'description': 'Name of the team to search for'}} output_type = "string" def forward(self, team_name: str) -> str: def _determine_match_outcome(home_team: str, away_team: str, home_score: int, away_score: int, target_team: str) -> str: """ Determine match outcome (W/D/L) from the perspective of the target team. """ if home_team == target_team: if home_score > away_score: return 'W' elif home_score < away_score: return 'L' else: return 'D' else: if away_score > home_score: return 'W' elif away_score < home_score: return 'L' else: return 'D' # API Base URL BASE_URL = "https://www.thesportsdb.com/api/v1/json/3" # Hardcoded Primeira Liga League ID PRIMEIRA_LIGA_ID = 4344 try: # Step 1: Search for the team to get its ID team_search_url = f"{BASE_URL}/searchteams.php?t={team_name.replace(' ', '%20')}" team_search_response = requests.get(team_search_url) team_search_data = team_search_response.json() if not team_search_data.get('teams'): return "Error: Team not found" # Get the first matching team's ID team_id = team_search_data['teams'][0]['idTeam'] # Step 2: Get league table table_url = f"{BASE_URL}/lookuptable.php?l={PRIMEIRA_LIGA_ID}" table_response = requests.get(table_url) table_data = table_response.json() # Find team's standing standing = next( (int(entry['intRank']) for entry in table_data.get('table', []) if entry['idTeam'] == team_id), None ) # Step 3: Get last 5 events for the team last_events_url = f"{BASE_URL}/eventslast.php?id={team_id}" last_events_response = requests.get(last_events_url) last_events_data = last_events_response.json() # Process last 3 matches last_3_matches = [] for event in last_events_data.get('results', [])[:3]: match = { 'opponent': event['strAwayTeam'] if event['strHomeTeam'] == team_name else event['strHomeTeam'], 'result': f"{event['intHomeScore']} - {event['intAwayScore']}", 'outcome': _determine_match_outcome( event['strHomeTeam'], event['strAwayTeam'], event['intHomeScore'], event['intAwayScore'], team_name ) } last_3_matches.append(match) return str({ "team": team_name, "standing": standing, "last_3_matches": last_3_matches }) except Exception as e: print(f"Error retrieving team stats: {e}") return str("Error retrieving team stats") def __init__(self, *args, **kwargs): self.is_initialized = False