Spaces:
Sleeping
Sleeping
Claude Code commited on
Commit ·
8bb095e
1
Parent(s): 6e71b49
fix: add error handling to export_chat function
Browse files
app.py
CHANGED
|
@@ -351,34 +351,38 @@ def toggle_system_status() -> tuple[bool, str]:
|
|
| 351 |
|
| 352 |
def export_chat(history: list, format_type: str = "txt") -> str:
|
| 353 |
"""Export chat history to a file."""
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 382 |
|
| 383 |
|
| 384 |
def track_async_task(task: asyncio.Task):
|
|
|
|
| 351 |
|
| 352 |
def export_chat(history: list, format_type: str = "txt") -> str:
|
| 353 |
"""Export chat history to a file."""
|
| 354 |
+
try:
|
| 355 |
+
if not history:
|
| 356 |
+
return "No conversation to export."
|
| 357 |
+
|
| 358 |
+
import tempfile
|
| 359 |
+
timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
|
| 360 |
+
|
| 361 |
+
if format_type == "json":
|
| 362 |
+
filepath = tempfile.gettempdir() / f"cain_chat_{timestamp}.json"
|
| 363 |
+
export_data = {
|
| 364 |
+
"session_id": _session_id,
|
| 365 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 366 |
+
"messages": [{"role": "user" if i % 2 == 0 else "assistant", "content": msg}
|
| 367 |
+
for pair in history for i, msg in enumerate(pair)]
|
| 368 |
+
}
|
| 369 |
+
with open(filepath, "w") as f:
|
| 370 |
+
json.dump(export_data, f, indent=2)
|
| 371 |
+
else: # txt
|
| 372 |
+
filepath = tempfile.gettempdir() / f"cain_chat_{timestamp}.txt"
|
| 373 |
+
with open(filepath, "w") as f:
|
| 374 |
+
f.write(f"Cain Chat Export - Session: {_session_id}\n")
|
| 375 |
+
f.write(f"Exported: {datetime.utcnow().isoformat()}\n")
|
| 376 |
+
f.write("=" * 50 + "\n\n")
|
| 377 |
+
for user_msg, bot_msg in history:
|
| 378 |
+
f.write(f"User: {user_msg}\n\n")
|
| 379 |
+
f.write(f"Cain: {bot_msg}\n\n")
|
| 380 |
+
f.write("-" * 30 + "\n\n")
|
| 381 |
+
|
| 382 |
+
return f"✅ Exported to {filepath.name}"
|
| 383 |
+
except Exception as e:
|
| 384 |
+
logger.error(f"[EXPORT_ERROR] Failed to export chat: {e}")
|
| 385 |
+
return f"Export failed: {e}"
|
| 386 |
|
| 387 |
|
| 388 |
def track_async_task(task: asyncio.Task):
|