Claude Code commited on
Commit
8bb095e
·
1 Parent(s): 6e71b49

fix: add error handling to export_chat function

Browse files
Files changed (1) hide show
  1. app.py +32 -28
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
- if not history:
355
- return "No conversation to export."
356
-
357
- import tempfile
358
- timestamp = datetime.utcnow().strftime("%Y%m%d_%H%M%S")
359
-
360
- if format_type == "json":
361
- filepath = tempfile.gettempdir() / f"cain_chat_{timestamp}.json"
362
- export_data = {
363
- "session_id": _session_id,
364
- "timestamp": datetime.utcnow().isoformat(),
365
- "messages": [{"role": "user" if i % 2 == 0 else "assistant", "content": msg}
366
- for pair in history for i, msg in enumerate(pair)]
367
- }
368
- with open(filepath, "w") as f:
369
- json.dump(export_data, f, indent=2)
370
- else: # txt
371
- filepath = tempfile.gettempdir() / f"cain_chat_{timestamp}.txt"
372
- with open(filepath, "w") as f:
373
- f.write(f"Cain Chat Export - Session: {_session_id}\n")
374
- f.write(f"Exported: {datetime.utcnow().isoformat()}\n")
375
- f.write("=" * 50 + "\n\n")
376
- for user_msg, bot_msg in history:
377
- f.write(f"User: {user_msg}\n\n")
378
- f.write(f"Cain: {bot_msg}\n\n")
379
- f.write("-" * 30 + "\n\n")
380
-
381
- return f"✅ Exported to {filepath.name}"
 
 
 
 
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):