Spaces:
Sleeping
Sleeping
Update agent.py
Browse files
agent.py
CHANGED
@@ -1,239 +1,63 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
import
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
OPENAI_API_VERSION = os.getenv("OPENAI_API_VERSION")
|
15 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
16 |
-
|
17 |
-
# Herramientas definidas
|
18 |
-
duck_search = Tool.from_space("duckduckgo-search-v1", name="duck_search", description="Búsqueda en DuckDuckGo", api_name="/predict")
|
19 |
-
google_search = Tool.from_space("google-search-v1", name="google_search", description="Búsqueda en Google", api_name="/predict")
|
20 |
-
visit_page = Tool.from_space("visit-webpage-v1", name="visit_page", description="Visita páginas web", api_name="/predict")
|
21 |
-
wiki_search = Tool.from_space("wikipedia-search-v1", name="wiki_search", description="Búsqueda en Wikipedia", api_name="/predict")
|
22 |
-
do_python = Tool.from_space("python-interpreter-v1", name="do_python", description="Ejecuta código Python", api_name="/predict")
|
23 |
-
final_answer = FinalAnswerTool()
|
24 |
-
|
25 |
-
# Inicializar el cliente de Tavily
|
26 |
-
tavily_search = TavilyClient()
|
27 |
-
|
28 |
-
speech_to_text_tool = Tool.from_space("hf-audio/whisper-large-v3-turbo",
|
29 |
-
name="speech_to_text_tool",
|
30 |
-
description="Convierte audio en texto proporcionando un archivo o URL.",
|
31 |
-
api_name="/predict")
|
32 |
-
|
33 |
-
visual_qa_tool = Tool.from_space("sitammeur/PicQ",
|
34 |
-
name="visual_qa_tool",
|
35 |
-
description="Responde preguntas sobre una imagen proporcionada.",
|
36 |
-
api_name="/predict")
|
37 |
-
|
38 |
-
# Agente básico
|
39 |
-
class BasicAgent:
|
40 |
def __init__(self):
|
41 |
-
#
|
42 |
self.web_agent = CodeAgent(
|
43 |
-
model=
|
44 |
-
|
45 |
-
azure_endpoint=AZURE_OPENAI_ENDPOINT,
|
46 |
-
api_key=AZURE_OPENAI_API_KEY,
|
47 |
-
api_version=OPENAI_API_VERSION
|
48 |
-
),
|
49 |
-
tools=[duck_search, google_search, wiki_search, visit_page, final_answer],
|
50 |
max_steps=8,
|
51 |
name="web_agent",
|
52 |
-
description="
|
53 |
-
add_base_tools=True
|
54 |
)
|
55 |
|
56 |
-
# Agente para convertir audio a texto
|
57 |
self.audio_agent = CodeAgent(
|
58 |
-
model=
|
59 |
-
|
60 |
-
azure_endpoint=AZURE_OPENAI_ENDPOINT,
|
61 |
-
api_key=AZURE_OPENAI_API_KEY,
|
62 |
-
api_version=OPENAI_API_VERSION
|
63 |
-
),
|
64 |
-
tools=[speech_to_text_tool, final_answer],
|
65 |
max_steps=4,
|
66 |
name="audio_agent",
|
67 |
-
description="
|
68 |
-
add_base_tools=True
|
69 |
)
|
70 |
|
71 |
-
# Agente para ejecutar código Python
|
72 |
self.py_agent = CodeAgent(
|
73 |
-
model=
|
74 |
-
|
75 |
-
azure_endpoint=AZURE_OPENAI_ENDPOINT,
|
76 |
-
api_key=AZURE_OPENAI_API_KEY,
|
77 |
-
api_version=OPENAI_API_VERSION
|
78 |
-
),
|
79 |
-
tools=[do_python, final_answer],
|
80 |
additional_authorized_imports=["json", "pandas", "numpy", "regex"],
|
81 |
max_steps=8,
|
82 |
name="python_code_agent",
|
83 |
-
description="
|
84 |
-
add_base_tools=True
|
85 |
)
|
86 |
|
87 |
-
# Agente para responder preguntas sobre imágenes
|
88 |
self.visual_agent = CodeAgent(
|
89 |
-
model=
|
90 |
-
|
91 |
-
azure_endpoint=AZURE_OPENAI_ENDPOINT,
|
92 |
-
api_key=AZURE_OPENAI_API_KEY,
|
93 |
-
api_version=OPENAI_API_VERSION
|
94 |
-
),
|
95 |
-
tools=[visual_qa_tool, final_answer],
|
96 |
max_steps=4,
|
97 |
name="visual_qa_agent",
|
98 |
-
description="
|
99 |
-
add_base_tools=True
|
100 |
)
|
101 |
|
102 |
-
# Agente principal que maneja los subagentes
|
103 |
self.manager_agent = CodeAgent(
|
104 |
-
model=
|
105 |
-
model_id=AZURE_OPENAI_MODEL,
|
106 |
-
azure_endpoint=AZURE_OPENAI_ENDPOINT,
|
107 |
-
api_key=AZURE_OPENAI_API_KEY,
|
108 |
-
api_version=OPENAI_API_VERSION
|
109 |
-
),
|
110 |
tools=[],
|
111 |
managed_agents=[self.web_agent, self.audio_agent, self.py_agent, self.visual_agent],
|
112 |
planning_interval=8,
|
113 |
verbosity_level=2,
|
114 |
max_steps=12,
|
115 |
-
add_base_tools=True
|
116 |
)
|
117 |
|
118 |
def forward(self, question: str, attachment: str = None) -> str:
|
119 |
-
# Verificamos que el agente principal esté inicializado antes de llamarlo
|
120 |
-
if not self.manager_agent:
|
121 |
-
raise Exception("El agente principal no está inicializado correctamente.")
|
122 |
-
|
123 |
if attachment:
|
124 |
result = self.manager_agent.run(question, additional_args={"attachment": attachment})
|
125 |
else:
|
126 |
result = self.manager_agent.run(question)
|
127 |
return result
|
128 |
-
|
129 |
-
|
130 |
-
# Función para ejecutar el flujo de trabajo completo
|
131 |
-
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
132 |
-
"""
|
133 |
-
Obtiene todas las preguntas, ejecuta el BasicAgent sobre ellas, envía las respuestas y muestra los resultados.
|
134 |
-
"""
|
135 |
-
space_id = os.getenv("SPACE_ID") # Obtener el ID del espacio para enviar el enlace al código
|
136 |
-
|
137 |
-
if profile:
|
138 |
-
username = f"{profile.username}"
|
139 |
-
print(f"Usuario logueado: {username}")
|
140 |
-
else:
|
141 |
-
print("Usuario no logueado.")
|
142 |
-
return "Por favor, inicie sesión en Hugging Face.", None
|
143 |
-
|
144 |
-
api_url = DEFAULT_API_URL
|
145 |
-
questions_url = f"{api_url}/questions"
|
146 |
-
attachments_url = f"{api_url}/files/"
|
147 |
-
submit_url = f"{api_url}/submit"
|
148 |
-
|
149 |
-
# Inicializar el agente
|
150 |
-
try:
|
151 |
-
print("Iniciando agente...")
|
152 |
-
agent = BasicAgent() # Inicialización correcta del agente
|
153 |
-
except Exception as e:
|
154 |
-
print(f"Error al inicializar el agente: {e}")
|
155 |
-
return f"Error al inicializar el agente: {e}", None
|
156 |
-
|
157 |
-
# 2. Obtener preguntas
|
158 |
-
print(f"Obteniendo preguntas de: {questions_url}")
|
159 |
-
try:
|
160 |
-
response = requests.get(questions_url, timeout=15)
|
161 |
-
response.raise_for_status()
|
162 |
-
questions_data = response.json()
|
163 |
-
if not questions_data:
|
164 |
-
print("La lista de preguntas está vacía.")
|
165 |
-
return "La lista de preguntas está vacía o en formato incorrecto.", None
|
166 |
-
print(f"Obtenidas {len(questions_data)} preguntas.")
|
167 |
-
for q in questions_data:
|
168 |
-
file_name = q.get("file_name", "")
|
169 |
-
task_id = q.get("task_id")
|
170 |
-
if file_name and task_id:
|
171 |
-
try:
|
172 |
-
att_response = requests.get(f"{attachments_url}{task_id}", timeout=15)
|
173 |
-
att_response.raise_for_status()
|
174 |
-
q["attachment_b64"] = att_response.text
|
175 |
-
except Exception as e:
|
176 |
-
print(f"Error al obtener archivo adjunto para tarea {task_id}: {e}")
|
177 |
-
q["attachment_b64"] = None
|
178 |
-
except requests.exceptions.RequestException as e:
|
179 |
-
print(f"Error al obtener preguntas: {e}")
|
180 |
-
return f"Error al obtener preguntas: {e}", None
|
181 |
-
|
182 |
-
# 3. Ejecutar agente sobre preguntas
|
183 |
-
results_log = []
|
184 |
-
answers_payload = []
|
185 |
-
print(f"Ejecutando agente sobre {len(questions_data)} preguntas...")
|
186 |
-
for item in questions_data:
|
187 |
-
task_id = item.get("task_id")
|
188 |
-
question_text = item.get("question", "")
|
189 |
-
attachment_b64 = item.get("attachment_b64", "")
|
190 |
-
if attachment_b64:
|
191 |
-
question_text = f"{question_text}\n\n[ATTACHMENT:]\n{attachment_b64}"
|
192 |
-
if not task_id or question_text is None:
|
193 |
-
print(f"Saltando elemento con task_id o pregunta faltante: {item}")
|
194 |
-
continue
|
195 |
-
try:
|
196 |
-
submitted_answer = agent.forward(question_text) # Aquí ejecutamos el agente para obtener la respuesta
|
197 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
198 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
199 |
-
except Exception as e:
|
200 |
-
print(f"Error ejecutando agente sobre tarea {task_id}: {e}")
|
201 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"ERROR AGENTE: {e}"})
|
202 |
-
|
203 |
-
if not answers_payload:
|
204 |
-
print("El agente no generó respuestas.")
|
205 |
-
return "El agente no generó respuestas.", None
|
206 |
-
|
207 |
-
# 4. Preparar la sumisión
|
208 |
-
submission_data = {"username": username.strip(), "answers": answers_payload}
|
209 |
-
print(f"Enviando respuestas para el usuario '{username}'...")
|
210 |
-
|
211 |
-
# 5. Enviar respuestas
|
212 |
-
try:
|
213 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
214 |
-
response.raise_for_status()
|
215 |
-
result_data = response.json()
|
216 |
-
final_status = (
|
217 |
-
f"¡Envío exitoso!\n"
|
218 |
-
f"Usuario: {result_data.get('username')}\n"
|
219 |
-
f"Puntuación total: {result_data.get('score', 'N/A')}% "
|
220 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correctas)"
|
221 |
-
)
|
222 |
-
print("Envío exitoso.")
|
223 |
-
return final_status, results_log
|
224 |
-
except requests.exceptions.RequestException as e:
|
225 |
-
status_message = f"Error al enviar respuestas: {e}"
|
226 |
-
print(status_message)
|
227 |
-
return status_message, results_log
|
228 |
-
|
229 |
-
# Interfaz de Gradio
|
230 |
-
with gr.Blocks() as demo:
|
231 |
-
gr.Markdown("# Evaluador de Agente Básico")
|
232 |
-
gr.LoginButton()
|
233 |
-
run_button = gr.Button("Ejecutar Evaluación y Enviar Todas las Respuestas")
|
234 |
-
status_output = gr.Textbox(label="Resultado de Ejecución / Envío", lines=5, interactive=False)
|
235 |
-
results_table = gr.DataFrame(label="Preguntas y Respuestas del Agente", wrap=True)
|
236 |
-
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
237 |
-
|
238 |
-
if __name__ == "__main__":
|
239 |
-
demo.launch(debug=True, share=False)
|
|
|
1 |
+
import agent_tools
|
2 |
+
from smolagents import CodeAgent, AzureOpenAIServerModel
|
3 |
+
import my_tokens
|
4 |
+
|
5 |
+
# Instancia del modelo
|
6 |
+
model = AzureOpenAIServerModel(
|
7 |
+
model_id=my_tokens.AZURE_OPENAI_MODEL,
|
8 |
+
azure_endpoint=my_tokens.AZURE_OPENAI_ENDPOINT,
|
9 |
+
api_key=my_tokens.AZURE_OPENAI_API_KEY,
|
10 |
+
api_version=my_tokens.OPENAI_API_VERSION
|
11 |
+
)
|
12 |
+
|
13 |
+
class CustomAgent:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
def __init__(self):
|
15 |
+
# Definir agentes de trabajo con sus herramientas
|
16 |
self.web_agent = CodeAgent(
|
17 |
+
model=model,
|
18 |
+
tools=[agent_tools.google_search, agent_tools.wiki_search, agent_tools.visit_page, agent_tools.final_answer],
|
|
|
|
|
|
|
|
|
|
|
19 |
max_steps=8,
|
20 |
name="web_agent",
|
21 |
+
description="Este agente maneja búsquedas web."
|
|
|
22 |
)
|
23 |
|
|
|
24 |
self.audio_agent = CodeAgent(
|
25 |
+
model=model,
|
26 |
+
tools=[agent_tools.speech_to_text_tool, agent_tools.final_answer],
|
|
|
|
|
|
|
|
|
|
|
27 |
max_steps=4,
|
28 |
name="audio_agent",
|
29 |
+
description="Este agente convierte audio a texto."
|
|
|
30 |
)
|
31 |
|
|
|
32 |
self.py_agent = CodeAgent(
|
33 |
+
model=model,
|
34 |
+
tools=[agent_tools.do_python, agent_tools.final_answer],
|
|
|
|
|
|
|
|
|
|
|
35 |
additional_authorized_imports=["json", "pandas", "numpy", "regex"],
|
36 |
max_steps=8,
|
37 |
name="python_code_agent",
|
38 |
+
description="Este agente ejecuta y valida código Python."
|
|
|
39 |
)
|
40 |
|
|
|
41 |
self.visual_agent = CodeAgent(
|
42 |
+
model=model,
|
43 |
+
tools=[agent_tools.visual_qa_tool, agent_tools.final_answer],
|
|
|
|
|
|
|
|
|
|
|
44 |
max_steps=4,
|
45 |
name="visual_qa_agent",
|
46 |
+
description="Este agente responde preguntas sobre imágenes."
|
|
|
47 |
)
|
48 |
|
|
|
49 |
self.manager_agent = CodeAgent(
|
50 |
+
model=model,
|
|
|
|
|
|
|
|
|
|
|
51 |
tools=[],
|
52 |
managed_agents=[self.web_agent, self.audio_agent, self.py_agent, self.visual_agent],
|
53 |
planning_interval=8,
|
54 |
verbosity_level=2,
|
55 |
max_steps=12,
|
|
|
56 |
)
|
57 |
|
58 |
def forward(self, question: str, attachment: str = None) -> str:
|
|
|
|
|
|
|
|
|
59 |
if attachment:
|
60 |
result = self.manager_agent.run(question, additional_args={"attachment": attachment})
|
61 |
else:
|
62 |
result = self.manager_agent.run(question)
|
63 |
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|