File size: 10,051 Bytes
c4c5304
 
 
 
 
 
84787e4
c4c5304
7c9c630
 
 
 
 
 
bbcb03b
c4c5304
 
bbcb03b
c4c5304
176aaac
73e9ad7
 
84787e4
 
 
e361be7
84787e4
 
 
 
 
 
5434006
 
 
 
 
 
84787e4
 
 
 
 
e361be7
5434006
84787e4
 
e361be7
84787e4
 
5434006
 
c06850c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32d58e4
 
 
 
 
 
 
c4c5304
 
32d58e4
 
c4c5304
32d58e4
 
 
 
 
c4c5304
32d58e4
c4c5304
 
 
 
 
 
 
 
 
 
 
32d58e4
 
 
 
 
c4c5304
 
 
 
 
 
32d58e4
 
c4c5304
 
 
 
32d58e4
 
 
c4c5304
 
 
 
32d58e4
c4c5304
32d58e4
c4c5304
32d58e4
 
 
 
 
c4c5304
32d58e4
 
c4c5304
 
 
 
 
 
 
cb665e3
 
c4c5304
 
 
32d58e4
 
c4c5304
 
32d58e4
 
 
 
c4c5304
32d58e4
 
c4c5304
32d58e4
c4c5304
 
 
 
 
c06850c
84787e4
 
32d58e4
 
 
c4c5304
 
 
 
32d58e4
 
 
c4c5304
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from IPython.display import Audio
from Gradio_UI import GradioUI

# # Below is an example of a tool that does nothing. Amaze us with your creativity !
# # @tool
# # def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
# #     #Keep this format for the description / args / args description but feel free to modify the tool
# #     """A tool that does nothing yet 
#     Args:
#         arg1: the first argument
#         arg2: the second argument
#     """
#     return "What magic will you build ?"

leak_warning_img = "leakage.png"
safe_status_img = "no leakage.jpeg"
alarm_sound_file = "alarm_sound.wav"

@tool
def leakage_alarm_checker(current_leakage_level: float, safe_threshold: float) -> tuple[str, "Image", "Audio | None"]:
    """
    Checks if the leakage level has exceeded a safe threshold and triggers an alarm.
    
    Args:
        current_leakage_level: The measured leakage level.
        safe_threshold: The maximum allowable leakage before triggering an alert.
    
    Returns:
        A tuple containing:
        - str: Alert message
        - Image: Warning or safe image
        - Audio | None: Alarm sound (if alert is triggered)
    """
    try:
        dif_leakage = current_leakage_level - safe_threshold
        if dif_leakage > 0:  
            alert_message = f"🚨 ALERT: Leakage level is {current_leakage_level} (Threshold: {safe_threshold}). IMMEDIATE ACTION REQUIRED!"
            warning_image = Image.open("leak_warning.png")  # Ensure this file exists
            return alert_message, warning_image, Audio("alarm_sound.wav", autoplay=True)
        else:
            alert_message = f"✅ SAFE: Leakage level is {current_leakage_level}, within the safe limit of {safe_threshold}. System is operating normally."
            safe_image = Image.open("safe_status.png")  # Ensure this file exists
            return alert_message, safe_image, None
    except Exception as e:
        return f"Error processing leakage levels: {str(e)}", Image.new("RGB", (200, 200), "gray"), None


@tool
def alarm_comparator_degrees(weather_average_degrees:float, optimal_fermentation_degrees:float)-> str: #it's import to specify the return type
    #Keep this format for the description / args / args description but feel free to modify the tool
    """A tool that compares the actual weathers degrees and the optimal fermentation degrees of a product in order to flag with an alert!!
    
    Args:
        weather_average_degrees: A float representing the avarage degrees of current weather.
        optimal_fermentation_degrees: A float representing the degrees that should be the fermentation process.
    """
    try:
        dif_degrees = weather_average_degrees - optimal_fermentation_degrees
        if abs(dif_degrees) >= 1.5:
            if dif_degrees < 0:
                return f"RED LIGHT - the difference degrees between optimal and current weather are {str(dif_degrees)}ºC - YOU SHOULD INCREASE THE HEATER BY {str(dif_degrees)}ºC!"   
            else:
                return f"RED LIGHT - the difference degrees between optimal and current weather are {str(dif_degrees)}ºC - YOU SHOULD DECREASE THE HEATER BY {str(dif_degrees)}ºC!"  
        else:
            return f"GREEN LIGHT - the difference degrees between optimal and current weather are {str(dif_degrees)} - DEGREES FOR FERMENTATION IN RANGE!"
    except Exception as e:
        return f"Error fetching {str(weather_average_degrees)} and {str(optimal_fermentation_degrees)}."
    

@tool
def convert_usd_to_eur(usd_amount: float) -> str:
    """
    Converts USD to EUR using a fixed exchange rate (mock).
    Args:
        usd_amount: The amount in USD.
    """
    # Example fixed rate: 1 USD = 0.9 EUR
    eur_amount = usd_amount * 0.9
    return f"${usd_amount} is approximately €{eur_amount:.2f}."


@tool
def daily_gold_oil_updates() -> str:
    """
    A tool that searches DuckDuckGo for daily gold and oil stock updates.
    """
    # Create an instance of the DuckDuckGoSearchTool
    ddg_tool = DuckDuckGoSearchTool()

    # Customize your search query as desired
    search_query = (
        "Gold and oil stock prices today. "
        "Daily updates, latest news, and current market data."
    )

    # Perform the search and return the raw results as a string
    results = ddg_tool.run(search_query)
    return results


@tool
def daily_weather_search(location: str) -> str:
    """
    A tool that searches DuckDuckGo for current weather in the specified location.

    Args:
        location: The city or region to get weather info for.

    Returns:
        A string containing raw DuckDuckGo search results about the current weather.
    """
    ddg_tool = DuckDuckGoSearchTool()
    search_query = f"Current weather in {location}, local forecast, temperature, humidity."
    results = ddg_tool.run(search_query)
    return results


@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()

# 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
model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
#model_id = 'deepseek-ai/DeepSeek-R1-Distill-Qwen-32B',
    

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,image_generation_tool ], ## add your tools here (don't remove final answer)
    tools=[
        final_answer,               # Final answer tool (don't remove)
        image_generation_tool,      # The text-to-image tool from the Hub
        convert_usd_to_eur,         # Your custom currency converter
        get_current_time_in_timezone,  # Your custom time tool
        daily_gold_oil_updates,
        daily_weather_search,
        alarm_comparator_degrees,
        leakage_alarm_checker
    ],
    max_steps=6,
    verbosity_level=1,
    grammar=None,
    planning_interval=None,
    name=None,
    description=None,
    prompt_templates=prompt_templates
)
GradioUI(agent).launch()


# import os
# import openai
# import datetime
# import requests
# import pytz
# import yaml
# from smolagents import CodeAgent, DuckDuckGoSearchTool, load_tool, tool
# from smolagents.models.openai_model import OpenAIModel  # OpenAI Model Import
# from tools.final_answer import FinalAnswerTool
# from Gradio_UI import GradioUI
# from smolagents.openai_model import OpenAIModel




# # Set your OpenAI API key securely
# openai.api_key = os.getenv("OPENAI_API_KEY")

# @tool
# def convert_usd_to_eur(usd_amount: float) -> str:
#     """
#     Converts USD to EUR using a fixed exchange rate (mock).
#     Args:
#         usd_amount: The amount in USD.
#     """
#     eur_amount = usd_amount * 0.9  # Example fixed rate
#     return f"${usd_amount} is approximately €{eur_amount:.2f}."

# @tool
# def daily_gold_oil_updates() -> str:
#     """
#     A tool that searches DuckDuckGo for daily gold and oil stock updates.
#     """
#     ddg_tool = DuckDuckGoSearchTool()
#     search_query = "Gold and oil stock prices today. Daily updates and market trends."
#     return ddg_tool.run(search_query)

# @tool
# def daily_weather_search(location: str) -> str:
#     """
#     A tool that searches DuckDuckGo for current weather in the specified location.
#     """
#     ddg_tool = DuckDuckGoSearchTool()
#     search_query = f"Current weather in {location}, temperature, and forecast."
#     return ddg_tool.run(search_query)

# @tool
# def get_current_time_in_timezone(timezone: str) -> str:
#     """Fetches the current local time in a specified timezone."""
#     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()

# # Using OpenAI GPT-4 instead of Hugging Face API
# model = OpenAIModel(
#     model_name="gpt-4",  # or "gpt-3.5-turbo"
#     temperature=0.5,
#     max_tokens=2048
# )

# # Import tool from Hugging Face 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,  # Final answer tool
#         image_generation_tool,  # Text-to-image tool
#         convert_usd_to_eur,  # Currency conversion tool
#         get_current_time_in_timezone,  # Timezone tool
#         daily_gold_oil_updates,  # Gold and oil updates tool
#         daily_weather_search  # Weather search tool
#     ],
#     max_steps=6,
#     verbosity_level=1,
#     prompt_templates=prompt_templates
# )

# GradioUI(agent).launch()