File size: 6,417 Bytes
cd463a6
9b5b26a
 
 
c19d193
cd463a6
6aae614
9b5b26a
 
cd463a6
c789d64
cd463a6
 
9b5b26a
cd463a6
9b5b26a
cd463a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
c789d64
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
c789d64
cd463a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
c789d64
cd463a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae7a494
cd463a6
e121372
cd463a6
 
 
 
13d500a
8c01ffb
9b5b26a
 
cd463a6
8c01ffb
861422e
 
9b5b26a
8c01ffb
8fe992b
cd463a6
 
 
 
 
 
 
 
 
8c01ffb
 
 
 
79d039a
 
861422e
8fe992b
 
8c01ffb
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
import json
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI

# Weather API Tool
@tool
def get_weather(location: str) -> str:
    """A tool that fetches current weather for a specified location.
    Args:
        location: A string representing a city or location (e.g., 'New York', 'London, UK').
    """
    try:
        # Using open-meteo API which doesn't require API key
        # First get coordinates
        geocoding_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1"
        geocoding_response = requests.get(geocoding_url)
        geocoding_data = geocoding_response.json()
        
        if not geocoding_data.get("results"):
            return f"Could not find location: {location}"
            
        lat = geocoding_data["results"][0]["latitude"]
        lon = geocoding_data["results"][0]["longitude"]
        city_name = geocoding_data["results"][0]["name"]
        
        # Now get weather
        weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}&current=temperature_2m,wind_speed_10m,relative_humidity_2m,precipitation,weather_code"
        weather_response = requests.get(weather_url)
        weather_data = weather_response.json()
        
        current = weather_data["current"]
        temperature = current["temperature_2m"]
        wind_speed = current["wind_speed_10m"]
        humidity = current["relative_humidity_2m"]
        precipitation = current["precipitation"]
        
        # Weather code to text mapping
        weather_codes = {
            0: "Clear sky",
            1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
            45: "Fog", 48: "Depositing rime fog",
            51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle",
            61: "Slight rain", 63: "Moderate rain", 65: "Heavy rain",
            71: "Slight snow fall", 73: "Moderate snow fall", 75: "Heavy snow fall",
            80: "Slight rain showers", 81: "Moderate rain showers", 82: "Violent rain showers",
            95: "Thunderstorm", 96: "Thunderstorm with slight hail", 99: "Thunderstorm with heavy hail"
        }
        
        weather_description = weather_codes.get(current["weather_code"], "Unknown")
        
        return f"Current weather in {city_name}: {weather_description}, {temperature}°C, {wind_speed}km/h wind, {humidity}% humidity, {precipitation}mm precipitation"
    
    except Exception as e:
        return f"Error fetching weather for '{location}': {str(e)}"

@tool
def get_current_time_in_timezone(timezone: str) -> str:
    """A tool that fetches the current local time in a specified timezone.
    Args:
        timezone: A string representing a valid timezone (e.g., 'America/New_York').
    """
    try:
        # Create timezone object
        tz = pytz.timezone(timezone)
        # Get current time in that 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 currency_converter(amount: float, from_currency: str, to_currency: str) -> str:
    """A tool that converts an amount from one currency to another using latest exchange rates.
    Args:
        amount: The amount to convert
        from_currency: The source currency code (e.g., 'USD')
        to_currency: The target currency code (e.g., 'EUR')
    """
    try:
        # Using ExchangeRate API
        url = f"https://open.er-api.com/v6/latest/{from_currency.upper()}"
        response = requests.get(url)
        data = response.json()
        
        if data["result"] != "success":
            return f"Error: Could not fetch exchange rates for {from_currency}"
            
        if to_currency.upper() not in data["rates"]:
            return f"Error: Target currency {to_currency} not found"
            
        rate = data["rates"][to_currency.upper()]
        converted_amount = amount * rate
        
        return f"{amount} {from_currency.upper()} = {converted_amount:.2f} {to_currency.upper()} (Rate: 1 {from_currency.upper()} = {rate} {to_currency.upper()})"
    
    except Exception as e:
        return f"Error converting currency: {str(e)}"

@tool
def stock_price_lookup(ticker: str) -> str:
    """A tool that looks up the latest stock price for a given ticker symbol.
    Args:
        ticker: The stock ticker symbol (e.g., 'AAPL' for Apple Inc.)
    """
    try:
        # Using Alpha Vantage API (free tier, limited to 25 requests per day)
        # Note: In a production environment, you'd want to use a proper API key
        url = f"https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol={ticker}&apikey=demo"
        response = requests.get(url)
        data = response.json()
        
        if "Global Quote" not in data or not data["Global Quote"]:
            return f"Could not find data for ticker: {ticker}"
            
        quote = data["Global Quote"]
        price = quote.get("05. price", "N/A")
        change = quote.get("09. change", "N/A")
        change_percent = quote.get("10. change percent", "N/A")
        
        return f"{ticker} current price: ${price} (Change: {change} / {change_percent})"
    
    except Exception as e:
        return f"Error looking up stock price for '{ticker}': {str(e)}"

final_answer = FinalAnswerTool()
model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
    custom_role_conversions=None,
)

# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
search_tool = DuckDuckGoSearchTool()

with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)
    
agent = CodeAgent(
    model=model,
    tools=[
        final_answer,
        get_current_time_in_timezone,
        get_weather,
        currency_converter,
        stock_price_lookup,
        image_generation_tool,
        search_tool
    ],
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates
)

GradioUI(agent).launch()