codeinpython2024/First_agent_template
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 multiplication_table(arg1: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 15 """A tool that takes an input (integer) and create a multiplication table of the input16 Args:17 arg1: the integer argument18 19 up_to: this is integer and it is fixed as 1220 21 """22 result = []23 24 up_to: int = 1225 26 for i in range(1, up_to + 1):27 28 result.append(f'{arg1} * {i} = {arg1 * i}')29 30 return "\n".join(result)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(location: str) -> str:49 """A tool that fetches the current weather of the location provided50 Args:51 location: A string representing a valid location (e.g., 'Abuja')52 """53 54 API_KEY = '207e6ba9ac0c491f4b09fc3090699ee7'55 W_API_KEY = 'ad33b41fcbe7031483d330f037158786'56 try:57 response = requests.get(url=f'http://api.openweathermap.org/geo/1.0/direct?q={location},NG&limit=1&appid={API_KEY}')58 data = response.json()59 for i in range(len(data)):60 lat = data[i]['lat']61 lon = data[i]['lon']62 63 response_1 = requests.get(url=f'https://api.openweathermap.org/data/2.5/weather?units=metric&lat={lat}&lon={lon}&appid={API_KEY}')64 data_1 = response_1.json()65 66 data_2 = requests.get(f'http://api.weatherstack.com/current?access_key={W_API_KEY}&query={lat},{lon}&units=m')67 condition = data_2.json()['current']['weather_descriptions'][0].strip()68 69 temperature = data_1['main']['temp']70 return f'The Temperature for {location}: {temperature}°C and it is {condition}'71 72 except Exception as e:73 return f'Error fetching weather for location "{location}": {str(e)}'74 75final_answer = FinalAnswerTool()76web_search = DuckDuckGoSearchTool()77 78# 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:79# model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud' 80 81model = HfApiModel(82max_tokens=2096,83temperature=0.5,84model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded85custom_role_conversions=None,86)87 88 89# Import tool from Hub90image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)91 92with open("prompts.yaml", 'r') as stream:93 prompt_templates = yaml.safe_load(stream)94 95agent = CodeAgent(96 model=model,97 tools=[final_answer, image_generation_tool, get_current_time_in_timezone, multiplication_table, web_search,get_weather], ## add your tools here (don't remove final answer)98 max_steps=6,99 verbosity_level=1,100 grammar=None,101 planning_interval=None,102 name=None,103 description=None,104 prompt_templates=prompt_templates105)106 107 108GradioUI(agent).launch()