File size: 7,556 Bytes
9b5b26a
 
 
 
c19d193
6aae614
8fe992b
9b5b26a
6bf5858
 
 
8dd2869
6bf5858
9d9f2f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
8dd2869
 
 
 
3ca0572
8dd2869
e3fe453
d5e51b7
8dd2869
 
 
 
8d77838
 
 
 
 
 
 
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d77838
 
 
 
 
 
 
 
 
 
 
0084adb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d77838
 
0084adb
 
 
8d77838
0084adb
 
8d77838
 
 
 
0084adb
 
8d77838
 
 
0084adb
 
 
 
 
8d77838
 
0084adb
 
8d77838
 
 
 
6aae614
ae7a494
 
 
 
e121372
bf6d34c
 
29ec968
fe328e0
13d500a
8c01ffb
 
9b5b26a
 
8c01ffb
861422e
 
9b5b26a
8c01ffb
8fe992b
8d77838
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
9b5b26a
8c01ffb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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()