CoolFace
Apppublic

astromonkey046/First_agent_template

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py162 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_current_time_in_timezone(timezone: str) -> str:23    """A tool that fetches the current local time in a specified timezone.24    Args:25        timezone: A string representing a valid timezone (e.g., 'America/New_York').26    """27    try:28        # Create timezone object29        tz = pytz.timezone(timezone)30        # Get current time in that timezone31        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")32        return f"The current local time in {timezone} is: {local_time}"33    except Exception as e:34        return f"Error fetching time for timezone '{timezone}': {str(e)}"35 36 37final_answer = FinalAnswerTool()38from smolagents import tool39import datetime40import pytz41import imaplib42import email as email_lib43import smtplib44from email.mime.text import MIMEText45 46@tool47def email_answer(sender_email: str, reply_body: str, recipient_email: str) -> str:48    """49    A tool that fetches the most recent email from your inbox (from sender_email)50    and sends a reply using recipient_email and reply_body.51 52    Args:53        sender_email: The email address of the person who originally sent you a message 54            (e.g., 'john@example.com'). We will look up the most recent email from this address.55        reply_body: The text content you want to send as a reply 56            (e.g., 'Thanks for reaching out—I’ll get back to you shortly.'). Must be non-empty.57        recipient_email: The email address from which the reply should be sent 58            (e.g., 'alice@example.com'). Must be a valid email address that you control.59 60    Returns:61        A string indicating success (e.g., 'Replied successfully to ...') or 62        an error message if something went wrong.63    """64    # 1) Validate or preprocess arguments65    if sender_email.count("@") != 1 or "." not in sender_email.split("@")[-1]:66        return f"Error: 'sender_email' is not a valid email address: {sender_email}"67    if recipient_email.count("@") != 1 or "." not in recipient_email.split("@")[-1]:68        return f"Error: 'recipient_email' is not a valid email address: {recipient_email}"69    if not isinstance(reply_body, str) or len(reply_body.strip()) == 0:70        return "Error: 'reply_body' must be a non-empty string."71 72    try:73        # 2a) (Optional) Fetch the most recent email from sender_email using IMAP74        #     (Uncomment and configure with your own IMAP credentials if desired)75        #76         imap_host = "imap.gmail.com"77         imap_user = "abhi.sjaswal6@gmail.com"78         imap_pass = "abhigoogle538549"79         mail = imaplib.IMAP4_SSL(imap_host)80         mail.login(imap_user, imap_pass)81         mail.select("INBOX")82         status, messages = mail.search(None, f'FROM "{sender_email}"')83         if status != "OK" or not messages[0].split():84             return f"No recent emails found from {sender_email}."85         latest_email_id = messages[0].split()[-1]86         status, msg_data = mail.fetch(latest_email_id, "(RFC822)")87         if status != "OK":88             return f"Error fetching email with ID {latest_email_id}"89         raw_email = msg_data[0][1]90         parsed_email = email_lib.message_from_bytes(raw_email)91         subject = parsed_email["Subject"]92        #93        # For now, we’ll simulate that we found an email subject "Meeting Tomorrow"94         Close the IMAP connection95         mail.logout()96 97        # 2b) Send the reply using SMTP98        #     (Uncomment and configure with your own SMTP credentials if desired)99        #100         smtp_host = "smtp.gmail.com"101         smtp_port = 465102         smtp_user = recipient_email103         smtp_pass = "abhigoogle538549"104        #105         msg = MIMEText(reply_body)106         msg["Subject"] = f"Re: {subject}"107         msg["From"] = smtp_user108         msg["To"] = sender_email109        #110         smtp_server = smtplib.SMTP_SSL(smtp_host, smtp_port)111         smtp_server.login(smtp_user, smtp_pass)112         smtp_server.sendmail(smtp_user, sender_email, msg.as_string())113         smtp_server.quit()114 115        # If we reach here, assume success116        return (117            f"Success: Simulated reply sent to {sender_email} with subject 'Re: {subject}',\n"118            f"from {recipient_email}. Reply body:\n{reply_body}"119        )120 121    except Exception as e:122        # 3) Catch any exceptions and return as a plain-text error123        return f"Error in email_answer: {str(e)}"124 125 126 127# 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:128# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 129 130model = HfApiModel(131max_tokens=2096,132temperature=0.5,133model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded134custom_role_conversions=None,135)136 137 138# Import tool from Hub139image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)140 141with open("prompts.yaml", 'r') as stream:142    prompt_templates = yaml.safe_load(stream)143    144agent = CodeAgent(145    model=model,146    tools=[final_answer,           # Always keep this first (the “stop and respond” tool)147        email_answer,           # Your custom email‐replying tool148        image_generation_tool,  # Example of a remote tool149        DuckDuckGoSearchTool(), # Pre‐built web search tool150        # You can add more @tool functions or load_tool(...) calls here151    ] ## add your tools here (don't remove final answer)152    max_steps=6,153    verbosity_level=1,154    grammar=None,155    planning_interval=None,156    name=None,157    description=None,158    prompt_templates=prompt_templates159)160 161 162GradioUI(agent).launch()