File size: 4,616 Bytes
654683e
9b5b26a
 
 
c19d193
654683e
 
 
 
6aae614
9b5b26a
 
654683e
 
9b5b26a
 
 
 
 
654683e
9b5b26a
 
 
654683e
9b5b26a
 
 
 
 
 
 
 
 
8c01ffb
654683e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
6aae614
e121372
654683e
 
 
 
13d500a
8c01ffb
9b5b26a
 
8c01ffb
861422e
 
9b5b26a
8c01ffb
8fe992b
654683e
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
654683e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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?"

@tool
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)}"

@tool
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)}"

@tool
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)}"

@tool
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."

@tool
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)}"

@tool
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()