maperez commited on
Commit
c55edd7
·
verified ·
1 Parent(s): 9a8c112

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -18
app.py CHANGED
@@ -1,23 +1,22 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
7
-
8
  from Gradio_UI import GradioUI
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_cutom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
  Args:
16
  arg1: the first argument
17
  arg2: the second argument
18
  """
19
- return "What magic will you build ?"
20
 
 
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
23
  """A tool that fetches the current local time in a specified timezone.
@@ -25,33 +24,66 @@ def get_current_time_in_timezone(timezone: str) -> str:
25
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
  """
27
  try:
28
- # Create timezone object
29
  tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
  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
  final_answer = FinalAnswerTool()
 
 
38
  model = HfApiModel(
39
- max_tokens=2096,
40
- temperature=0.5,
41
- model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloaded
42
- custom_role_conversions=None,
43
  )
44
 
45
-
46
- # Import tool from Hub
47
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
48
 
 
49
  with open("prompts.yaml", 'r') as stream:
50
  prompt_templates = yaml.safe_load(stream)
51
-
 
 
 
 
 
52
  agent = CodeAgent(
53
  model=model,
54
- tools=[final_answer], ## add your tools here (don't remove final answer)
55
  max_steps=6,
56
  verbosity_level=1,
57
  grammar=None,
@@ -61,5 +93,5 @@ agent = CodeAgent(
61
  prompt_templates=prompt_templates
62
  )
63
 
64
-
65
  GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
 
7
  from Gradio_UI import GradioUI
8
 
9
+ # Herramienta personalizada de ejemplo
10
  @tool
11
+ def my_cutom_tool(arg1: str, arg2: int) -> str:
12
+ """A tool that does nothing yet.
 
13
  Args:
14
  arg1: the first argument
15
  arg2: the second argument
16
  """
17
+ return "What magic will you build?"
18
 
19
+ # Herramienta para obtener la hora actual en una zona horaria específica
20
  @tool
21
  def get_current_time_in_timezone(timezone: str) -> str:
22
  """A tool that fetches the current local time in a specified timezone.
 
24
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
25
  """
26
  try:
27
+ # Crear objeto de zona horaria
28
  tz = pytz.timezone(timezone)
29
+ # Obtener la hora actual en esa zona horaria
30
  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 ciudad
36
+ @tool
37
+ def 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 final
62
  final_answer = FinalAnswerTool()
63
+
64
+ # Configuración del modelo
65
  model = HfApiModel(
66
+ max_tokens=2096,
67
+ temperature=0.5,
68
+ model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud', # Puede estar sobrecargado
69
+ custom_role_conversions=None,
70
  )
71
 
72
+ # Cargar herramienta de generación de imágenes desde el Hub
 
73
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
74
 
75
+ # Cargar plantillas de prompts desde un archivo YAML
76
  with open("prompts.yaml", 'r') as stream:
77
  prompt_templates = yaml.safe_load(stream)
78
+
79
+ # Crear instancias de las herramientas
80
+ search_tool = DuckDuckGoSearchTool()
81
+ weather_tool = get_current_weather
82
+
83
+ # Configurar el agente con las herramientas
84
  agent = 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,
 
93
  prompt_templates=prompt_templates
94
  )
95
 
96
+ # Lanzar la interfaz de Gradio
97
  GradioUI(agent).launch()