File size: 5,027 Bytes
32d4d45
9b5b26a
 
 
c19d193
6aae614
9b5b26a
 
32d4d45
9b5b26a
32d4d45
 
 
9b5b26a
32d4d45
 
9b5b26a
32d4d45
f665351
32d4d45
f665351
 
32d4d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
 
 
 
32d4d45
9b5b26a
 
 
 
 
 
 
 
 
 
 
8c01ffb
6aae614
ae7a494
d6266eb
e121372
32d4d45
 
d6266eb
32d4d45
13d500a
8c01ffb
9b5b26a
d6266eb
 
 
 
 
8c01ffb
861422e
 
32d4d45
d6266eb
 
 
 
 
8c01ffb
8fe992b
d6266eb
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
d6266eb
 
 
 
 
 
 
 
 
 
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
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from Gradio_UI import GradioUI

# Fully functional weather forecast tool
@tool
def get_weather_forecast(city: str, country_code: str = "") -> str:
    """A tool that fetches the current weather and forecast for a specified location.
    
    Args:
        city: The name of the city to get weather for (e.g., 'London', 'New York')
        country_code: Optional two-letter country code (e.g., 'US', 'UK', 'FR')
    """
    try:
        # WeatherAPI.com API endpoint and parameters
        # Note: In a real application, you should store API keys securely
        API_KEY =  "397ed132ff5643738fb112308252602"  # Replace with your actual API key
        base_url = "http://api.weatherapi.com/v1"
        
        # Build location string based on inputs
        location = city
        if country_code:
            location = f"{city},{country_code}"
            
        # Create request parameters
        params = {
            'q': location,
            'appid': API_KEY,
            'units': 'metric'  # Use metric units (Celsius)
        }
        
        # Make API request
        response = requests.get(base_url, params=params)
        response.raise_for_status()  # Raise exception for HTTP errors
        
        # Parse response
        weather_data = response.json()
        
        # Extract relevant information
        current_temp = weather_data['main']['temp']
        feels_like = weather_data['main']['feels_like']
        humidity = weather_data['main']['humidity']
        conditions = weather_data['weather'][0]['description']
        wind_speed = weather_data['wind']['speed']
        
        # Format and return results
        result = (
            f"Current Weather in {weather_data['name']}, {weather_data['sys']['country']}:\n"
            f"• Temperature: {current_temp}°C (feels like {feels_like}°C)\n"
            f"• Conditions: {conditions.capitalize()}\n"
            f"• Humidity: {humidity}%\n"
            f"• Wind Speed: {wind_speed} m/s"
        )
        
        return result
    
    except requests.exceptions.HTTPError as http_err:
        return f"HTTP Error occurred: {http_err}"
    except requests.exceptions.ConnectionError:
        return f"Connection Error: Unable to connect to weather service"
    except requests.exceptions.Timeout:
        return f"Timeout Error: Request timed out"
    except requests.exceptions.RequestException as err:
        return f"Error fetching weather data: {err}"
    except KeyError as key_err:
        return f"Error parsing weather data: {key_err}"
    except Exception as e:
        return f"Unexpected error: {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)}"

final_answer = FinalAnswerTool()

# Use the HF endpoint as suggested in the comment since there's an auth error with the direct model
model = HfApiModel(
    max_tokens=2096,
    temperature=0.5,
    model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',  # Using the suggested endpoint
    custom_role_conversions=None,
)

# Import tool from Hub
try:
    image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
except Exception as e:
    print(f"Warning: Could not load image generation tool: {e}")
    image_generation_tool = None

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

# Create a list of tools, only adding ones that are successfully loaded
tools = [final_answer, get_weather_forecast, get_current_time_in_timezone]
if image_generation_tool is not None:
    tools.append(image_generation_tool)

agent = CodeAgent(
    model=model,
    tools=tools,
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates
)

# Modified to handle potential errors in the Gradio UI
try:
    GradioUI(agent).launch()
except TypeError as e:
    if "unsupported operand type(s) for +=" in str(e):
        print("Warning: There seems to be an issue with token counting in the Gradio UI.")
        print("This could be due to the model not properly returning token count information.")
        print("Consider modifying the Gradio_UI.py file to handle None values for token counts.")
    else:
        raise