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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -85
app.py CHANGED
@@ -1,119 +1,80 @@
1
- # Autors: [Escriu aquí el teu nom] i [nom del company si en teniu]
2
- # Pràctica 26/05/2025 - Agent amb eines noves: traductor i resumidor
3
-
4
- # 1. Instal·lació automàtica de llibreries (al principi del fitxer)
5
- import subprocess
6
- import sys
7
-
8
- def install(package):
9
- subprocess.check_call([sys.executable, "-m", "pip", "install", package])
10
-
11
- # Instalar primero las dependencias pesadas
12
- install("torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu")
13
- install("transformers")
14
- install("deep-translator")
15
- install("langchain")
16
- install("sentencepiece")
17
-
18
- # 2. Importaciones después de las instalaciones
19
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
20
  import datetime
21
  import requests
22
  import pytz
23
  import yaml
24
  from tools.final_answer import FinalAnswerTool
25
- from Gradio_UI import GradioUI
26
- from langchain.tools import Tool
27
-
28
- # 3. Configuración del traductor (no requiere PyTorch/TensorFlow)
29
- from deep_translator import GoogleTranslator
30
 
31
- def translate_text(text: str) -> str:
32
- """Traduce texto a inglés usando Google Translate"""
33
- try:
34
- return GoogleTranslator(source='auto', target='en').translate(text)
35
- except Exception as e:
36
- return f"Error en traducción: {str(e)}"
37
-
38
- translate_tool = Tool(
39
- name="TextTranslator",
40
- func=translate_text,
41
- description="Translate input text to English. Input can be in any language."
42
- )
43
-
44
- # 4. Configuración alternativa del resumidor (sin PyTorch/TensorFlow)
45
- from transformers import pipeline
46
-
47
- try:
48
- # Intentamos cargar un modelo pequeño que pueda funcionar sin GPU
49
- summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
50
- except:
51
- # Fallback a una implementación más simple si falla
52
- def simple_summarizer(text: str) -> str:
53
- """Resumen básico tomando las primeras oraciones"""
54
- sentences = text.split('.')
55
- return '. '.join(sentences[:3]) + '.' if len(sentences) > 3 else text
56
-
57
- summarizer = simple_summarizer
58
-
59
- def summarize_text(text: str) -> str:
60
- try:
61
- if callable(summarizer):
62
- summary = summarizer(text, max_length=130, min_length=30, do_sample=False)
63
- return summary[0]['summary_text'] if isinstance(summary, list) else summary
64
- return summarizer(text)
65
- except Exception as e:
66
- return f"Error en resumen: {str(e)}"
67
 
68
- summarize_tool = Tool(
69
- name="TextSummarizer",
70
- func=summarize_text,
71
- description="Summarize input text. Use it for long paragraphs or documents."
72
- )
 
 
 
 
 
73
 
74
- # 5. Herramientas adicionales
75
  @tool
76
  def get_current_time_in_timezone(timezone: str) -> str:
77
- """Obtiene la hora actual en una zona horaria específica"""
 
 
 
78
  try:
 
79
  tz = pytz.timezone(timezone)
 
80
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
81
  return f"The current local time in {timezone} is: {local_time}"
82
  except Exception as e:
83
- return f"Error fetching time: {str(e)}"
 
 
 
84
 
85
- # 6. Configuración del agente
86
  final_answer = FinalAnswerTool()
87
 
 
 
 
 
88
  model = HfApiModel(
89
  max_tokens=2096,
90
  temperature=0.5,
91
- model_id="mistralai/Mistral-Small-3.1-24B-Instruct-2503",
 
 
 
 
 
 
92
  custom_role_conversions=None,
93
  )
94
 
95
- try:
96
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
97
- except:
98
- @tool
99
- def image_generation_tool(prompt: str) -> str:
100
- return "Image generation disabled in this environment"
101
 
102
- # 7. Carga de plantillas y creación del agente
 
 
 
103
  with open("prompts.yaml", 'r') as stream:
104
  prompt_templates = yaml.safe_load(stream)
105
 
 
106
  agent = CodeAgent(
107
  model=model,
108
- tools=[
109
- translate_tool,
110
- summarize_tool,
111
- get_current_time_in_timezone,
112
- image_generation_tool,
113
- final_answer
114
- ],
 
115
  prompt_templates=prompt_templates
116
  )
117
 
118
- # 8. Iniciar la interfaz
119
  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
 
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.
24
+ Args:
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,
74
+ planning_interval=None,
75
+ name=None,
76
+ description=None,
77
  prompt_templates=prompt_templates
78
  )
79
 
 
80
  GradioUI(agent).launch()