File size: 6,004 Bytes
1f0fe58
22f1261
 
 
 
 
 
 
 
 
 
 
 
 
8fe992b
22f1261
9b5b26a
67f10b6
22f1261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
22f1261
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
 
6aae614
ae7a494
 
22f1261
ae7a494
e121372
22f1261
 
 
 
13d500a
8c01ffb
 
9b5b26a
 
8c01ffb
861422e
 
22f1261
8c01ffb
8fe992b
22f1261
 
 
 
 
 
 
 
 
8c01ffb
 
 
 
 
 
22f1261
8fe992b
 
9b5b26a
22f1261
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
166

from smolagents import (
    CodeAgent,
    DuckDuckGoSearchTool,
    VisitWebpageTool,
    HfApiModel,
    load_tool,
    tool,
)
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool

from Gradio_UI import GradioUI


# ---------------------------------------------------------------------------
# Custom tool 1: Real-time weather (Open-Meteo — free, no API key required)
# ---------------------------------------------------------------------------
@tool
def get_weather(city: str) -> str:
    """Get the current weather for a given city.
    Args:
        city: the name of the city (e.g. 'Paris', 'New York').
    """
    try:
        # 1) Geocode the city name into lat/lon
        geo = requests.get(
            "https://geocoding-api.open-meteo.com/v1/search",
            params={"name": city, "count": 1, "language": "en", "format": "json"},
            timeout=15,
        ).json()
        if not geo.get("results"):
            return f"Could not find a city named '{city}'."
        loc = geo["results"][0]
        lat, lon = loc["latitude"], loc["longitude"]

        # 2) Fetch current weather at that location
        weather = requests.get(
            "https://api.open-meteo.com/v1/forecast",
            params={
                "latitude": lat,
                "longitude": lon,
                "current_weather": "true",
                "timezone": "auto",
            },
            timeout=15,
        ).json()

        cur = weather.get("current_weather", {})
        temp_c = cur.get("temperature")
        windspeed = cur.get("windspeed")
        wmo = cur.get("weathercode", 0)

        # Map WMO weather codes to readable descriptions
        descriptions = {
            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", 73: "moderate snow", 75: "heavy snow",
            80: "slight rain showers", 81: "moderate rain showers", 82: "violent rain showers",
            95: "thunderstorm", 96: "thunderstorm with slight hail", 99: "thunderstorm with heavy hail",
        }
        desc = descriptions.get(wmo, "unknown conditions")

        return (
            f"Current weather in {loc['name']}: {desc}, "
            f"{temp_c}°C, wind {windspeed} km/h."
        )
    except Exception as e:
        return f"Error fetching weather for '{city}': {str(e)}"


# ---------------------------------------------------------------------------
# Custom tool 2: Currency converter (free exchange-rate API, no key needed)
# ---------------------------------------------------------------------------
@tool
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
    """Convert an amount from one currency to another.
    Args:
        amount: the amount of money to convert.
        from_currency: the source currency code (e.g. 'USD').
        to_currency: the target currency code (e.g. 'EUR').
    """
    try:
        rates = requests.get(
            "https://open.er-api.com/v6/latest",
            params={"base": from_currency.upper()},
            timeout=15,
        ).json()
        if rates.get("result") != "success":
            return f"Could not fetch rates for '{from_currency}'."
        rate = rates["rates"].get(to_currency.upper())
        if rate is None:
            return f"Unknown currency code '{to_currency}'."
        converted = amount * rate
        return (
            f"{amount} {from_currency.upper()} = {converted:.2f} "
            f"{to_currency.upper()} (rate {rate:.4f})"
        )
    except Exception as e:
        return f"Error converting currency: {str(e)}"


# ---------------------------------------------------------------------------
# Existing tools
# ---------------------------------------------------------------------------
@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:
        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)}"


final_answer = FinalAnswerTool()

# If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'

model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='Qwen/Qwen2.5-Coder-32B-Instruct',  # it is possible that this model may be overloaded
    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,                     # don't remove
        DuckDuckGoSearchTool(),           # web search (was imported but never added!)
        VisitWebpageTool(),               # read the pages the search finds
        image_generation_tool,            # text-to-image (was loaded but never added!)
        get_current_time_in_timezone,     # current local time in any timezone
        get_weather,                      # real-time weather by city
        convert_currency,                 # currency conversion
    ],
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates,
)


GradioUI(agent).launch()