import requests import os import smolagents from smolagents.tools import Tool # y obtener tu clave API para usar este código. API_KEY = os.getenv("EXCHANGE_RATE_API_KEY") # Read from environment variable BASE_URL = "https://api.currencyfreaks.com/v2.0/rates/latest" class ExchangeRatesTool(Tool): name = "exchange_rates" description = "Converts an amount from one currency to another using the latest exchange rates." inputs = {'amount': {'type': 'number', 'description': 'The amount to convert.'}, 'from_currency': {'type': 'string', 'description': 'The currency to convert from.'}, 'to_currency': {'type': 'string', 'description': 'The currency to convert to.'}} output_type = "number" def forward(self, amount: float, from_currency: str, to_currency: str) -> float: result = currency_converter(amount, from_currency, to_currency) if isinstance(result, float): return result else: raise Exception(result) def currency_converter(amount: float, from_currency: str, to_currency: str) -> float | str: """Convierte un monto dado de una divisa a otra usando tipos de cambio en tiempo real. Args: amount: La cantidad de dinero a convertir (e.g., 100.0). from_currency: El código de la divisa de origen (e.g., "USD"). to_currency: El código de la divisa de destino (e.g., "EUR"). """ try: # CurrencyFreaks API provides rates relative to USD by default. url = f"{BASE_URL}?apikey={API_KEY}" response = requests.get(url) response.raise_for_status() # Lanza un error para códigos de estado HTTP malos data = response.json() rates = data.get("rates") from_currency_upper = from_currency.upper() to_currency_upper = to_currency.upper() # Validate if API_KEY is missing or rates are not found if not API_KEY: return "Error: La clave API no está configurada. Por favor, asegúrate de que EXCHANGE_RATE_API_KEY esté en tus variables de entorno." if not rates: return "Error: No se pudieron obtener las tasas de cambio de la API." # Handle USD as a special case, as it's the base if from_currency_upper == "USD": from_usd_rate = 1.0 elif from_currency_upper in rates: from_usd_rate = float(rates[from_currency_upper]) else: return f"Error: No se encontró la tasa de conversión para la divisa de origen '{from_currency_upper}'." if to_currency_upper == "USD": to_usd_rate = 1.0 elif to_currency_upper in rates: to_usd_rate = float(rates[to_currency_upper]) else: return f"Error: No se encontró la tasa de conversión para la divisa de destino '{to_currency_upper}'." # Convert 'amount' from 'from_currency' to USD amount_in_usd = amount / from_usd_rate # Convert amount in USD to 'to_currency' converted_amount = amount_in_usd * to_usd_rate return converted_amount except requests.exceptions.HTTPError as e: return f"Error HTTP al obtener tasas: {e}" except Exception as e: return f"Ocurrió un error inesperado: {str(e)}"