File size: 4,721 Bytes
7aa4ec8
9b5b26a
 
 
c19d193
7aa4ec8
6aae614
6dcbbf7
9b5b26a
 
6dcbbf7
9b5b26a
7aa4ec8
5233a17
 
9b5b26a
5233a17
9b5b26a
6dcbbf7
 
 
7aa4ec8
5233a17
 
 
 
 
6dcbbf7
5233a17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
 
 
 
7aa4ec8
9b5b26a
 
 
 
 
 
 
 
 
 
 
8c01ffb
6dcbbf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aae614
ae7a494
e121372
7aa4ec8
 
6dcbbf7
7aa4ec8
13d500a
8c01ffb
9b5b26a
 
8c01ffb
6dcbbf7
861422e
 
6dcbbf7
8c01ffb
8fe992b
7aa4ec8
6dcbbf7
 
 
 
 
 
7aa4ec8
8c01ffb
 
 
 
 
 
d408435
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
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

# Weather tool that securely handles the API key
@tool
def get_weather(city: str) -> str:
    """A tool that fetches current weather data for a specified city.
    
    Args:
        city: The name of the city to get weather for (e.g., 'London', 'New York')
    """
    # In production, use: api_key = os.environ.get("OPENWEATHER_API_KEY")
    # For this example, we'll use a direct string (replace with your key)
    api_key = "2dfcb906753cbf580f5a027ebe974842"
    
    try:
        # Construct the API URL
        base_url = "https://api.openweathermap.org/data/2.5/weather"
        params = {
            "q": city,
            "appid": api_key,  # Now properly as a string
            "units": "metric"  # For temperature in Celsius
        }
        
        # Send the request
        response = requests.get(base_url, params=params)
        data = response.json()
        
        # Check if the request was successful
        if response.status_code == 200:
            # Extract relevant weather information
            weather_desc = data["weather"][0]["description"]
            temperature = data["main"]["temp"]
            humidity = data["main"]["humidity"]
            wind_speed = data["wind"]["speed"]
            
            # Format the weather information
            weather_info = f"Current weather in {city}:\n"
            weather_info += f"- Condition: {weather_desc.capitalize()}\n"
            weather_info += f"- Temperature: {temperature}°C\n"
            weather_info += f"- Humidity: {humidity}%\n"
            weather_info += f"- Wind Speed: {wind_speed} m/s"
            
            return weather_info
        else:
            return f"Error: Could not retrieve weather data for {city}. Status code: {response.status_code}. Message: {data.get('message', 'Unknown error')}"
    
    except Exception as e:
        return f"Error fetching weather data: {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)}"

# Simple calculator tool as an additional example
@tool
def simple_calculator(operation: str, num1: float, num2: float) -> str:
    """A tool that performs basic arithmetic operations on two numbers.
    
    Args:
        operation: The operation to perform ('add', 'subtract', 'multiply', 'divide')
        num1: The first number
        num2: The second number
    """
    operation = operation.lower()
    
    if operation == "add":
        result = num1 + num2
        return f"{num1} + {num2} = {result}"
    elif operation == "subtract":
        result = num1 - num2
        return f"{num1} - {num2} = {result}"
    elif operation == "multiply":
        result = num1 * num2
        return f"{num1} * {num2} = {result}"
    elif operation == "divide":
        if num2 == 0:
            return "Error: Cannot divide by zero"
        result = num1 / num2
        return f"{num1} / {num2} = {result}"
    else:
        return "Invalid operation. Please use 'add', 'subtract', 'multiply', or 'divide'."

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)

# Load system prompt from prompt.yaml file
with open("prompts.yaml", 'r') as stream:
    prompt_templates = yaml.safe_load(stream)
    
agent = CodeAgent(
    model=model,
    tools=[
        final_answer,  # Don't remove this
        get_weather,  # Weather information tool
        get_current_time_in_timezone,  # Timezone tool
        image_generation_tool,  # Image generation
        DuckDuckGoSearchTool(),  # Web search capability
        simple_calculator  # Basic calculator
    ],
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=None
)

GradioUI(agent).launch()