File size: 4,609 Bytes
6d9a52c
9b5b26a
 
 
c19d193
b82d8a3
6d9a52c
9b5b26a
 
b82d8a3
 
12e7fda
 
 
 
b82d8a3
 
12e7fda
 
 
b82d8a3
 
12e7fda
 
 
b82d8a3
 
12e7fda
 
6d9a52c
12e7fda
6d9a52c
12e7fda
b82d8a3
 
12e7fda
 
 
 
 
 
b82d8a3
12e7fda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b82d8a3
12e7fda
 
b82d8a3
 
6d9a52c
9b5b26a
6d9a52c
9b5b26a
 
 
 
 
6d9a52c
 
9b5b26a
6d9a52c
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
 
6d9a52c
 
 
 
 
 
 
12e7fda
 
6d9a52c
 
 
6aae614
6d9a52c
 
e121372
6d9a52c
 
12e7fda
6d9a52c
13d500a
8c01ffb
6d9a52c
9b5b26a
8c01ffb
6d9a52c
861422e
 
6d9a52c
 
8c01ffb
8fe992b
b82d8a3
6d9a52c
 
 
 
b82d8a3
 
8c01ffb
 
 
 
b82d8a3
 
861422e
8fe992b
 
6d9a52c
12e7fda
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
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
import os
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI


# Define a new tool: Weather Information Fetcher
import os
import requests
from smolagents import tool

@tool
def get_weather(city: str) -> str:
    """
    Fetches the current weather information for a given city.

    Args:
        city: The name of the city (e.g., 'New York').

    Returns:
        str: A formatted weather report including temperature, humidity, and conditions.
    """
    try:
        # 🔒 Get API key from environment variable (NEVER hardcode it)
        api_key = "39ed1534532b15efbf0fb9dfffc55298" #os.getenv("OPENWEATHERMAP_API_KEY")
        if not api_key:
            return "Error: API key is missing. Please set OPENWEATHERMAP_API_KEY as an environment variable."
        
        # 🌍 Build the API request URL
        url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
        
        # 📡 Fetch data from OpenWeather API
        response = requests.get(url)
        
        # ❌ Handle HTTP request failure
        if response.status_code != 200:
            return f"Error: Unable to fetch weather data. HTTP Status: {response.status_code}"
        
        # 📜 Parse JSON response
        data = response.json()
        
        # ❌ Handle API-level error (e.g., city not found)
        if data.get("cod") != 200:
            return f"Error fetching weather: {data.get('message', 'Unknown error')}"

        # 🌡️ Extract weather details
        weather_desc = data["weather"][0]["description"].capitalize()
        temp = data["main"]["temp"]
        pressure = data["main"]["pressure"]
        humidity = data["main"]["humidity"]
        wind_speed = data["wind"]["speed"]

        # 📝 Format the response
        return (
            f"🌍 **Weather in {city}**:\n"
            f"- 🌤 **Condition:** {weather_desc}\n"
            f"- 🌡 **Temperature:** {temp}°C\n"
            f"- 💨 **Wind Speed:** {wind_speed} m/s\n"
            f"- 💧 **Humidity:** {humidity}%\n"
            f"- 🏋 **Pressure:** {pressure} hPa"
        )

    except Exception as e:
        return f"⚠️ Error fetching weather for '{city}': {str(e)}"



# Define a custom tool
@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?"


# Define a timezone-aware clock tool
@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)}"


# Define web search tool
@tool
def web_search(query: str) -> str:
    """A tool that searches the web using DuckDuckGo.
    Args:
        query: The search query.
    """
    return DuckDuckGoSearchTool().forward(query)  # ✅ Correct: Calls `.forward(query)`



# Load final answer tool
final_answer = FinalAnswerTool()

# Hugging Face model setup
model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='deepseek-ai/DeepSeek-R1-Distill-Qwen-32B',
    custom_role_conversions=None,
)

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

# Load prompt templates
with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)

# Initialize the agent with multiple tools
agent = CodeAgent(
    model=model,
    tools=[
        final_answer,
        web_search,  # Enables web search via DuckDuckGo
        image_generation_tool,  # Enables text-to-image generation
        get_weather,  # Enables weather fetching
        get_current_time_in_timezone,  # Enables timezone-based time retrieval
    ],
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name="Enhanced CodeAgent",
    description="An AI agent with web search, image generation, weather, and timezone utilities.",
    prompt_templates=prompt_templates
)

# Launch Gradio UI
GradioUI(agent).launch()