chris-clippd's picture
Added argument definition for num_teams to docstring
9c0968c verified
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel,load_tool,tool
from bs4 import BeautifulSoup
import datetime
import requests
import pytz
from typing import List
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI
@tool
def get_top_ranked_teams(division:str, gender:str, num_teams:int)-> List[dict]:
"""A tool that returns a list of dictionaries containing information about the top "num_teams" ranked teams for a given division and gender.
This dictionary includes the team name, their board name (i.e. the short form of their name) and their school ID.
Args:
division: A string representing the division. This can only take values from ["NCAA Division I", "NCAA Division II", "NCAA Division III].
gender: A string representing the gender. This can only take values from ["Women", "Men"].
num_teams: An integer representing the top N teams for which information will be returned.
"""
api_url = f"https://scoreboard.clippd.com/api/rankings/leaderboard?rankingType=Team&gender={gender}&division={division}&sortField=rank&season=2025&limit={num_teams}&offset=0"
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
'Content-Type': 'application/json'
}
response = requests.get(api_url, headers=headers)
if response.status_code == 200:
data = response.json()
schools = data.get("results", [{}])
school_info = []
for school in schools:
school_data = {k: school[k] for k in ["schoolName", "boardName", "schoolId", "eventsWon", "eventsTop3", "strokePlayEvents", "matchPlayEvents"] if k in school}
school_info.append(school_data)
return school_info
else:
return "Error: Unable to fetch the school information."
@tool
def get_team_results(school_id: str) -> dict:
"""A tool that returns a dictionary of event results for a team using their school ID.
Args:
school_id: A string representing the school's ID.
"""
# Target URL with dynamic school_id
url = f"https://scoreboard.clippd.com/teams/{school_id}?season=2025"
# Headers to mimic a browser request
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)',
}
# Dictionary to store extracted data
golf_data = {}
# Fetch the raw HTML
response = requests.get(url, headers=headers)
if response.status_code != 200:
print(f"Failed to retrieve page. Status code: {response.status_code}")
return golf_data
# Parse HTML content
soup = BeautifulSoup(response.text, "html.parser")
# Find the specific table
table = soup.find("table", {
"class": "w-full table-auto",
"data-sentry-component": "InnerTable"
})
if not table:
print("No table found on the page")
return golf_data
# Find all table rows inside tbody
table_rows = table.select("tbody tr")
for row in table_rows:
# Extract Event Name
event_name_tag = row.select_one("td a div div span")
event_name = event_name_tag.get_text(strip=True) if event_name_tag else ""
# Extract Position
position_tag = row.select_one("td:nth-of-type(2) p")
position = position_tag.get_text(strip=True) if position_tag else ""
# Extract Score
score_tag = row.select_one("td:nth-of-type(3) div div")
score = score_tag.get_text(strip=True) if score_tag else ""
# Append extracted data to dictionary
if event_name and position and score:
golf_data[event_name] = {"Position": position, "Score": score}
return golf_data
@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 string representing a valid timezone (e.g., 'America/New_York').
"""
try:
# Create timezone object
tz = pytz.timezone(timezone)
# Get current time in that 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()
# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer, get_top_ranked_teams, get_team_results], ## add your tools here (don't remove final answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()