CoolFace
Apppublic

Gennadion/first_agent

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py120 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(lat: int, lon: int) -> str:23    """A tool that fetches current weather in specified coordinates24    Args:25        lat: The latitude of the location26        lon: The longitude of the location27 28    Returns:29        weather: A string with weather details of the location30    """31    API_KEY = "0797a42ab0a8814771f59d4747054fb5"32    url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API_KEY}"33    response = requests.get(url)34    data = response.json()35    36    if data.get("cod") != 200:37        return "City not found!"38    39    weather = data["weather"][0]["description"]40    temp_k = data["main"]["temp"]41    temp = temp_k - 273.1542    return f"Weather is: {weather}; Temperature is {temp}"43 44@tool45def get_coordinates(location: str) -> tuple[int, int]:46    """47    Convert a location (city, address, or landmark) into latitude and longitude using OpenCage API.48    49    Args:50        location: The location to be geocoded.51 52    Returns:53        lat: The latitude of the location54        lon: The longitude of the location55    """56    API_KEY = "18f67c8f74db45baa1b79a97e4c1fec9"57    url = f"https://api.opencagedata.com/geocode/v1/json?q={location}&key={API_KEY}"58    59    response = requests.get(url)60    data = response.json()61    62    if data['results']:63        lat = data['results'][0]['geometry']['lat']64        lon = data['results'][0]['geometry']['lng']65        return lat, lon66    else:67        return None68 69@tool70def get_current_time_in_timezone(timezone: str) -> str:71    """A tool that fetches the current local time in a specified timezone.72    Args:73        timezone: A string representing a valid timezone (e.g., 'America/New_York').74 75    Returns:76        local_time: Local time of the timezone77    """78    try:79        # Create timezone object80        tz = pytz.timezone(timezone)81        # Get current time in that timezone82        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")83        return local_time84    except Exception as e:85        return f"Error fetching time for timezone '{timezone}': {str(e)}"86 87 88final_answer = FinalAnswerTool()89 90# 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:91# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 92 93model = HfApiModel(94max_tokens=2096,95temperature=0.5,96model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',97custom_role_conversions=None,98)99 100 101# Import tool from Hub102image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)103 104with open("prompts.yaml", 'r') as stream:105    prompt_templates = yaml.safe_load(stream)106    107agent = CodeAgent(108    model=model,109    tools=[get_coordinates, get_current_time_in_timezone, get_weather, final_answer], ## add your tools here (don't remove final answer)110    max_steps=6,111    verbosity_level=1,112    grammar=None,113    planning_interval=None,114    name=None,115    description=None,116    prompt_templates=prompt_templates117)118 119 120GradioUI(agent).launch()