Update app.py
Browse files
app.py
CHANGED
|
@@ -222,10 +222,19 @@ def ejecutar_codigo_sandbox(codigo, nombre):
|
|
| 222 |
return False, "❌ Lenguaje no soportado"
|
| 223 |
|
| 224 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
def normalize_history(history):
|
| 226 |
"""
|
| 227 |
-
Normaliza history a
|
| 228 |
-
|
| 229 |
"""
|
| 230 |
normalized = []
|
| 231 |
if not isinstance(history, list):
|
|
@@ -236,49 +245,50 @@ def normalize_history(history):
|
|
| 236 |
assistant_msg = ""
|
| 237 |
|
| 238 |
if isinstance(item, dict):
|
| 239 |
-
#
|
| 240 |
-
if "user" in item
|
| 241 |
-
user_msg =
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
elif "
|
| 245 |
-
user_msg =
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
assistant_msg = content
|
| 255 |
elif isinstance(item, (list, tuple)) and len(item) >= 2:
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
if user_msg.strip() or assistant_msg.strip():
|
| 262 |
normalized.append({"user": user_msg, "assistant": assistant_msg})
|
| 263 |
|
| 264 |
return normalized
|
| 265 |
|
| 266 |
|
| 267 |
-
def history_to_messages(
|
| 268 |
"""
|
| 269 |
Convierte historial normalizado a formato messages para la API.
|
| 270 |
"""
|
| 271 |
messages = []
|
| 272 |
-
for item in
|
| 273 |
-
if item["user"]
|
| 274 |
messages.append({"role": "user", "content": item["user"]})
|
| 275 |
-
if item["assistant"]
|
| 276 |
messages.append({"role": "assistant", "content": item["assistant"]})
|
| 277 |
return messages
|
| 278 |
|
| 279 |
|
| 280 |
def run_chat(message, history, user_context, max_tokens, temperature, top_p, token, file_content, file_name, memoria):
|
| 281 |
-
# --- Normalizar history
|
| 282 |
norm_history = normalize_history(history)
|
| 283 |
|
| 284 |
# --- SEGURIDAD ---
|
|
@@ -310,13 +320,19 @@ def run_chat(message, history, user_context, max_tokens, temperature, top_p, tok
|
|
| 310 |
if memoria and memoria.strip():
|
| 311 |
final_system += f"\n--- MEMORIA ---\n{memoria}\n"
|
| 312 |
|
| 313 |
-
# --- Construir messages
|
| 314 |
messages = [{"role": "system", "content": final_system}]
|
| 315 |
messages.extend(history_to_messages(norm_history))
|
| 316 |
-
|
| 317 |
user_content = message + (contexto_archivo if contexto_archivo else "")
|
| 318 |
messages.append({"role": "user", "content": user_content})
|
| 319 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
# --- Streaming de respuesta ---
|
| 321 |
resp_text = ""
|
| 322 |
try:
|
|
@@ -332,8 +348,11 @@ def run_chat(message, history, user_context, max_tokens, temperature, top_p, tok
|
|
| 332 |
chatbot_so_far = norm_history + [{"user": message, "assistant": resp_text}]
|
| 333 |
yield chatbot_so_far, "", "", "Generando...", ""
|
| 334 |
except Exception as e:
|
| 335 |
-
|
| 336 |
-
|
|
|
|
|
|
|
|
|
|
| 337 |
return
|
| 338 |
|
| 339 |
# --- Auto-corrección ---
|
|
@@ -373,12 +392,15 @@ def run_chat(message, history, user_context, max_tokens, temperature, top_p, tok
|
|
| 373 |
resp_text += f"\n\n--- CORRECCIÓN {intentos} ---\n{new_resp}"
|
| 374 |
else:
|
| 375 |
break
|
| 376 |
-
except Exception:
|
|
|
|
| 377 |
break
|
| 378 |
|
| 379 |
# --- Output final ---
|
| 380 |
chatbot_output = norm_history + [{"user": message, "assistant": resp_text}]
|
| 381 |
yield chatbot_output, resp_text, resp_text, ultima_ejecucion, memoria
|
|
|
|
|
|
|
| 382 |
# ============================================
|
| 383 |
# INTERFAZ GRADIO
|
| 384 |
# ============================================
|
|
@@ -387,7 +409,6 @@ with gr.Blocks(title="Aura Programadora") as demo:
|
|
| 387 |
|
| 388 |
with gr.Row():
|
| 389 |
with gr.Column(scale=3):
|
| 390 |
-
# ✅ SIN type="pairs" — Gradio maneja el formato automáticamente
|
| 391 |
chatbot = gr.Chatbot(label="Chat", height=400)
|
| 392 |
chat_input = gr.Textbox(placeholder="Escribe tu código, error o pregunta de programación...", lines=2)
|
| 393 |
with gr.Row():
|
|
|
|
| 222 |
return False, "❌ Lenguaje no soportado"
|
| 223 |
|
| 224 |
|
| 225 |
+
def safe_str(val):
|
| 226 |
+
"""Convierte cualquier valor a string seguro."""
|
| 227 |
+
if val is None:
|
| 228 |
+
return ""
|
| 229 |
+
if isinstance(val, str):
|
| 230 |
+
return val
|
| 231 |
+
return str(val)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
def normalize_history(history):
|
| 235 |
"""
|
| 236 |
+
Normaliza history a lista limpia de dicts: [{"user": str, "assistant": str}, ...]
|
| 237 |
+
Elimina cualquier mensaje corrupto o inválido.
|
| 238 |
"""
|
| 239 |
normalized = []
|
| 240 |
if not isinstance(history, list):
|
|
|
|
| 245 |
assistant_msg = ""
|
| 246 |
|
| 247 |
if isinstance(item, dict):
|
| 248 |
+
# Intentar formato Gradio moderno primero
|
| 249 |
+
if "user" in item:
|
| 250 |
+
user_msg = safe_str(item["user"])
|
| 251 |
+
elif "message" in item:
|
| 252 |
+
user_msg = safe_str(item["message"])
|
| 253 |
+
elif "role" in item and item["role"] == "user":
|
| 254 |
+
user_msg = safe_str(item.get("content", ""))
|
| 255 |
+
|
| 256 |
+
if "assistant" in item:
|
| 257 |
+
assistant_msg = safe_str(item["assistant"])
|
| 258 |
+
elif "response" in item:
|
| 259 |
+
assistant_msg = safe_str(item["response"])
|
| 260 |
+
elif "role" in item and item["role"] == "assistant":
|
| 261 |
+
assistant_msg = safe_str(item.get("content", ""))
|
| 262 |
+
|
|
|
|
| 263 |
elif isinstance(item, (list, tuple)) and len(item) >= 2:
|
| 264 |
+
user_msg = safe_str(item[0])
|
| 265 |
+
assistant_msg = safe_str(item[1])
|
| 266 |
+
|
| 267 |
+
# Solo agregar si al menos uno tiene texto
|
| 268 |
+
user_msg = user_msg.strip() if user_msg else ""
|
| 269 |
+
assistant_msg = assistant_msg.strip() if assistant_msg else ""
|
| 270 |
|
| 271 |
+
if user_msg or assistant_msg:
|
|
|
|
| 272 |
normalized.append({"user": user_msg, "assistant": assistant_msg})
|
| 273 |
|
| 274 |
return normalized
|
| 275 |
|
| 276 |
|
| 277 |
+
def history_to_messages(norm_history):
|
| 278 |
"""
|
| 279 |
Convierte historial normalizado a formato messages para la API.
|
| 280 |
"""
|
| 281 |
messages = []
|
| 282 |
+
for item in norm_history:
|
| 283 |
+
if item["user"]:
|
| 284 |
messages.append({"role": "user", "content": item["user"]})
|
| 285 |
+
if item["assistant"]:
|
| 286 |
messages.append({"role": "assistant", "content": item["assistant"]})
|
| 287 |
return messages
|
| 288 |
|
| 289 |
|
| 290 |
def run_chat(message, history, user_context, max_tokens, temperature, top_p, token, file_content, file_name, memoria):
|
| 291 |
+
# --- Normalizar history ---
|
| 292 |
norm_history = normalize_history(history)
|
| 293 |
|
| 294 |
# --- SEGURIDAD ---
|
|
|
|
| 320 |
if memoria and memoria.strip():
|
| 321 |
final_system += f"\n--- MEMORIA ---\n{memoria}\n"
|
| 322 |
|
| 323 |
+
# --- Construir messages ---
|
| 324 |
messages = [{"role": "system", "content": final_system}]
|
| 325 |
messages.extend(history_to_messages(norm_history))
|
|
|
|
| 326 |
user_content = message + (contexto_archivo if contexto_archivo else "")
|
| 327 |
messages.append({"role": "user", "content": user_content})
|
| 328 |
|
| 329 |
+
# --- Validar que todos los mensajes tengan role y content ---
|
| 330 |
+
for i, msg in enumerate(messages):
|
| 331 |
+
if not isinstance(msg, dict) or "role" not in msg or "content" not in msg:
|
| 332 |
+
print(f"\n[DEBUG] Mensaje corrupto en posición {i}: {msg}")
|
| 333 |
+
messages[i] = {"role": "system", "content": "[mensaje corrupto eliminado]"}
|
| 334 |
+
msg["content"] = safe_str(msg["content"])
|
| 335 |
+
|
| 336 |
# --- Streaming de respuesta ---
|
| 337 |
resp_text = ""
|
| 338 |
try:
|
|
|
|
| 348 |
chatbot_so_far = norm_history + [{"user": message, "assistant": resp_text}]
|
| 349 |
yield chatbot_so_far, "", "", "Generando...", ""
|
| 350 |
except Exception as e:
|
| 351 |
+
error_msg = f"Error IA: {e}"
|
| 352 |
+
print(f"\n[DEBUG] Error en chat_completion: {e}")
|
| 353 |
+
print(f"[DEBUG] Messages enviadas: {messages}")
|
| 354 |
+
chatbot_output = norm_history + [{"user": message, "assistant": error_msg}]
|
| 355 |
+
yield chatbot_output, "", "", error_msg, ""
|
| 356 |
return
|
| 357 |
|
| 358 |
# --- Auto-corrección ---
|
|
|
|
| 392 |
resp_text += f"\n\n--- CORRECCIÓN {intentos} ---\n{new_resp}"
|
| 393 |
else:
|
| 394 |
break
|
| 395 |
+
except Exception as e:
|
| 396 |
+
print(f"\n[DEBUG] Error auto-corrección {intentos}: {e}")
|
| 397 |
break
|
| 398 |
|
| 399 |
# --- Output final ---
|
| 400 |
chatbot_output = norm_history + [{"user": message, "assistant": resp_text}]
|
| 401 |
yield chatbot_output, resp_text, resp_text, ultima_ejecucion, memoria
|
| 402 |
+
|
| 403 |
+
|
| 404 |
# ============================================
|
| 405 |
# INTERFAZ GRADIO
|
| 406 |
# ============================================
|
|
|
|
| 409 |
|
| 410 |
with gr.Row():
|
| 411 |
with gr.Column(scale=3):
|
|
|
|
| 412 |
chatbot = gr.Chatbot(label="Chat", height=400)
|
| 413 |
chat_input = gr.Textbox(placeholder="Escribe tu código, error o pregunta de programación...", lines=2)
|
| 414 |
with gr.Row():
|