Update app.py
Browse files
app.py
CHANGED
|
@@ -223,7 +223,6 @@ def ejecutar_codigo_sandbox(codigo, nombre):
|
|
| 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):
|
|
@@ -233,57 +232,57 @@ def safe_str(val):
|
|
| 233 |
|
| 234 |
def normalize_history(history):
|
| 235 |
"""
|
| 236 |
-
Normaliza history
|
| 237 |
-
|
|
|
|
|
|
|
| 238 |
"""
|
| 239 |
normalized = []
|
| 240 |
if not isinstance(history, list):
|
| 241 |
return normalized
|
| 242 |
|
| 243 |
for item in history:
|
| 244 |
-
user_msg = ""
|
| 245 |
-
assistant_msg = ""
|
| 246 |
-
|
| 247 |
if isinstance(item, dict):
|
| 248 |
-
#
|
| 249 |
-
if "
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
assistant_msg = safe_str(item
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 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 |
-
|
| 268 |
-
|
| 269 |
-
|
| 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
|
| 284 |
-
messages.append({"role": "
|
| 285 |
-
if item["assistant"]:
|
| 286 |
-
messages.append({"role": "assistant", "content": item["assistant"]})
|
| 287 |
return messages
|
| 288 |
|
| 289 |
|
|
@@ -294,12 +293,14 @@ def run_chat(message, history, user_context, max_tokens, temperature, top_p, tok
|
|
| 294 |
# --- SEGURIDAD ---
|
| 295 |
for bloqueo in BLOQUEOS_JAILBREAK:
|
| 296 |
if bloqueo in message.lower():
|
| 297 |
-
|
|
|
|
| 298 |
yield chatbot_output, "", "", "⛔ Bloqueado por seguridad.", ""
|
| 299 |
return
|
| 300 |
|
| 301 |
if not HF_TOKEN:
|
| 302 |
-
|
|
|
|
| 303 |
yield chatbot_output, "", "", "Configura HF_TOKEN.", ""
|
| 304 |
return
|
| 305 |
|
|
@@ -320,20 +321,19 @@ def run_chat(message, history, user_context, max_tokens, temperature, top_p, tok
|
|
| 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
|
| 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
|
| 337 |
resp_text = ""
|
| 338 |
try:
|
| 339 |
for chunk in client.chat_completion(
|
|
@@ -345,13 +345,17 @@ def run_chat(message, history, user_context, max_tokens, temperature, top_p, tok
|
|
| 345 |
):
|
| 346 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 347 |
resp_text += chunk.choices[0].delta.content
|
| 348 |
-
chatbot_so_far = norm_history + [
|
|
|
|
|
|
|
|
|
|
| 349 |
yield chatbot_so_far, "", "", "Generando...", ""
|
| 350 |
except Exception as e:
|
| 351 |
error_msg = f"Error IA: {e}"
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
|
|
|
| 355 |
yield chatbot_output, "", "", error_msg, ""
|
| 356 |
return
|
| 357 |
|
|
@@ -371,7 +375,10 @@ def run_chat(message, history, user_context, max_tokens, temperature, top_p, tok
|
|
| 371 |
if exito:
|
| 372 |
break
|
| 373 |
intentos += 1
|
| 374 |
-
chatbot_so_far = norm_history + [
|
|
|
|
|
|
|
|
|
|
| 375 |
yield chatbot_so_far, "", "", ultima_ejecucion, ""
|
| 376 |
try:
|
| 377 |
new_resp = ""
|
|
@@ -397,7 +404,10 @@ def run_chat(message, history, user_context, max_tokens, temperature, top_p, tok
|
|
| 397 |
break
|
| 398 |
|
| 399 |
# --- Output final ---
|
| 400 |
-
chatbot_output = norm_history + [
|
|
|
|
|
|
|
|
|
|
| 401 |
yield chatbot_output, resp_text, resp_text, ultima_ejecucion, memoria
|
| 402 |
|
| 403 |
|
|
|
|
| 223 |
|
| 224 |
|
| 225 |
def safe_str(val):
|
|
|
|
| 226 |
if val is None:
|
| 227 |
return ""
|
| 228 |
if isinstance(val, str):
|
|
|
|
| 232 |
|
| 233 |
def normalize_history(history):
|
| 234 |
"""
|
| 235 |
+
Normaliza history del chatbot de Gradio a formato limpio.
|
| 236 |
+
Gradio 5.x devuelve: [{"role": "user"/"assistant", "content": "..."}, ...]
|
| 237 |
+
Otras versiones: [{"user": "...", "assistant": "..."}]
|
| 238 |
+
Legacy: [("user...", "assistant..."), ...]
|
| 239 |
"""
|
| 240 |
normalized = []
|
| 241 |
if not isinstance(history, list):
|
| 242 |
return normalized
|
| 243 |
|
| 244 |
for item in history:
|
|
|
|
|
|
|
|
|
|
| 245 |
if isinstance(item, dict):
|
| 246 |
+
# Gradio 5.x: {"role": "user"|"assistant", "content": "..."}
|
| 247 |
+
if "role" in item and "content" in item:
|
| 248 |
+
role = item["role"]
|
| 249 |
+
content = safe_str(item["content"])
|
| 250 |
+
if role in ("user", "assistant", "system"):
|
| 251 |
+
normalized.append({"role": role, "content": content})
|
| 252 |
+
# Gradio 4.x: {"user": "...", "assistant": "..."}
|
| 253 |
+
elif "user" in item or "assistant" in item:
|
| 254 |
+
user_msg = safe_str(item.get("user", ""))
|
| 255 |
+
assistant_msg = safe_str(item.get("assistant", ""))
|
| 256 |
+
if user_msg:
|
| 257 |
+
normalized.append({"role": "user", "content": user_msg})
|
| 258 |
+
if assistant_msg:
|
| 259 |
+
normalized.append({"role": "assistant", "content": assistant_msg})
|
| 260 |
+
# Gradio 4.x alternate: {"message": "...", "response": "..."}
|
| 261 |
+
elif "message" in item or "response" in item:
|
| 262 |
+
user_msg = safe_str(item.get("message", ""))
|
| 263 |
+
assistant_msg = safe_str(item.get("response", ""))
|
| 264 |
+
if user_msg:
|
| 265 |
+
normalized.append({"role": "user", "content": user_msg})
|
| 266 |
+
if assistant_msg:
|
| 267 |
+
normalized.append({"role": "assistant", "content": assistant_msg})
|
| 268 |
elif isinstance(item, (list, tuple)) and len(item) >= 2:
|
| 269 |
+
# Legacy: (user_msg, assistant_msg)
|
| 270 |
user_msg = safe_str(item[0])
|
| 271 |
assistant_msg = safe_str(item[1])
|
| 272 |
+
if user_msg:
|
| 273 |
+
normalized.append({"role": "user", "content": user_msg})
|
| 274 |
+
if assistant_msg:
|
| 275 |
+
normalized.append({"role": "assistant", "content": assistant_msg})
|
|
|
|
|
|
|
|
|
|
| 276 |
|
| 277 |
return normalized
|
| 278 |
|
| 279 |
|
| 280 |
def history_to_messages(norm_history):
|
| 281 |
+
"""Convierte historial normalizado a formato messages para la API."""
|
|
|
|
|
|
|
| 282 |
messages = []
|
| 283 |
for item in norm_history:
|
| 284 |
+
if item.get("role") in ("user", "assistant", "system"):
|
| 285 |
+
messages.append({"role": item["role"], "content": item["content"]})
|
|
|
|
|
|
|
| 286 |
return messages
|
| 287 |
|
| 288 |
|
|
|
|
| 293 |
# --- SEGURIDAD ---
|
| 294 |
for bloqueo in BLOQUEOS_JAILBREAK:
|
| 295 |
if bloqueo in message.lower():
|
| 296 |
+
reply = {"role": "assistant", "content": "Soy Aura, asistente especializado exclusivamente en programación."}
|
| 297 |
+
chatbot_output = norm_history + [{"role": "user", "content": message}, reply]
|
| 298 |
yield chatbot_output, "", "", "⛔ Bloqueado por seguridad.", ""
|
| 299 |
return
|
| 300 |
|
| 301 |
if not HF_TOKEN:
|
| 302 |
+
reply = {"role": "assistant", "content": "⚠️ Falta HF_TOKEN. Configura tu API Key en Settings → Secrets."}
|
| 303 |
+
chatbot_output = norm_history + [{"role": "user", "content": message}, reply]
|
| 304 |
yield chatbot_output, "", "", "Configura HF_TOKEN.", ""
|
| 305 |
return
|
| 306 |
|
|
|
|
| 321 |
if memoria and memoria.strip():
|
| 322 |
final_system += f"\n--- MEMORIA ---\n{memoria}\n"
|
| 323 |
|
| 324 |
+
# --- Construir messages para la API ---
|
| 325 |
messages = [{"role": "system", "content": final_system}]
|
| 326 |
messages.extend(history_to_messages(norm_history))
|
| 327 |
user_content = message + (contexto_archivo if contexto_archivo else "")
|
| 328 |
messages.append({"role": "user", "content": user_content})
|
| 329 |
|
| 330 |
+
# --- Validar mensajes ---
|
| 331 |
for i, msg in enumerate(messages):
|
| 332 |
if not isinstance(msg, dict) or "role" not in msg or "content" not in msg:
|
|
|
|
| 333 |
messages[i] = {"role": "system", "content": "[mensaje corrupto eliminado]"}
|
| 334 |
msg["content"] = safe_str(msg["content"])
|
| 335 |
|
| 336 |
+
# --- Streaming ---
|
| 337 |
resp_text = ""
|
| 338 |
try:
|
| 339 |
for chunk in client.chat_completion(
|
|
|
|
| 345 |
):
|
| 346 |
if chunk.choices and chunk.choices[0].delta.content:
|
| 347 |
resp_text += chunk.choices[0].delta.content
|
| 348 |
+
chatbot_so_far = norm_history + [
|
| 349 |
+
{"role": "user", "content": message},
|
| 350 |
+
{"role": "assistant", "content": resp_text}
|
| 351 |
+
]
|
| 352 |
yield chatbot_so_far, "", "", "Generando...", ""
|
| 353 |
except Exception as e:
|
| 354 |
error_msg = f"Error IA: {e}"
|
| 355 |
+
chatbot_output = norm_history + [
|
| 356 |
+
{"role": "user", "content": message},
|
| 357 |
+
{"role": "assistant", "content": error_msg}
|
| 358 |
+
]
|
| 359 |
yield chatbot_output, "", "", error_msg, ""
|
| 360 |
return
|
| 361 |
|
|
|
|
| 375 |
if exito:
|
| 376 |
break
|
| 377 |
intentos += 1
|
| 378 |
+
chatbot_so_far = norm_history + [
|
| 379 |
+
{"role": "user", "content": message},
|
| 380 |
+
{"role": "assistant", "content": f"{resp_text}\n\n🔄 *Auto-corrigiendo ({intentos}/{MAX_AUTOFIX})...*"}
|
| 381 |
+
]
|
| 382 |
yield chatbot_so_far, "", "", ultima_ejecucion, ""
|
| 383 |
try:
|
| 384 |
new_resp = ""
|
|
|
|
| 404 |
break
|
| 405 |
|
| 406 |
# --- Output final ---
|
| 407 |
+
chatbot_output = norm_history + [
|
| 408 |
+
{"role": "user", "content": message},
|
| 409 |
+
{"role": "assistant", "content": resp_text}
|
| 410 |
+
]
|
| 411 |
yield chatbot_output, resp_text, resp_text, ultima_ejecucion, memoria
|
| 412 |
|
| 413 |
|