Team Ai
Apppublic

strickvl/First_agent_template

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py101 linesDownload Raw Back to root
1from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool2import datetime3import requests4import pytz5import yaml6import time7import logging8from tools.final_answer import FinalAnswerTool9from tools.text_analysis import analyze_text10 11from Gradio_UI import GradioUI12 13# Set up logging14logger = logging.getLogger(__name__)15 16 17# Below is an example of a tool that does nothing. Amaze us with your creativity !18@tool19def my_cutom_tool(20    arg1: str, arg2: int21) -> str:  # it's import to specify the return type22    # Keep this format for the description / args / args description but feel free to modify the tool23    """A tool that does nothing yet24    Args:25        arg1: the first argument26        arg2: the second argument27    """28    return "What magic will you build ?"29 30 31@tool32def get_current_time_in_timezone(timezone: str) -> str:33    """A tool that fetches the current local time in a specified timezone.34    Args:35        timezone: A string representing a valid timezone (e.g., 'America/New_York').36    """37    try:38        # Create timezone object39        tz = pytz.timezone(timezone)40        # Get current time in that timezone41        local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")42        return f"The current local time in {timezone} is: {local_time}"43    except Exception as e:44        return f"Error fetching time for timezone '{timezone}': {str(e)}"45 46 47final_answer = FinalAnswerTool()48 49 50class RetryingHfApiModel(HfApiModel):51    """HfApiModel with retry logic for rate limiting"""52 53    def __init__(self, max_retries=3, retry_delay=2, **kwargs):54        super().__init__(**kwargs)55        self.max_retries = max_retries56        self.retry_delay = retry_delay57 58    async def async_chat(self, *args, **kwargs):59        for attempt in range(self.max_retries):60            try:61                return await super().async_chat(*args, **kwargs)62            except Exception as e:63                if "429" in str(e) and attempt < self.max_retries - 1:64                    wait_time = self.retry_delay * (attempt + 1)  # Exponential backoff65                    logger.warning(f"Rate limited. Retrying in {wait_time} seconds...")66                    time.sleep(wait_time)67                    continue68                raise  # Re-raise the exception if it's not a 429 or we're out of retries69 70 71# Replace the model initialization with our retrying version72model = RetryingHfApiModel(73    max_tokens=2096,74    temperature=0.5,75    model_id="Qwen/Qwen2.5-Coder-32B-Instruct",76    custom_role_conversions=None,77    max_retries=3,  # Will try up to 3 times78    retry_delay=2,  # Start with 2 second delay, will increase with each retry79)80 81# Import tool from Hub82image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)83 84with open("prompts.yaml", "r") as stream:85    prompt_templates = yaml.safe_load(stream)86 87agent = CodeAgent(88    model=model,89    tools=[final_answer, analyze_text],  # Added analyze_text tool90    max_steps=6,91    verbosity_level=1,92    grammar=None,93    planning_interval=None,94    name=None,95    description=None,96    prompt_templates=prompt_templates,97)98 99 100GradioUI(agent).launch()101