Spaces:
Sleeping
Sleeping
test
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,toolimport datetimeimport requestsimport pytzimport yamlfrom tools.final_answer import FinalAnswerToolfrom Gradio_UI import GradioUI# Below is an example of a tool that does nothing. Amaze us with your creativity !@tooldef 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 yetArgs:arg1: the first argumentarg2: the second argument"""return "What magic will you build ?"@tooldef 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 objecttz = pytz.timezone(timezone)# Get current time in that timezonelocal_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 overloadedcustom_role_conversions=None,)# Import tool from Hubimage_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], ## 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, toolimport datetimeimport requestsimport pytzimport yamlfrom tools.final_answer import FinalAnswerToolfrom Gradio_UI import GradioUI# Open-Meteo API URLsGEOCODING_URL = "https://geocoding-api.open-meteo.com/v1/search"WEATHER_URL = "https://api.open-meteo.com/v1/forecast"@tooldef get_weather(location: str, units: str = "metric") -> str:"""Fetches the current weather for a given location using Open-Meteo.Args:location: The city or place to get weather information for.units: 'metric' for Celsius, 'imperial' for Fahrenheit."""try:# Step 1: Convert location name to latitude and longitudegeo_params = {"name": location, "count": 1, "format": "json"}geo_response = requests.get(GEOCODING_URL, params=geo_params)geo_data = geo_response.json()if "results" not in geo_data or len(geo_data["results"]) == 0:return f"Error: Could not find coordinates for '{location}'."lat, lon = geo_data["results"][0]["latitude"], geo_data["results"][0]["longitude"]# Step 2: Fetch weather data for the coordinatesweather_params = {"latitude": lat,"longitude": lon,"current": "temperature_2m,relative_humidity_2m,weathercode","temperature_unit": "celsius" if units == "metric" else "fahrenheit","windspeed_unit": "kmh","timezone": "auto",}weather_response = requests.get(WEATHER_URL, params=weather_params)weather_data = weather_response.json()if "current" not in weather_data:return f"Error: Unable to retrieve weather data for '{location}'."# Extract weather detailstemp = weather_data["current"]["temperature_2m"]humidity = weather_data["current"]["relative_humidity_2m"]weather_code = weather_data["current"]["weathercode"]# Weather description mapping (basic)weather_conditions = {0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",45: "Fog", 48: "Depositing rime fog",51: "Light drizzle", 53: "Moderate drizzle", 55: "Dense drizzle",61: "Light rain", 63: "Moderate rain", 65: "Heavy rain",71: "Light snow", 73: "Moderate snow", 75: "Heavy snow",80: "Light showers", 81: "Moderate showers", 82: "Violent showers",95: "Thunderstorm", 96: "Thunderstorm with hail"}weather_desc = weather_conditions.get(weather_code, "Unknown weather condition")return (f"Weather in {location}: {weather_desc}, Temperature: {temp}°C, "f"Humidity: {humidity}%")except Exception as e:return f"Error fetching weather: {str(e)}"@tooldef get_current_time_in_timezone(timezone: str) -> str:"""Fetches the current local time in a specified timezone.Args:timezone: A string representing a valid timezone (e.g., 'America/New_York')."""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()# Define the AI modelmodel = HfApiModel(max_tokens=2096,temperature=0.5,model_id='Qwen/Qwen2.5-Coder-32B-Instruct',)# Load promptswith open("prompts.yaml", 'r') as stream:prompt_templates = yaml.safe_load(stream)# Initialize the agent with toolsagent = CodeAgent(model=model,tools=[final_answer, get_weather, get_current_time_in_timezone], # Add get_weather heremax_steps=6,verbosity_level=1,grammar=None,planning_interval=None,name="WeatherAgent",description="An AI agent that provides weather updates and time information.",prompt_templates=prompt_templates)# Launch Gradio UIGradioUI(agent).launch()
app.py+71-30