Spaces:
Sleeping
Sleeping
| from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool | |
| import datetime | |
| import requests | |
| import pytz | |
| import yaml | |
| import random | |
| import math | |
| import yfinance as yf | |
| from forex_python.converter import CurrencyRates | |
| from tools.final_answer import FinalAnswerTool | |
| from Gradio_UI import GradioUI | |
| # Example of a custom tool | |
| def my_custom_tool(arg1: str, arg2: int) -> str: | |
| """A tool that does nothing yet | |
| Args: | |
| arg1: the first argument | |
| arg2: the second argument | |
| """ | |
| return "What magic will you build?" | |
| def get_current_time_in_timezone(timezone: str) -> str: | |
| """Fetches the current local time in a specified timezone. | |
| Args: | |
| timezone: A string representing a valid timezone (e.g., 'America/New_York'). | |
| """ | |
| try: | |
| tz = pytz.timezone(timezone) | |
| local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") | |
| return f"The current local time in {timezone} is: {local_time}" | |
| except Exception as e: | |
| return f"Error fetching time for timezone '{timezone}': {str(e)}" | |
| def calculator(expression: str) -> str: | |
| """Evaluates a mathematical expression and returns the result. | |
| Args: | |
| expression: A string representing a valid mathematical expression (e.g., '2 + 3 * 4'). | |
| """ | |
| try: | |
| result = eval(expression, {"__builtins__": None}, {"math": math}) | |
| return f"The result of {expression} is: {result}" | |
| except Exception as e: | |
| return f"Error evaluating expression '{expression}': {str(e)}" | |
| def python_repl(command: str) -> str: | |
| """Executes a Python command in a safe restricted environment. | |
| Args: | |
| command: A string representing a Python command (e.g., '2 ** 10'). | |
| """ | |
| try: | |
| result = eval(command, {"__builtins__": None}, {"math": math}) | |
| return f"Execution result: {result}" | |
| except Exception as e: | |
| return f"Error executing command '{command}': {str(e)}" | |
| def unit_converter(value: float, from_unit: str, to_unit: str) -> str: | |
| """Converts a given value from one unit to another (supports length and weight). | |
| Args: | |
| value: The numerical value to be converted. | |
| from_unit: The unit to convert from (e.g., 'm', 'km', 'lb', 'kg'). | |
| to_unit: The unit to convert to. | |
| """ | |
| conversions = { | |
| ('m', 'km'): lambda x: x / 1000, | |
| ('km', 'm'): lambda x: x * 1000, | |
| ('lb', 'kg'): lambda x: x * 0.453592, | |
| ('kg', 'lb'): lambda x: x / 0.453592, | |
| } | |
| try: | |
| result = conversions[(from_unit, to_unit)](value) | |
| return f"{value} {from_unit} is equal to {result} {to_unit}" | |
| except KeyError: | |
| return "Conversion not supported." | |
| def stock_price_lookup(ticker: str) -> str: | |
| """Fetches the latest stock price for a given ticker symbol. | |
| Args: | |
| ticker: The stock ticker symbol (e.g., 'AAPL' for Apple Inc.). | |
| """ | |
| try: | |
| stock = yf.Ticker(ticker) | |
| price = stock.history(period='1d')['Close'].iloc[-1] | |
| return f"The latest stock price of {ticker} is ${price:.2f}" | |
| except Exception as e: | |
| return f"Error fetching stock price for {ticker}: {str(e)}" | |
| def currency_converter(amount: float, from_currency: str, to_currency: str) -> str: | |
| """Converts currency based on the latest exchange rates. | |
| Args: | |
| amount: The amount of money to be converted. | |
| from_currency: The currency to convert from (e.g., 'USD'). | |
| to_currency: The currency to convert to (e.g., 'EUR'). | |
| """ | |
| try: | |
| c = CurrencyRates() | |
| converted_amount = c.convert(from_currency, to_currency, amount) | |
| return f"{amount} {from_currency} is equal to {converted_amount:.2f} {to_currency}" | |
| except Exception as e: | |
| return f"Error converting currency from {from_currency} to {to_currency}: {str(e)}" | |
| final_answer = FinalAnswerTool() | |
| model = HfApiModel( | |
| max_tokens=2096, | |
| temperature=0.5, | |
| model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud', | |
| custom_role_conversions=None, | |
| ) | |
| # Import tool from Hub | |
| image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) | |
| with open("prompts.yaml", 'r') as stream: | |
| prompt_templates = yaml.safe_load(stream) | |
| agent = CodeAgent( | |
| model=model, | |
| tools=[final_answer, calculator, python_repl, unit_converter, stock_price_lookup, currency_converter], | |
| max_steps=6, | |
| verbosity_level=1, | |
| grammar=None, | |
| planning_interval=None, | |
| name=None, | |
| description=None, | |
| prompt_templates=prompt_templates | |
| ) | |
| GradioUI(agent).launch() | |