from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool import datetime import requests import pytz import yaml from tools.final_answer import FinalAnswerTool from Gradio_UI import GradioUI import re import requests # Import the requests library from bs4 import BeautifulSoup #for parsing from urllib.parse import quote @tool def get_crypto_price(crypto: str, currency: str = "usd") -> str: """ Fetches and returns the current price of a given cryptocurrency as a formatted USD string. Args: crypto: The ID of the cryptocurrency (e.g., 'bitcoin'). currency: The currency in which to return the price (default is 'usd'). """ url = f"https://api.coingecko.com/api/v3/simple/price?ids={crypto}&vs_currencies={currency}" try: data = requests.get(url).json() price = float(data[crypto][currency]) return f"${price:,.2f}" except Exception as e: return f"Error: {e}" @tool def get_full_poem(verse: str) -> str: """ Fetches and returns the song that includes the verse Args: verse: the verse that user wants to find the poem of it. (eg: چو ایران نباشد) """ encoded_query = quote(query) url = f"https://ganjoor.net/search?s={encoded_query}&es=1&author=0" return url # url = f"https://ganjoor.net/search?s=%D8%B3%D9%84%D8%A7%D9%85&es=1&author=0" try: data = requests.get(url).json() price = float(data[crypto][currency]) return f"${price:,.2f}" except Exception as e: return f"Error: {e}" @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)}" @tool def find_the_song(arg1: str) -> str: """A tool that gets the description of song from a verse provided by use. Args: arg1: A string representing a valid timezone (e.g., 'America/New_York'). """ try: search_term = f"site:genius.com OR site:azlyrics.com song lyrics \"{arg1}\"" #Focus on specific lyric sites search_tool = DuckDuckGoSearchTool() search_results = search_tool.use({"query": search_term}) if search_results: #Try extracting information from Genius or AZLyrics (prioritized) if "genius.com" in search_results.lower(): try: url = re.search(r'(https?://[^\s]+)', search_results).group(0) # Get the genius URL response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') #html parser song_title = soup.find("h1", class_="song_title").text.strip() if soup.find("h1", class_="song_title") else None #search song's name from specific h1 tag artist = soup.find("a", class_="artist_name").text.strip() if soup.find("a", class_="artist_name") else None #same but for artist name lyrics_div = soup.find("div", class_="lyrics") if soup.find("div", class_="lyrics") else soup.find("div", class_="Lyrics__Container") #finding lyrics tags (check them both if one is not available) if lyrics_div: lyrics = lyrics_div.get_text(separator="\n").strip() else: lyrics = None except Exception as e: return f"Error scraping Genius: {e}. Raw results: {search_results}" elif "azlyrics.com" in search_results.lower(): try: url = re.search(r'(https?://[^\s]+)', search_results).group(0) # Get the azlyrics URL response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') lyrics_div = soup.find("div", class_="ringtone") # Lyrics are inside a specific div if lyrics_div: lyrics = lyrics_div.find_next("div").get_text().strip() # Get the lyrics that are in the next div artist_element = soup.find('div', class_='lyricsh') # Find the tag of the lyrics artist = artist_element.find_next('b').text.split('lyrics')[0].strip() #parse the artist's name out song_title = soup.find('title').text.split(' - ')[0].strip() #same for name else: lyrics = None except Exception as e: return f"Error scraping AZLyrics: {e}. Raw results: {search_results}" else: return f"Could not find Genius or AZLyrics page, so couldn't extract lyrics. Raw results: {search_results}" if song_title is None or artist is None: title_match = re.search(r"Title:\s*(.*)", search_results, re.IGNORECASE) artist_match = re.search(r"Artist:\s*(.*)", search_results, re.IGNORECASE) song_title = title_match.group(1).strip() if title_match else None artist = artist_match.group(1).strip() if artist_match else None if song_title and artist and lyrics and spotify_url: return f"song name: {song_title} , by {artist} . the spotify url is : {spotify_url} \nthe lyrics are : {lyrics}" # return the song + lyrics if song_title and artist: spotify_message = f"\n(Could not reliably extract Spotify URL)" if spotify_url is None else "" lyrics_message = f"\n(Could not reliably extract Lyrics)" if lyrics is None else "" return f"Found song: {song_title} by {artist} . {spotify_message}{lyrics_message}. Raw results: {search_results}" return f"Could not extract full information, check the search results:\n {search_results}" #in case it fails return the search result else: return "Could not find any songs matching the verse." except Exception as e: return f"An error occurred: {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, find_the_song, get_crypto_price,get_full_poem,get_current_time_in_timezone], ## 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()