function save_chat_session_to_file
Persists a chat session object to a JSON file in the designated chat sessions directory, using the session's ID as the filename.
/tf/active/vicechatdev/vice_ai/complex_app.py
141 - 150
simple
Purpose
This function provides file-based persistence for chat session data. It serializes a chat_session object to JSON format and saves it to disk, enabling session recovery, audit trails, and data persistence across application restarts. The function includes error handling and logging for debugging and monitoring purposes.
Source Code
def save_chat_session_to_file(chat_session):
"""Save chat session to file"""
try:
ensure_directories()
file_path = os.path.join(CHAT_SESSIONS_DIR, f"{chat_session.id}.json")
with open(file_path, 'w') as f:
json.dump(chat_session.to_dict(), f, indent=2)
logger.info(f"💾 Chat session saved to file: {chat_session.id}")
except Exception as e:
logger.error(f"❌ Failed to save chat session {chat_session.id}: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
chat_session |
- | - | positional_or_keyword |
Parameter Details
chat_session: A chat session object that must have an 'id' attribute (used for filename) and a 'to_dict()' method that returns a dictionary representation suitable for JSON serialization. This object typically contains conversation history, metadata, and session state.
Return Value
This function does not return any value (implicitly returns None). Success or failure is communicated through logging messages. On success, logs an info message with the session ID. On failure, logs an error message with the exception details.
Dependencies
osjsonlogging
Required Imports
import os
import json
import logging
Usage Example
import os
import json
import logging
# Setup
CHAT_SESSIONS_DIR = './chat_sessions'
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def ensure_directories():
os.makedirs(CHAT_SESSIONS_DIR, exist_ok=True)
# Mock chat session class
class ChatSession:
def __init__(self, session_id, messages):
self.id = session_id
self.messages = messages
def to_dict(self):
return {
'id': self.id,
'messages': self.messages,
'timestamp': '2024-01-01T12:00:00'
}
# Usage
chat_session = ChatSession('session_123', ['Hello', 'How are you?'])
save_chat_session_to_file(chat_session)
# Result: Creates './chat_sessions/session_123.json' with serialized session data
Best Practices
- Ensure the chat_session object has a valid 'id' attribute that is filesystem-safe (no special characters that could cause path issues)
- The chat_session.to_dict() method should return only JSON-serializable data types (strings, numbers, lists, dicts, booleans, None)
- Call ensure_directories() before first use to guarantee the target directory exists
- Consider implementing file locking mechanisms if multiple processes/threads might write to the same session file simultaneously
- Monitor disk space as chat sessions accumulate over time; implement cleanup/archival strategies for old sessions
- The function silently catches all exceptions - consider whether specific exception types should be handled differently or re-raised
- For production use, consider adding file write validation (e.g., reading back the file to verify integrity)
- Session IDs should be unique to prevent overwriting existing session files
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function save_session_to_disk_v1 88.6% similar
-
function save_session_to_disk 87.0% similar
-
function load_chat_session_from_file 82.9% similar
-
function load_all_chat_sessions 73.1% similar
-
function load_all_sessions 68.0% similar