CoolFace
Apppublic

palash147/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py143 linesDownload Raw Back to root
1from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool2import datetime3import requests4import pytz5import yaml6from tools.final_answer import FinalAnswerTool7 8from Gradio_UI import GradioUI9 10# Below is an example of a tool that does nothing. Amaze us with your creativity !11@tool12def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type13    #Keep this format for the description / args / args description but feel free to modify the tool14    """A tool that does nothing yet 15    Args:16        arg1: the first argument17        arg2: the second argument18    """19    return "What magic will you build ?"20 21@tool22def get_weather_by_location(location_str: str) -> str:23    """24    Get weather data for a location name without requiring API keys.25    26    Args:27        location_str (str): Name of location (e.g., "New York City" or "Paris, France")28        29    Returns:30        dict: Weather data including location details and forecast31    """32    try:33        # Step 1: Convert location string to coordinates using Nominatim (OpenStreetMap)34        # This geocoding service is free and doesn't require an API key35        geocode_url = "https://nominatim.openstreetmap.org/search"36        geocode_params = {37            "q": location_str,38            "format": "json",39            "limit": 140        }41        headers = {42            "User-Agent": "WeatherApp/1.0"  # OSM requires a user agent43        }44        45        geocode_response = requests.get(geocode_url, params=geocode_params, headers=headers)46        geocode_response.raise_for_status()47        48        geocode_data = geocode_response.json()49        if not geocode_data:50            raise ValueError(f"Location '{location_str}' not found")51        52        # Extract coordinates and location details53        latitude = float(geocode_data[0]["lat"])54        longitude = float(geocode_data[0]["lon"])55        location_name = geocode_data[0]["display_name"]56        57        # Step 2: Get weather data from OpenMeteo using the coordinates58        weather_url = "https://api.open-meteo.com/v1/forecast"59        weather_params = {60            "latitude": latitude,61            "longitude": longitude,62            "current": "temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m",63            "hourly": "temperature_2m",64            "daily": "weather_code,temperature_2m_max,temperature_2m_min,sunrise,sunset",65            "timezone": "auto"66        }67        68        weather_response = requests.get(weather_url, params=weather_params)69        weather_response.raise_for_status()70        71        weather_data = weather_response.json()72        73        # Step 3: Combine location and weather data74        result = {75            "location": {76                "name": location_name,77                "latitude": latitude,78                "longitude": longitude79            },80            "weather": weather_data81        }82        83        return result84    85    except requests.exceptions.RequestException as e:86        print(f"Error making request: {e}")87        raise88    except ValueError as e:89        print(f"Value error: {e}")90        raise91    except Exception as e:92        print(f"Unexpected error: {e}")93        raise94 95@tool96def get_current_time_in_timezone(timezone: str) -> str:97    """A tool that fetches the current local time in a specified timezone.98    Args:99        timezone: A string representing a valid timezone (e.g., 'America/New_York').100    """101    try:102        # Create timezone object103        tz = pytz.timezone(timezone)104        # Get current time in that timezone105        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")106        return f"The current local time in {timezone} is: {local_time}"107    except Exception as e:108        return f"Error fetching time for timezone '{timezone}': {str(e)}"109 110 111final_answer = FinalAnswerTool()112 113# 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:114# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 115 116model = HfApiModel(117max_tokens=2096,118temperature=0.5,119model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded120custom_role_conversions=None,121)122 123 124# Import tool from Hub125image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)126 127with open("prompts.yaml", 'r') as stream:128    prompt_templates = yaml.safe_load(stream)129    130agent = CodeAgent(131    model=model,132    tools=[get_weather_by_location,get_current_time_in_timezone,final_answer], ## add your tools here (don't remove final answer)133    max_steps=6,134    verbosity_level=1,135    grammar=None,136    planning_interval=None,137    name=None,138    description=None,139    prompt_templates=prompt_templates140)141 142 143GradioUI(agent).launch()