yannickkerherve/First_agent_template
0
1from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool2import json3import datetime4import requests5import pytz6import yaml7from tools.final_answer import FinalAnswerTool8 9from Gradio_UI import GradioUI10 11# Below is an example of a tool that does nothing. Amaze us with your creativity !12@tool13def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type14 #Keep this format for the description / args / args description but feel free to modify the tool15 """A tool that does nothing yet 16 Args:17 arg1: the first argument18 arg2: the second argument19 """20 return "What magic will you build ?"21 22# Code Agent Example: Retrieve Weather Information23from smolagents import tool24 25from smolagents import tool26 27@tool28def get_weather(city: str) -> str:29 """Get current weather information for a specified city.30 31 Args:32 city: The name of the city to get weather information for. Example: "Paris", "London", "New York"33 34 Returns:35 A string containing the current weather information including temperature,36 description and humidity for the specified city.37 """38 import requests39 40 API_KEY = "YOUR_API_KEY_HERE"41 base_url = "http://api.openweathermap.org/data/2.5/weather"42 43 params = {44 'q': city,45 'appid': API_KEY,46 'units': 'metric',47 'lang': 'fr'48 }49 50 try:51 response = requests.get(base_url, params=params)52 response.raise_for_status()53 54 data = response.json()55 temperature = data['main']['temp']56 description = data['weather'][0]['description']57 humidity = data['main']['humidity']58 59 weather_info = (60 f"Météo à {city}:\n"61 f"Température: {temperature}°C\n"62 f"Conditions: {description}\n"63 f"Humidité: {humidity}%"64 )65 66 return weather_info67 68 except Exception as e:69 return f"Erreur lors de la récupération des données météo pour {city}: {str(e)}" 70 71@tool72def get_current_time_in_timezone(timezone: str) -> str:73 """A tool that fetches the current local time in a specified timezone.74 Args:75 timezone: A string representing a valid timezone (e.g., 'America/New_York').76 """77 try:78 # Create timezone object79 tz = pytz.timezone(timezone)80 # Get current time in that timezone81 local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")82 return f"The current local time in {timezone} is: {local_time}"83 except Exception as e:84 return f"Error fetching time for timezone '{timezone}': {str(e)}"85 86@tool87def calculator(a: int, b: int) -> int:88 """Multiply two integers 89 90 Args:91 a: First integer input for calculation92 b: Second integer input for calculation93 94 Returns:95 int: the Product of a and b96 """97 return a * b98 99 100final_answer = FinalAnswerTool()101model = HfApiModel(102max_tokens=2096,103temperature=0.5,104#model_id = "meta-llama/Llama-3.2-3B-Instruct",105#model_id='Qwen/Qwen2.5-Coder-32B-Instruct'106#model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloaded107model_id='https://jc26mwg228mkj8dw.us-east-1.aws.endpoints.huggingface.cloud',108custom_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, get_current_time_in_timezone, calculator, get_weather], ## 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()