File size: 8,758 Bytes
372e44f
9b5b26a
 
c19d193
6aae614
372e44f
8fe992b
9b5b26a
 
 
372e44f
c7fac19
372e44f
9b5b26a
c7fac19
9b5b26a
c7fac19
372e44f
 
 
 
 
 
c7fac19
372e44f
c7fac19
372e44f
 
c7fac19
372e44f
 
 
 
 
 
 
 
 
c7fac19
 
 
9b5b26a
372e44f
 
 
 
 
 
 
 
 
 
 
 
 
 
9b5b26a
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
c7fac19
372e44f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7fac19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c01ffb
6aae614
ae7a494
 
 
 
e121372
bf6d34c
 
29ec968
fe328e0
13d500a
8c01ffb
 
9b5b26a
 
8c01ffb
861422e
 
9b5b26a
8c01ffb
8fe992b
e2a35fa
8c01ffb
 
 
 
 
 
861422e
8fe992b
 
9b5b26a
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
import datetime
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
import re

from Gradio_UI import GradioUI

@tool
def get_current_weather(location: str) -> str:
    """
    Returns the weather report by querying Google Search using DuckDuckGo.
    Args:
        location: the name of the place that you want the weather for. Should be a place name, followed by possibly a city name, then a country, like "Anchor Point, Taghazout, Morocco".
    """
    try:
        # Get the current date and time from the machine
        date_time_obj = datetime.datetime.now()

        # Convert the current datetime object to the desired string format
        date_time_str = date_time_obj.strftime("%m/%d/%y %H:%M:%S")

    except Exception as e:
        return f"Failed to get current date and time. Error: {str(e)}"
    
    # Use DuckDuckGo to search for weather information for the specified location
    search_query = f"weather in {location}"
    try:
        search_results = DuckDuckGoSearchTool().search(search_query)
        
        # Extract weather details using regex (simplified for general use)
        weather_info = extract_weather_from_search_results(search_results)
        
        if weather_info:
            return f"Weather for {location} on {date_time_str}: {weather_info}"
        else:
            return f"Could not extract weather information for {location} from search results."
    
    except Exception as e:
        return f"Failed to fetch weather data for {location}. Error: {str(e)}"

def extract_weather_from_search_results(search_results: str) -> str:
    """
    Extracts weather information from the DuckDuckGo search results.
    """
    # A simple regex to extract temperature and weather condition (this can be more complex depending on the result structure)
    temperature_match = re.search(r'(\d+)\s?°C', search_results)
    condition_match = re.search(r"(clear|cloudy|rainy|sunny|stormy)", search_results, re.IGNORECASE)

    if temperature_match and condition_match:
        temperature = temperature_match.group(1)
        condition = condition_match.group(1)
        return f"Temperature: {temperature}°C, Condition: {condition.capitalize()}"
    return None

@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 recommend_activities_auto(location: str = "Your City, Your Country", timezone: str = "America/New_York") -> str:
    """
    Suggests an activity based on the current weather and time without requiring the user to specify them manually.
    
    Args:
        location: The name of the location to fetch weather for. Defaults to "Your City, Your Country".
        timezone: The timezone for fetching local time. Defaults to "America/New_York".
    
    Returns:
        A friendly activity suggestion based on the current conditions.
    """
    # Get the current weather using the location
    weather_report = get_current_weather(location)
    if "Temperature" not in weather_report:  # Check if weather data was successfully retrieved
        return "Sorry, I couldn't retrieve the weather data right now."
    
    # Extract temperature and weather condition from the report
    temperature_match = re.search(r"Temperature: (\d+)°C", weather_report)
    condition_match = re.search(r"Condition: (\w+)", weather_report)
    
    if temperature_match and condition_match:
        temperature = float(temperature_match.group(1))
        condition = condition_match.group(1).lower()
    else:
        return "Sorry, there was an issue extracting weather details."

    # Get the current time using the timezone
    time_report = get_current_time_in_timezone(timezone)
    if "Error" in time_report:  # Check if time data was successfully retrieved
        return "Sorry, I couldn't retrieve the current time."

    # Extract the time of day from the time report
    time_of_day_match = re.search(r"current local time in [\w/]+ is: (\d+:\d+:\d+)", time_report)
    if time_of_day_match:
        time_of_day = get_time_of_day()  # This function can extract time of day based on the time
    else:
        return "Sorry, there was an issue extracting the time of day."

    # Now, use the current weather and time to recommend activities
    risk_of_rain = 1 if condition in ["rainy", "stormy"] else 0
    activity_suggestion = recommend_activities(temperature, risk_of_rain, time_of_day)

    return activity_suggestion


def get_time_of_day() -> str:
    """
    Helper function to determine the time of day based on the current time.
    Returns one of "morning", "afternoon", "evening", or "night".
    """
    current_time = datetime.datetime.now()
    if 5 <= current_time.hour < 12:
        return "morning"
    elif 12 <= current_time.hour < 17:
        return "afternoon"
    elif 17 <= current_time.hour < 21:
        return "evening"
    else:
        return "night"
       

def recommend_activities(temperature: float, risk_of_rain: float, time_of_day: str) -> str:
    """
    Suggests a friendly activity recommendation based on temperature, risk of rain, and time of day.

    Args:
        temperature: The temperature in Celsius.
        risk_of_rain: The probability of rain (as a decimal between 0 and 1).
        time_of_day: Part of the day (morning, afternoon, evening, night).
    
    Returns:
        A friendly activity suggestion as a sentence.
    """
    time_of_day = time_of_day.lower()

    if time_of_day not in ["morning", "afternoon", "evening", "night"]:
        return "Hmm, I don’t recognize that time of day. Try 'morning', 'afternoon', 'evening', or 'night'."

    cold = temperature < 10
    warm = 10 <= temperature <= 25
    hot = temperature > 25
    rainy = risk_of_rain > 0.5

    if time_of_day == "morning":
        if rainy or cold:
            return "It's the perfect time to stay in, enjoy a warm cup of coffee, and start your day with a good book or a cozy movie."
        return "A fresh morning awaits! Go for a peaceful walk, grab a nice breakfast, or enjoy some outdoor yoga."

    elif time_of_day == "afternoon":
        if rainy:
            return "Rainy afternoon? How about visiting a museum, watching a movie, or enjoying a relaxed café break?"
        if hot:
            return "It's warm outside! A swim, a cold drink, or a relaxing afternoon indoors sounds perfect."
        return "Great time to explore! A bike ride, a picnic, or a casual city stroll could be just what you need."

    elif time_of_day == "evening":
        if rainy or cold:
            return "A cozy dinner indoors, a movie night, or a relaxed evening at home sounds just right."
        return "How about a sunset walk, a rooftop café visit, or a fun evening with friends?"

    elif time_of_day == "night":
        if rainy or cold:
            return "Snuggle up with a blanket, put on your favorite series, or enjoy a warm drink before bed."
        return "A quiet night walk, some stargazing, or a laid-back evening out could be a great way to end the day."

    return "Not sure what to recommend, but whatever you do, enjoy your time!"


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, get_current_time_in_timezone, get_current_weather, recommend_activities_auto], ## add your tools here (don't remove final answer)
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates
)


GradioUI(agent).launch()