ytcaples/First_agent_example
0
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 37@tool38def get_eur_exchange_rate(currency_code: str) -> str:39 """A tool that retrieves the current exchange rate from EUR to a given currency40 41 Args:42 currency_code: The 3-letter currency code in lowercase (e.g., "usd", "gbp", "jpy")43 """44 45 try:46 # Fetch the EUR exchange rates from the API47 api_url = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json"48 response = requests.get(api_url, timeout=10)49 response.raise_for_status()50 51 data = response.json()52 53 # Extract date and exchange rates54 date = data.get("date", "Unknown date")55 exchange_rates = data.get("eur", {})56 57 # Get the specific exchange rate58 if currency_code in exchange_rates:59 rate = exchange_rates[currency_code]60 return f"1 EUR = {rate} {currency_code.upper()} (as of {date})"61 else:62 return f"Currency code '{currency_code}' not found in the exchange rate data. Please check the currency code format."63 64 except requests.RequestException as e:65 return f"Error fetching exchange rate data: {str(e)}"66 except Exception as e:67 return f"Error: {str(e)}"68 69@tool 70def get_simple_joke() -> str:71 """A tool that fetches a random joke from JokeAPI with minimal filtering"""72 73 try:74 # Simple request to JokeAPI75 api_url = "https://v2.jokeapi.dev/joke/any"76 77 response = requests.get(api_url, timeout=10)78 response.raise_for_status()79 80 joke_data = response.json()81 82 if joke_data.get("error", False):83 return f"Error: {joke_data.get('message', 'Could not get joke')}"84 85 if joke_data.get("type") == "single":86 return f"Here's a joke:\n\n{joke_data.get('joke', '')}"87 elif joke_data.get("type") == "twopart":88 setup = joke_data.get("setup", "")89 delivery = joke_data.get("delivery", "")90 return f"Here's a joke:\n\n{setup}\n{delivery}"91 92 return "Could not parse joke from API response"93 94 except Exception as e:95 return f"Error: {str(e)}"96 97 98 99final_answer = FinalAnswerTool()100 101# 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:102# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 103 104model = HfApiModel(105max_tokens=2096,106temperature=0.5,107model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded108custom_role_conversions=None,109)110 111 112# Import tool from Hub113image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)114 115with open("prompts.yaml", 'r') as stream:116 prompt_templates = yaml.safe_load(stream)117 118agent = CodeAgent(119 model=model,120 tools=[final_answer, my_custom_tool, get_current_time_in_timezone, get_eur_exchange_rate, get_simple_joke], ## add your tools here (don't remove final answer)121 max_steps=6,122 verbosity_level=1,123 grammar=None,124 planning_interval=None,125 name=None,126 description=None,127 prompt_templates=prompt_templates128)129 130 131GradioUI(agent).launch()