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