Quivering commited on
Commit
070c855
·
verified ·
1 Parent(s): 180099a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +178 -2
app.py CHANGED
@@ -6,6 +6,9 @@ import yaml
6
  import os
7
  from tools.final_answer import FinalAnswerTool
8
  from Gradio_UI import GradioUI
 
 
 
9
 
10
  # Set up OpenWeather API key
11
  OPENWEATHER_API_KEY = os.getenv('OPENWEATHER_API_KEY', 'your_api_key_here')
@@ -42,6 +45,178 @@ def get_weather_info(city: str) -> str:
42
  f"Wind Speed: {wind_speed} m/s")
43
  except Exception as e:
44
  return f"Error fetching weather for city '{city}': {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  @tool
47
  def get_current_time_in_timezone(timezone: str) -> str:
@@ -85,14 +260,15 @@ agent = CodeAgent(
85
  search_tool,
86
  image_generation_tool,
87
  get_current_time_in_timezone,
88
- get_weather_info
 
89
  ],
90
  max_steps=6,
91
  verbosity_level=1,
92
  grammar=None,
93
  planning_interval=None,
94
  name="Multi-tool Assistant",
95
- description="An agent capable of searching, generating images, checking time zones, and getting weather information.",
96
  prompt_templates=prompt_templates
97
  )
98
 
 
6
  import os
7
  from tools.final_answer import FinalAnswerTool
8
  from Gradio_UI import GradioUI
9
+ from typing import Optional, List
10
+ import requests
11
+ from datetime import datetime, timedelta
12
 
13
  # Set up OpenWeather API key
14
  OPENWEATHER_API_KEY = os.getenv('OPENWEATHER_API_KEY', 'your_api_key_here')
 
45
  f"Wind Speed: {wind_speed} m/s")
46
  except Exception as e:
47
  return f"Error fetching weather for city '{city}': {str(e)}"
48
+ @tool
49
+ def crypto_tracker(action: str, crypto_id: Optional[str] = None) -> str:
50
+ """Tracks cryptocurrency prices and changes using CoinGecko API
51
+ Args:
52
+ action: The action to perform ('price', 'top', 'detail', 'summary')
53
+ crypto_id: The cryptocurrency ID (e.g., 'bitcoin', 'ethereum') - required for 'price' and 'detail' actions
54
+ """
55
+ try:
56
+ base_url = "https://api.coingecko.com/api/v3"
57
+
58
+ def format_price_change(change: float) -> str:
59
+ """Format price change with color indicator"""
60
+ if change > 0:
61
+ return f"↑ {change:.2f}%"
62
+ elif change < 0:
63
+ return f"↓ {change:.2f}%"
64
+ return f"{change:.2f}%"
65
+
66
+ if action == "top":
67
+ # Get top 10 cryptocurrencies by market cap
68
+ response = requests.get(
69
+ f"{base_url}/coins/markets",
70
+ params={
71
+ "vs_currency": "usd",
72
+ "order": "market_cap_desc",
73
+ "per_page": 10,
74
+ "page": 1,
75
+ "sparkline": False,
76
+ "price_change_percentage": "24h,7d"
77
+ }
78
+ )
79
+ response.raise_for_status()
80
+ data = response.json()
81
+
82
+ result = "Top 10 Cryptocurrencies:\n\n"
83
+ for coin in data:
84
+ result += (
85
+ f"📊 {coin['name']} ({coin['symbol'].upper()})\n"
86
+ f" Price: ${coin['current_price']:,.2f}\n"
87
+ f" 24h Change: {format_price_change(coin['price_change_percentage_24h'])}\n"
88
+ f" 7d Change: {format_price_change(coin['price_change_percentage_7d'])}\n"
89
+ f" Market Cap: ${coin['market_cap']:,.0f}\n\n"
90
+ )
91
+ return result
92
+
93
+ elif action == "price" and crypto_id:
94
+ # Get simple price data for a specific cryptocurrency
95
+ response = requests.get(
96
+ f"{base_url}/simple/price",
97
+ params={
98
+ "ids": crypto_id,
99
+ "vs_currencies": "usd",
100
+ "include_24hr_change": True,
101
+ "include_market_cap": True
102
+ }
103
+ )
104
+ response.raise_for_status()
105
+ data = response.json()
106
+
107
+ if crypto_id not in data:
108
+ return f"Cryptocurrency '{crypto_id}' not found"
109
+
110
+ coin_data = data[crypto_id]
111
+ return (
112
+ f"Current {crypto_id.title()} Price:\n"
113
+ f"USD: ${coin_data['usd']:,.2f}\n"
114
+ f"24h Change: {format_price_change(coin_data['usd_24h_change'])}\n"
115
+ f"Market Cap: ${coin_data['usd_market_cap']:,.0f}"
116
+ )
117
+
118
+ elif action == "detail" and crypto_id:
119
+ # Get detailed information about a specific cryptocurrency
120
+ response = requests.get(f"{base_url}/coins/{crypto_id}")
121
+ response.raise_for_status()
122
+ data = response.json()
123
+
124
+ market_data = data['market_data']
125
+ return (
126
+ f"📊 {data['name']} ({data['symbol'].upper()}) Detailed Report:\n\n"
127
+ f"Current Price: ${market_data['current_price']['usd']:,.2f}\n"
128
+ f"24h Change: {format_price_change(market_data['price_change_percentage_24h'])}\n"
129
+ f"7d Change: {format_price_change(market_data['price_change_percentage_7d'])}\n"
130
+ f"30d Change: {format_price_change(market_data['price_change_percentage_30d'])}\n"
131
+ f"Market Cap Rank: #{data['market_cap_rank']}\n"
132
+ f"Market Cap: ${market_data['market_cap']['usd']:,.0f}\n"
133
+ f"24h Trading Volume: ${market_data['total_volume']['usd']:,.0f}\n"
134
+ f"Circulating Supply: {market_data['circulating_supply']:,.0f} {data['symbol'].upper()}\n"
135
+ f"All-Time High: ${market_data['ath']['usd']:,.2f} ({market_data['ath_date']['usd'][:10]})\n"
136
+ f"All-Time Low: ${market_data['atl']['usd']:,.2f} ({market_data['atl_date']['usd'][:10]})\n\n"
137
+ f"Description: {data['description']['en'][:300]}..."
138
+ )
139
+
140
+ else:
141
+ elif action == "summary":
142
+ # Get 24-hour summary for top 5 cryptocurrencies
143
+ response = requests.get(
144
+ f"{base_url}/coins/markets",
145
+ params={
146
+ "vs_currency": "usd",
147
+ "order": "market_cap_desc",
148
+ "per_page": 5,
149
+ "page": 1,
150
+ "sparkline": False,
151
+ "price_change_percentage": "24h",
152
+ "include_24hr_vol": True
153
+ }
154
+ )
155
+ response.raise_for_status()
156
+ data = response.json()
157
+
158
+ total_market_change = sum(coin['price_change_percentage_24h'] for coin in data) / len(data)
159
+ total_volume = sum(coin['total_volume'] for coin in data)
160
+
161
+ summary = "🚀 24-Hour Crypto Market Summary\n\n"
162
+ summary += f"Overall Market Trend: {format_price_change(total_market_change)} (Top 5 Average)\n"
163
+ summary += f"Total Trading Volume: ${total_volume:,.0f}\n\n"
164
+ summary += "Top 5 Cryptocurrency Performance:\n\n"
165
+
166
+ for coin in data:
167
+ price_change = coin['price_change_percentage_24h']
168
+ volume_change = (coin['total_volume'] / coin['market_cap']) * 100 # Volume/Market Cap ratio
169
+
170
+ # Determine market sentiment
171
+ if price_change > 5:
172
+ sentiment = "🔥 Strong Bullish"
173
+ elif price_change > 2:
174
+ sentiment = "📈 Bullish"
175
+ elif price_change < -5:
176
+ sentiment = "💧 Strong Bearish"
177
+ elif price_change < -2:
178
+ sentiment = "📉 Bearish"
179
+ else:
180
+ sentiment = "➡️ Stable"
181
+
182
+ summary += (
183
+ f"{coin['name']} ({coin['symbol'].upper()}):\n"
184
+ f" Current Price: ${coin['current_price']:,.2f}\n"
185
+ f" 24h Change: {format_price_change(price_change)}\n"
186
+ f" 24h Volume: ${coin['total_volume']:,.0f}\n"
187
+ f" Volume/Market Cap: {volume_change:.2f}%\n"
188
+ f" Market Sentiment: {sentiment}\n\n"
189
+ )
190
+
191
+ # Add significant events or thresholds crossed
192
+ significant_events = []
193
+ for coin in data:
194
+ if abs(coin['price_change_percentage_24h']) > 10:
195
+ significant_events.append(
196
+ f"⚠️ {coin['name']} moved {format_price_change(coin['price_change_percentage_24h'])} in 24h"
197
+ )
198
+ if coin['current_price'] > coin.get('ath', float('inf')):
199
+ significant_events.append(f"🎉 {coin['name']} reached a new all-time high!")
200
+
201
+ if significant_events:
202
+ summary += "Significant Events:\n"
203
+ summary += "\n".join(f"• {event}" for event in significant_events)
204
+
205
+ return summary
206
+
207
+ else:
208
+ return ("Invalid action. Use:\n"
209
+ "'top' to see top 10 cryptocurrencies\n"
210
+ "'price <crypto_id>' to get current price (e.g., 'price bitcoin')\n"
211
+ "'detail <crypto_id>' to get detailed information\n"
212
+ "'summary' to get 24-hour summary of top 5 cryptocurrencies")
213
+
214
+ except requests.exceptions.RequestException as e:
215
+ return f"Error fetching cryptocurrency data: {str(e)}"
216
+ except KeyError as e:
217
+ return f"Error processing cryptocurrency data: {str(e)}"
218
+ except Exception as e:
219
+ return f"Unexpected error: {str(e)}"
220
 
221
  @tool
222
  def get_current_time_in_timezone(timezone: str) -> str:
 
260
  search_tool,
261
  image_generation_tool,
262
  get_current_time_in_timezone,
263
+ get_weather_info,
264
+ cryptotracker
265
  ],
266
  max_steps=6,
267
  verbosity_level=1,
268
  grammar=None,
269
  planning_interval=None,
270
  name="Multi-tool Assistant",
271
+ description="An agent capable of searching, generating images, checking time zones, checking crypto prices and getting weather information.",
272
  prompt_templates=prompt_templates
273
  )
274