EmincanY commited on
Commit
8f5e5c3
·
verified ·
1 Parent(s): ae7a494

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -2
app.py CHANGED
@@ -3,10 +3,20 @@ import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
 
6
  from tools.final_answer import FinalAnswerTool
7
-
 
 
 
 
 
8
  from Gradio_UI import GradioUI
9
 
 
 
 
10
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
  def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
@@ -33,6 +43,139 @@ def get_current_time_in_timezone(timezone: str) -> str:
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  final_answer = FinalAnswerTool()
38
 
@@ -55,7 +198,15 @@ with open("prompts.yaml", 'r') as stream:
55
 
56
  agent = CodeAgent(
57
  model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
 
 
 
 
 
 
 
 
59
  max_steps=6,
60
  verbosity_level=1,
61
  grammar=None,
 
3
  import requests
4
  import pytz
5
  import yaml
6
+ import os
7
+ from dotenv import load_dotenv
8
  from tools.final_answer import FinalAnswerTool
9
+ import wikipediaapi
10
+ from newsapi import NewsApiClient
11
+ from forex_python.converter import CurrencyRates
12
+ import sympy
13
+ import random
14
+ import string
15
  from Gradio_UI import GradioUI
16
 
17
+ # Load environment variables
18
+ load_dotenv()
19
+
20
  # Below is an example of a tool that does nothing. Amaze us with your creativity !
21
  @tool
22
  def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
 
43
  except Exception as e:
44
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
45
 
46
+ @tool
47
+ def get_weather(city: str) -> str:
48
+ """Get current weather information for a specified city
49
+ Args:
50
+ city: Name of the city to get weather for
51
+ """
52
+ # Using OpenWeatherMap API
53
+ API_KEY = os.getenv("OPENWEATHERMAP_API_KEY")
54
+ if not API_KEY:
55
+ return "Error: OpenWeatherMap API key not found in environment variables"
56
+
57
+ base_url = "http://api.openweathermap.org/data/2.5/weather"
58
+
59
+ try:
60
+ params = {
61
+ 'q': city,
62
+ 'appid': API_KEY,
63
+ 'units': 'metric' # For Celsius
64
+ }
65
+ response = requests.get(base_url, params=params)
66
+ data = response.json()
67
+
68
+ if response.status_code == 200:
69
+ temp = data['main']['temp']
70
+ humidity = data['main']['humidity']
71
+ description = data['weather'][0]['description']
72
+ return f"Weather in {city}: Temperature: {temp}°C, Humidity: {humidity}%, Conditions: {description}"
73
+ else:
74
+ return f"Error getting weather: {data.get('message', 'Unknown error')}"
75
+ except Exception as e:
76
+ return f"Error: {str(e)}"
77
+
78
+ @tool
79
+ def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
80
+ """Convert an amount from one currency to another
81
+ Args:
82
+ amount: Amount to convert
83
+ from_currency: Source currency code (e.g., USD)
84
+ to_currency: Target currency code (e.g., EUR)
85
+ """
86
+ try:
87
+ c = CurrencyRates()
88
+ result = c.convert(from_currency.upper(), to_currency.upper(), amount)
89
+ return f"{amount} {from_currency.upper()} = {result:.2f} {to_currency.upper()}"
90
+ except Exception as e:
91
+ return f"Error converting currency: {str(e)}"
92
+
93
+ @tool
94
+ def get_news_headlines(topic: str, count: int = 5) -> str:
95
+ """Get latest news headlines for a specific topic
96
+ Args:
97
+ topic: Topic to search news for
98
+ count: Number of headlines to return (default: 5)
99
+ """
100
+ API_KEY = os.getenv("NEWSAPI_KEY")
101
+ if not API_KEY:
102
+ return "Error: NewsAPI key not found in environment variables"
103
+
104
+ newsapi = NewsApiClient(api_key=API_KEY)
105
+
106
+ try:
107
+ news = newsapi.get_everything(q=topic, language='en', sort_by='publishedAt', page_size=count)
108
+ if news['articles']:
109
+ headlines = []
110
+ for idx, article in enumerate(news['articles'][:count], 1):
111
+ headlines.append(f"{idx}. {article['title']} ({article['source']['name']})")
112
+ return "\n".join(headlines)
113
+ return f"No news found for topic: {topic}"
114
+ except Exception as e:
115
+ return f"Error fetching news: {str(e)}"
116
+
117
+ @tool
118
+ def get_wikipedia_summary(topic: str) -> str:
119
+ """Get a summary of a Wikipedia article
120
+ Args:
121
+ topic: Topic to get summary for
122
+ """
123
+ wiki = wikipediaapi.Wikipedia('en')
124
+ try:
125
+ page = wiki.page(topic)
126
+ if page.exists():
127
+ # Get first two sentences or first 500 characters, whichever is shorter
128
+ summary = page.summary[:500]
129
+ if len(summary) == 500:
130
+ summary = summary[:summary.rindex('.')] + '.'
131
+ return summary
132
+ return f"No Wikipedia article found for: {topic}"
133
+ except Exception as e:
134
+ return f"Error fetching Wikipedia summary: {str(e)}"
135
+
136
+ @tool
137
+ def solve_math_expression(expression: str) -> str:
138
+ """Solve a mathematical expression
139
+ Args:
140
+ expression: Mathematical expression as string
141
+ """
142
+ try:
143
+ # Convert string to sympy expression
144
+ expr = sympy.sympify(expression)
145
+ result = expr.evalf()
146
+ return f"Result: {result}"
147
+ except Exception as e:
148
+ return f"Error solving expression: {str(e)}"
149
+
150
+ @tool
151
+ def generate_password(length: int = 12, include_special: bool = True) -> str:
152
+ """Generate a secure random password
153
+ Args:
154
+ length: Length of password (default: 12)
155
+ include_special: Include special characters (default: True)
156
+ """
157
+ try:
158
+ if length < 8:
159
+ return "Password length must be at least 8 characters"
160
+
161
+ chars = string.ascii_letters + string.digits
162
+ if include_special:
163
+ chars += string.punctuation
164
+
165
+ password = ''.join(random.choice(chars) for _ in range(length))
166
+
167
+ # Ensure password contains at least one of each required type
168
+ if not any(c.isupper() for c in password):
169
+ password = random.choice(string.ascii_uppercase) + password[1:]
170
+ if not any(c.islower() for c in password):
171
+ password = password[:-1] + random.choice(string.ascii_lowercase)
172
+ if not any(c.isdigit() for c in password):
173
+ pos = random.randint(1, len(password)-2)
174
+ password = password[:pos] + random.choice(string.digits) + password[pos+1:]
175
+
176
+ return f"Generated password: {password}"
177
+ except Exception as e:
178
+ return f"Error generating password: {str(e)}"
179
 
180
  final_answer = FinalAnswerTool()
181
 
 
198
 
199
  agent = CodeAgent(
200
  model=model,
201
+ tools=[
202
+ final_answer,
203
+ get_weather,
204
+ convert_currency,
205
+ get_news_headlines,
206
+ get_wikipedia_summary,
207
+ solve_math_expression,
208
+ generate_password
209
+ ],
210
  max_steps=6,
211
  verbosity_level=1,
212
  grammar=None,