function save_session_to_disk
Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings.
/tf/active/vicechatdev/docchat/app.py
117 - 130
simple
Purpose
This function saves the current state of a chat session identified by session_id to a JSON file on disk. It is designed to be called within a thread-safe context (while holding session_lock) to prevent race conditions. The function retrieves session data from a global chat_sessions dictionary, converts datetime fields to ISO format strings for JSON serialization, and writes the data to a file in the SESSIONS_DIR directory. Error handling is included to log failures without raising exceptions.
Source Code
def save_session_to_disk(session_id):
"""Persist session to disk - must be called while holding session_lock"""
try:
if session_id in chat_sessions:
session_file = SESSIONS_DIR / f"{session_id}.json"
session_data = chat_sessions[session_id].copy()
# Convert datetime objects to strings
session_data['created_at'] = session_data['created_at'].isoformat()
session_data['updated_at'] = session_data['updated_at'].isoformat()
with open(session_file, 'w') as f:
json.dump(session_data, f, indent=2)
except Exception as e:
logger.error(f"Failed to save session {session_id}: {e}")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_id |
- | - | positional_or_keyword |
Parameter Details
session_id: A unique identifier (typically a string or UUID) for the chat session to be saved. This ID is used to look up the session in the chat_sessions dictionary and to name the output JSON file (e.g., '{session_id}.json').
Return Value
This function does not return any value (implicitly returns None). It performs a side effect of writing session data to disk. If an error occurs during the save operation, it logs the error but does not raise an exception.
Dependencies
jsonloggingpathlib
Required Imports
import json
import logging
from pathlib import Path
Usage Example
import json
import logging
from pathlib import Path
from datetime import datetime
from threading import Lock
# Setup
SESSIONS_DIR = Path('./sessions')
SESSIONS_DIR.mkdir(exist_ok=True)
chat_sessions = {}
session_lock = Lock()
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# Create a sample session
session_id = 'abc123'
chat_sessions[session_id] = {
'session_id': session_id,
'user_id': 'user456',
'messages': [{'role': 'user', 'content': 'Hello'}],
'created_at': datetime.now(),
'updated_at': datetime.now()
}
# Save session to disk (must hold lock)
with session_lock:
save_session_to_disk(session_id)
# Verify the file was created
session_file = SESSIONS_DIR / f'{session_id}.json'
print(f'Session saved: {session_file.exists()}')
Best Practices
- Always call this function while holding the session_lock to prevent concurrent access issues
- Ensure SESSIONS_DIR exists and is writable before calling this function
- The chat_sessions dictionary must contain the session_id as a key before calling
- Session data must include 'created_at' and 'updated_at' as datetime objects
- Consider implementing retry logic or more robust error handling for production use
- The function silently fails on errors (only logs), so check logs for save failures
- Ensure the logger is properly configured before using this function
- Consider adding validation to ensure session data is complete before saving
- For high-frequency saves, consider implementing a write-behind cache or batching mechanism
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function save_session_to_disk_v1 96.6% similar
-
function save_chat_session_to_file 87.0% similar
-
function load_session_from_disk 74.2% similar
-
function load_chat_session_from_file 72.6% similar
-
function load_all_sessions 71.1% similar