CoolFace
Apppublic

Risalat/First_agent_template2

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py117 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    try:20        # Generate image using the loaded tool21        result = image_generation_tool(prompt=arg1)22 23        # Check result format (it may vary depending on the tool's implementation)24        if isinstance(result, str):25            return f"Generated image URL: {result}"26        elif isinstance(result, dict) and "image_url" in result:27            return f"Generated image URL: {result['image_url']}"28        else:29            return f"Image generated successfully: {result}"30    except Exception as e:31        return f"Failed to generate image from prompt '{arg1}': {str(e)}"32from smolagents import tool33 34# Assuming this is already loaded earlier35# image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)36# Import tool from Hub37image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)38from PIL import Image39 40@tool41def image_generator(arg1: str) -> Image.Image:42    """43    A tool that generates an image based on a text prompt.44 45    Args:46        arg1: A description or prompt for the image to be generated.47 48    Returns:49        A PIL.Image object which Gradio and final_answer can display properly.50    """51    try:52        result = image_generation_tool(prompt=arg1)53 54        # If result is a PIL image, return a fully loaded version55        if isinstance(result, Image.Image):56            return result.convert("RGB")  # Ensures it's fully loaded and in a common format57        elif isinstance(result, str):58            raise ValueError("Expected an image, but got a string URL. Cannot pass this to final_answer.")59        elif isinstance(result, dict) and "image_url" in result:60            raise ValueError("Expected an image, but got a dict with 'image_url'. Cannot pass this to final_answer.")61        else:62            raise ValueError(f"Unexpected result type: {type(result)}")63    except Exception as e:64        # Raise errors to let the agent or UI handle them65        raise RuntimeError(f"Error generating image from prompt '{arg1}': {str(e)}")66 67 68 69 70@tool71def get_current_time_in_timezone(timezone: str) -> str:72    """A tool that fetches the current local time in a specified timezone.73    Args:74        timezone: A string representing a valid timezone (e.g., 'America/New_York').75    """76    try:77        # Create timezone object78        tz = pytz.timezone(timezone)79        # Get current time in that timezone80        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")81        return f"The current local time in {timezone} is: {local_time}"82    except Exception as e:83        return f"Error fetching time for timezone '{timezone}': {str(e)}"84 85 86final_answer = FinalAnswerTool()87 88# 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:89# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 90 91model = HfApiModel(92max_tokens=2096,93temperature=0.5,94model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded95custom_role_conversions=None,96)97 98 99 100 101with open("prompts.yaml", 'r') as stream:102    prompt_templates = yaml.safe_load(stream)103    104agent = CodeAgent(105    model=model,106    tools=[final_answer,image_generator], ## add your tools here (don't remove final answer)107    max_steps=6,108    verbosity_level=1,109    grammar=None,110    planning_interval=None,111    name=None,112    description=None,113    prompt_templates=prompt_templates114)115 116 117GradioUI(agent).launch()