CoolFace
Apppublic

emroca/First_agent_template

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py103 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 GradioUI9import os10 11# Below is an example of a tool that does nothing. Amaze us with your creativity !12@tool13def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type14    """A tool that generates text based on the provided arguments.15    Args:16        arg1: A string input to guide the generation.17        arg2: An integer input to specify the type of generation (1 for detailed description, 2 for summary).18    """19    if arg2 == 1:20        # Generate detailed description using LLM21        prompt = f"Generate a detailed description based on the following input: {arg1}"22        response = model.generate(prompt)23        return response['choices'][0]['text']24    elif arg2 == 2:25        # Generate summary using LLM26        prompt = f"Generate a summary based on the following input: {arg1}"27        response = model.generate(prompt)28        return response['choices'][0]['text']29    else:30        return "Invalid argument for arg2. Use 1 for detailed description and 2 for summary."31 32@tool33def get_current_time_in_timezone(timezone: str) -> str:34    """A tool that fetches the current local time in a specified timezone.35    Args:36        timezone: A string representing a valid timezone (e.g., 'America/New_York').37    """38    try:39        # Create timezone object40        tz = pytz.timezone(timezone)41        # Get current time in that timezone42        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")43        return f"The current local time in {timezone} is: {local_time}"44    except Exception as e:45        return f"Error fetching time for timezone '{timezone}': {str(e)}"46 47@tool48def get_weather(city: str) -> str:49    """A tool that fetches the current weather for a specified city.50    Args:51        city: The name of the city to get the weather for.52    """53    api_key = "c46c960cf2d8dd517715b8ff14818d7e"  # Replace with your actual OpenWeather API key54    url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"55    56    try:57        response = requests.get(url)58        data = response.json()59        60        if response.status_code == 200:61            weather_description = data['weather'][0]['description']62            temperature = data['main']['temp']63            return f"The current weather in {city} is {weather_description} with a temperature of {temperature}°C."64        else:65            return f"Error fetching weather for city '{city}': {data['message']}"66    except Exception as e:67        return f"Error fetching weather for city '{city}': {str(e)}"        68 69 70final_answer = FinalAnswerTool()71 72# 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:73# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 74# model_id='Qwen/Qwen2.5-Coder-32B-Instruct'75 76model = HfApiModel(77max_tokens=2096,78temperature=0.5,79model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloaded80custom_role_conversions=None,81)82 83 84# Import tool from Hub85image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True, use_auth_token=os.getenv("HF_TOKEN"))86 87with open("prompts.yaml", 'r') as stream:88    prompt_templates = yaml.safe_load(stream)89    90agent = CodeAgent(91    model=model,92    tools=[final_answer, get_weather, my_custom_tool], ## add your tools here (don't remove final answer)93    max_steps=6,94    verbosity_level=1,95    grammar=None,96    planning_interval=None,97    name=None,98    description=None,99    prompt_templates=prompt_templates100)101 102 103GradioUI(agent).launch()