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

Create tools.py

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