Spaces:
Sleeping
Sleeping
| 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 | |
| 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)}" | |
| 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 | |
| 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() |