aleexbescoos commited on
Commit
9f79217
·
verified ·
1 Parent(s): 88b369f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -35
app.py CHANGED
@@ -1,23 +1,12 @@
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_custom_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,49 +14,82 @@ 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
 
38
-
39
  final_answer = FinalAnswerTool()
40
-
41
- # 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:
42
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
43
-
44
 
45
  model = HfApiModel(
46
  max_tokens=2096,
47
  temperature=0.5,
48
- # The following two models were given originally but are giving Error
49
- # model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
50
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud',
51
- # Mistral works well. but writes its own tools
52
- model_id = "mistralai/Mistral-Small-3.1-24B-Instruct-2503",
53
- # model_id = "mistralai/Mistral-Nemo-Instruct-2407",
54
- # model_id = "microsoft/Phi-3-mini-4k-instruct",
55
  custom_role_conversions=None,
56
  )
57
 
58
-
59
-
60
- # Import tool from Hub
61
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
62
-
63
  with open("prompts.yaml", 'r') as stream:
64
  prompt_templates = yaml.safe_load(stream)
65
 
66
-
67
  agent = CodeAgent(
68
  model=model,
69
- tools=[final_answer, image_generation_tool, get_current_time_in_timezone, my_custom_tool], ## add your tools here (don't remove final answer)
70
- #tools=[final_answer, image_generation_tool, my_custom_tool, DuckDuckGoSearchTool()], ## add your tools here (don't remove final answer)
 
 
 
 
 
71
  max_steps=6,
72
  verbosity_level=1,
73
  grammar=None,
@@ -77,4 +99,5 @@ agent = CodeAgent(
77
  prompt_templates=prompt_templates
78
  )
79
 
 
80
  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 para obtener la hora en una zona horaria específica
 
 
 
 
 
 
 
 
 
 
10
  @tool
11
  def get_current_time_in_timezone(timezone: str) -> str:
12
  """A tool that fetches the current local time in a specified timezone.
 
14
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
15
  """
16
  try:
 
17
  tz = pytz.timezone(timezone)
 
18
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
19
  return f"The current local time in {timezone} is: {local_time}"
20
  except Exception as e:
21
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
22
 
23
+ # Primer nuevo tool: Traductor de texto
24
+ @tool
25
+ def text_translator(text: str, target_language: str) -> str:
26
+ """A tool that translates text to a specified target language.
27
+ Args:
28
+ text: The text to be translated.
29
+ target_language: The target language code (e.g., 'es' for Spanish, 'fr' for French).
30
+ """
31
+ try:
32
+ try:
33
+ from translate import Translator
34
+ except ImportError:
35
+ import subprocess, sys
36
+ subprocess.check_call([sys.executable, "-m", "pip", "install", "translate"])
37
+ from translate import Translator
38
+
39
+ translator = Translator(to_lang=target_language)
40
+ translation = translator.translate(text)
41
+ return f"Translation to {target_language}: {translation}"
42
+ except Exception as e:
43
+ return f"Translation failed: {str(e)}"
44
 
45
+ # Segundo nuevo tool: Búsqueda y resumen de información
46
+ @tool
47
+ def search_and_summarize(query: str, max_results: int = 3) -> str:
48
+ """A tool that performs a web search and provides summaries of the top results.
49
+ Args:
50
+ query: The search query.
51
+ max_results: Maximum number of results to return (default 3).
52
+ """
53
+ try:
54
+ search_results = DuckDuckGoSearchTool()(query)
55
+
56
+ if not search_results:
57
+ return "No results found for the query."
58
+
59
+ summaries = []
60
+ for i, result in enumerate(search_results[:max_results]):
61
+ summaries.append(f"Result {i+1}:\nTitle: {result.get('title', 'No title')}\n"
62
+ f"URL: {result.get('link', 'No URL')}\n"
63
+ f"Snippet: {result.get('snippet', 'No snippet available')}")
64
+
65
+ return "\n\n".join(summaries)
66
+ except Exception as e:
67
+ return f"Search and summarize failed: {str(e)}"
68
 
69
+ # Configuración del modelo y herramientas
70
  final_answer = FinalAnswerTool()
71
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
72
 
73
  model = HfApiModel(
74
  max_tokens=2096,
75
  temperature=0.5,
76
+ model_id="mistralai/Mistral-Small-3.1-24B-Instruct-2503",
 
 
 
 
 
 
77
  custom_role_conversions=None,
78
  )
79
 
 
 
 
 
 
80
  with open("prompts.yaml", 'r') as stream:
81
  prompt_templates = yaml.safe_load(stream)
82
 
83
+ # Creación del agente con todas las herramientas
84
  agent = CodeAgent(
85
  model=model,
86
+ tools=[
87
+ final_answer,
88
+ image_generation_tool,
89
+ get_current_time_in_timezone,
90
+ text_translator,
91
+ search_and_summarize
92
+ ],
93
  max_steps=6,
94
  verbosity_level=1,
95
  grammar=None,
 
99
  prompt_templates=prompt_templates
100
  )
101
 
102
+ # Lanzamiento de la interfaz
103
  GradioUI(agent).launch()