maperez/First_agent_template
0
1from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool2import datetime3import requests4import pytz5import yaml6from tools.final_answer import FinalAnswerTool7from Gradio_UI import GradioUI8 9# Herramienta personalizada de ejemplo10@tool11def my_cutom_tool(arg1: str, arg2: int) -> str:12 """A tool that does nothing yet.13 Args:14 arg1: the first argument15 arg2: the second argument16 """17 return "What magic will you build?"18 19# Herramienta para obtener la hora actual en una zona horaria específica20@tool21def get_current_time_in_timezone(timezone: str) -> str:22 """A tool that fetches the current local time in a specified timezone.23 Args:24 timezone: A string representing a valid timezone (e.g., 'America/New_York').25 """26 try:27 # Crear objeto de zona horaria28 tz = pytz.timezone(timezone)29 # Obtener la hora actual en esa zona horaria30 local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")31 return f"The current local time in {timezone} is: {local_time}"32 except Exception as e:33 return f"Error fetching time for timezone '{timezone}': {str(e)}"34 35# Herramienta para obtener el clima actual de una ciudad36@tool37def get_current_weather(city: str, api_key: str) -> str:38 """A tool that fetches the current weather for a specified city.39 Args:40 city: The name of the city to fetch the weather for.41 api_key: The API key for OpenWeatherMap.42 """43 base_url = "http://api.openweathermap.org/data/2.5/weather?"44 complete_url = f"{base_url}q={city}&appid={api_key}&units=metric"45 46 try:47 response = requests.get(complete_url)48 data = response.json()49 50 if data["cod"] != "404":51 main = data["main"]52 temperature = main["temp"]53 humidity = main["humidity"]54 weather_description = data["weather"][0]["description"]55 return f"The current temperature in {city} is {temperature}°C with {weather_description}. Humidity is {humidity}%."56 else:57 return f"City {city} not found."58 except Exception as e:59 return f"Error fetching weather data: {str(e)}"60 61# Herramienta de respuesta final62final_answer = FinalAnswerTool()63 64# Configuración del modelo65model = HfApiModel(66 max_tokens=2096,67 temperature=0.5,68 model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud', # Puede estar sobrecargado69 custom_role_conversions=None,70)71 72# Cargar herramienta de generación de imágenes desde el Hub73image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)74 75# Cargar plantillas de prompts desde un archivo YAML76with open("prompts.yaml", 'r') as stream:77 prompt_templates = yaml.safe_load(stream)78 79# Crear instancias de las herramientas80search_tool = DuckDuckGoSearchTool()81weather_tool = get_current_weather82 83# Configurar el agente con las herramientas84agent = CodeAgent(85 model=model,86 tools=[final_answer, search_tool, weather_tool, get_current_time_in_timezone], # Agregar herramientas aquí87 max_steps=6,88 verbosity_level=1,89 grammar=None,90 planning_interval=None,91 name=None,92 description=None,93 prompt_templates=prompt_templates94)95 96# Lanzar la interfaz de Gradio97GradioUI(agent).launch()