danielkorat commited on
Commit
d034bf1
·
verified ·
1 Parent(s): 987f003

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -240
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
@@ -21,245 +21,9 @@ model = HfApiModel()
21
  # model = TransformersModel(model_id="meta-llama/Llama-3.2-2B-Instruct")
22
 
23
  # For anthropic: change model_id below to 'anthropic/claude-3-5-sonnet-20240620'
24
- # model = LiteLLMModel(model_id="gpt-4o")
25
 
26
 
27
- @tool
28
- def get_weather(location: str, celsius: Optional[bool] = False) -> str:
29
- """
30
- Get the current weather at the given location using the WeatherStack API.
31
-
32
- Args:
33
- location: The location (city name).
34
- celsius: Whether to return the temperature in Celsius (default is False, which returns Fahrenheit).
35
-
36
- Returns:
37
- A string describing the current weather at the location.
38
- """
39
- api_key = "your_api_key" # Replace with your API key from https://weatherstack.com/
40
- units = "m" if celsius else "f" # 'm' for Celsius, 'f' for Fahrenheit
41
-
42
- url = f"http://api.weatherstack.com/current?access_key={api_key}&query={location}&units={units}"
43
-
44
- try:
45
- response = requests.get(url)
46
- response.raise_for_status() # Raise an exception for HTTP errors
47
-
48
- data = response.json()
49
-
50
- if data.get("error"): # Check if there's an error in the response
51
- return f"Error: {data['error'].get('info', 'Unable to fetch weather data.')}"
52
-
53
- weather = data["current"]["weather_descriptions"][0]
54
- temp = data["current"]["temperature"]
55
- temp_unit = "°C" if celsius else "°F"
56
-
57
- return f"The current weather in {location} is {weather} with a temperature of {temp} {temp_unit}."
58
-
59
- except requests.exceptions.RequestException as e:
60
- return f"Error fetching weather data: {str(e)}"
61
-
62
-
63
- @tool
64
- def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
65
- """
66
- Converts a specified amount from one currency to another using the ExchangeRate-API.
67
-
68
- Args:
69
- amount: The amount of money to convert.
70
- from_currency: The currency code of the currency to convert from (e.g., 'USD').
71
- to_currency: The currency code of the currency to convert to (e.g., 'EUR').
72
-
73
- Returns:
74
- str: A string describing the converted amount in the target currency, or an error message if the conversion fails.
75
-
76
- Raises:
77
- requests.exceptions.RequestException: If there is an issue with the HTTP request to the ExchangeRate-API.
78
- """
79
- api_key = "your_api_key" # Replace with your actual API key from https://www.exchangerate-api.com/
80
- url = f"https://v6.exchangerate-api.com/v6/{api_key}/latest/{from_currency}"
81
-
82
- try:
83
- response = requests.get(url)
84
- response.raise_for_status()
85
-
86
- data = response.json()
87
- exchange_rate = data["conversion_rates"].get(to_currency)
88
-
89
- if not exchange_rate:
90
- return f"Error: Unable to find exchange rate for {from_currency} to {to_currency}."
91
-
92
- converted_amount = amount * exchange_rate
93
- return f"{amount} {from_currency} is equal to {converted_amount} {to_currency}."
94
-
95
- except requests.exceptions.RequestException as e:
96
- return f"Error fetching conversion data: {str(e)}"
97
-
98
-
99
- @tool
100
- def get_news_headlines() -> str:
101
- """
102
- Fetches the top news headlines from the News API for the United States.
103
- This function makes a GET request to the News API to retrieve the top news headlines
104
- for the United States. It returns the titles and sources of the top 5 articles as a
105
- formatted string. If no articles are available, it returns a message indicating that
106
- no news is available. In case of a request error, it returns an error message.
107
- Returns:
108
- str: A string containing the top 5 news headlines and their sources, or an error message.
109
- """
110
- api_key = "your_api_key" # Replace with your actual API key from https://newsapi.org/
111
- url = f"https://newsapi.org/v2/top-headlines?country=us&apiKey={api_key}"
112
-
113
- try:
114
- response = requests.get(url)
115
- response.raise_for_status()
116
-
117
- data = response.json()
118
- articles = data["articles"]
119
-
120
- if not articles:
121
- return "No news available at the moment."
122
-
123
- headlines = [f"{article['title']} - {article['source']['name']}" for article in articles[:5]]
124
- return "\n".join(headlines)
125
-
126
- except requests.exceptions.RequestException as e:
127
- return f"Error fetching news data: {str(e)}"
128
-
129
-
130
- @tool
131
- def get_joke() -> str:
132
- """
133
- Fetches a random joke from the JokeAPI.
134
- This function sends a GET request to the JokeAPI to retrieve a random joke.
135
- It handles both single jokes and two-part jokes (setup and delivery).
136
- If the request fails or the response does not contain a joke, an error message is returned.
137
- Returns:
138
- str: The joke as a string, or an error message if the joke could not be fetched.
139
- """
140
- url = "https://v2.jokeapi.dev/joke/Any?type=single"
141
-
142
- try:
143
- response = requests.get(url)
144
- response.raise_for_status()
145
-
146
- data = response.json()
147
-
148
- if "joke" in data:
149
- return data["joke"]
150
- elif "setup" in data and "delivery" in data:
151
- return f"{data['setup']} - {data['delivery']}"
152
- else:
153
- return "Error: Unable to fetch joke."
154
-
155
- except requests.exceptions.RequestException as e:
156
- return f"Error fetching joke: {str(e)}"
157
-
158
-
159
- @tool
160
- def get_time_in_timezone(location: str) -> str:
161
- """
162
- Fetches the current time for a given location using the World Time API.
163
- Args:
164
- location: The location for which to fetch the current time, formatted as 'Region/City'.
165
- Returns:
166
- str: A string indicating the current time in the specified location, or an error message if the request fails.
167
- Raises:
168
- requests.exceptions.RequestException: If there is an issue with the HTTP request.
169
- """
170
- url = f"http://worldtimeapi.org/api/timezone/{location}.json"
171
-
172
- try:
173
- response = requests.get(url)
174
- response.raise_for_status()
175
-
176
- data = response.json()
177
- current_time = data["datetime"]
178
-
179
- return f"The current time in {location} is {current_time}."
180
-
181
- except requests.exceptions.RequestException as e:
182
- return f"Error fetching time data: {str(e)}"
183
-
184
-
185
- @tool
186
- def get_random_fact() -> str:
187
- """
188
- Fetches a random fact from the "uselessfacts.jsph.pl" API.
189
- Returns:
190
- str: A string containing the random fact or an error message if the request fails.
191
- """
192
- url = "https://uselessfacts.jsph.pl/random.json?language=en"
193
-
194
- try:
195
- response = requests.get(url)
196
- response.raise_for_status()
197
-
198
- data = response.json()
199
-
200
- return f"Random Fact: {data['text']}"
201
-
202
- except requests.exceptions.RequestException as e:
203
- return f"Error fetching random fact: {str(e)}"
204
-
205
-
206
- @tool
207
- def search_wikipedia(query: str) -> str:
208
- """
209
- Fetches a summary of a Wikipedia page for a given query.
210
- Args:
211
- query: The search term to look up on Wikipedia.
212
- Returns:
213
- str: A summary of the Wikipedia page if successful, or an error message if the request fails.
214
- Raises:
215
- requests.exceptions.RequestException: If there is an issue with the HTTP request.
216
- """
217
- url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{query}"
218
-
219
- try:
220
- response = requests.get(url)
221
- response.raise_for_status()
222
-
223
- data = response.json()
224
- title = data["title"]
225
- extract = data["extract"]
226
-
227
- return f"Summary for {title}: {extract}"
228
-
229
- except requests.exceptions.RequestException as e:
230
- return f"Error fetching Wikipedia data: {str(e)}"
231
-
232
-
233
-
234
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
235
- @tool
236
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
237
- #Keep this format for the description / args / args description but feel free to modify the tool
238
- """A tool that does nothing yet
239
- Args:
240
- arg1: the first argument
241
- arg2: the second argument
242
- """
243
- return "What magic will you build ?"
244
-
245
- @tool
246
- def get_current_time_in_timezone(timezone: str) -> str:
247
- """A tool that fetches the current local time in a specified timezone.
248
- Args:
249
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
250
- """
251
- try:
252
- # Create timezone object
253
- tz = pytz.timezone(timezone)
254
- # Get current time in that timezone
255
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
256
- return f"The current local time in {timezone} is: {local_time}"
257
- except Exception as e:
258
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
259
-
260
-
261
- final_answer = FinalAnswerTool()
262
-
263
  # If the agent does not answer, the model is overloaded, please use another model or the original Hugging Face Endpoint for contains qwen2.5 coder:
264
  # 'Qwen/Qwen2.5-Coder-32B-Instruct'
265
  model = HfApiModel(
@@ -269,7 +33,8 @@ model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud', #
269
  custom_role_conversions=None,
270
  )
271
 
272
- # Import tool from Hub
 
273
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
274
  search_tool = DuckDuckGoSearchTool()
275
 
@@ -288,6 +53,7 @@ agent = CodeAgent(
288
  get_joke,
289
  get_random_fact,
290
  search_wikipedia,
 
291
  ],
292
  max_steps=10,
293
  verbosity_level=4,
@@ -299,4 +65,4 @@ agent = CodeAgent(
299
  )
300
 
301
 
302
- GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool
2
  import datetime
3
  import requests
4
  import pytz
 
21
  # model = TransformersModel(model_id="meta-llama/Llama-3.2-2B-Instruct")
22
 
23
  # For anthropic: change model_id below to 'anthropic/claude-3-5-sonnet-20240620'
24
+ # model = LiteLLMModel(model_id="gt-4o")
25
 
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  # If the agent does not answer, the model is overloaded, please use another model or the original Hugging Face Endpoint for contains qwen2.5 coder:
28
  # 'Qwen/Qwen2.5-Coder-32B-Instruct'
29
  model = HfApiModel(
 
33
  custom_role_conversions=None,
34
  )
35
 
36
+ # Init tools
37
+ final_answer = FinalAnswerTool()
38
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
39
  search_tool = DuckDuckGoSearchTool()
40
 
 
53
  get_joke,
54
  get_random_fact,
55
  search_wikipedia,
56
+ get_current_time_in_timezone
57
  ],
58
  max_steps=10,
59
  verbosity_level=4,
 
65
  )
66
 
67
 
68
+ GradioUI(agent).launch(share=True)