function save_session_to_disk_v1
Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings for storage.
/tf/active/vicechatdev/docchat/blueprint.py
52 - 65
simple
Purpose
This function saves the current state of a chat session identified by session_id to a JSON file on disk. It retrieves session data from an in-memory chat_sessions dictionary, converts datetime objects to ISO format strings for JSON serialization, and writes the data to a file in the SESSIONS_DIR directory. This enables session persistence across application restarts and provides a backup mechanism for chat history.
Source Code
def save_session_to_disk(session_id):
"""Persist session to disk"""
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 (likely 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. Must correspond to an existing session in the chat_sessions dictionary.
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 or return an error indicator.
Dependencies
jsonloggingpathlibdatetime
Required Imports
import json
import logging
from pathlib import Path
from datetime import datetime
Usage Example
import json
import logging
from pathlib import Path
from datetime import datetime
# Setup required module-level variables
SESSIONS_DIR = Path('./sessions')
SESSIONS_DIR.mkdir(exist_ok=True)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
chat_sessions = {
'session_123': {
'session_id': 'session_123',
'user_id': 'user_456',
'messages': [{'role': 'user', 'content': 'Hello'}],
'created_at': datetime.now(),
'updated_at': datetime.now()
}
}
def save_session_to_disk(session_id):
try:
if session_id in chat_sessions:
session_file = SESSIONS_DIR / f"{session_id}.json"
session_data = chat_sessions[session_id].copy()
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}")
# Usage
save_session_to_disk('session_123')
print(f"Session saved to {SESSIONS_DIR / 'session_123.json'}")
Best Practices
- Ensure SESSIONS_DIR exists and is writable before calling this function
- The function silently fails on errors (only logs them), so check logs if sessions aren't being saved
- Session data is copied before modification to avoid mutating the original in-memory session
- Only datetime objects in 'created_at' and 'updated_at' fields are converted; if other datetime fields exist in session_data, they may cause JSON serialization errors
- Consider adding validation to ensure session_id exists in chat_sessions before attempting to save
- The function uses shallow copy (.copy()), so nested mutable objects will still reference the original session data
- File naming uses session_id directly; ensure session_id contains only filesystem-safe characters
- Consider implementing file locking if multiple processes/threads might save the same session simultaneously
- No return value means callers cannot determine if save succeeded without checking logs or filesystem
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function save_session_to_disk 96.6% similar
-
function save_chat_session_to_file 88.6% similar
-
function load_session_from_disk 74.4% similar
-
function load_chat_session_from_file 74.1% similar
-
function load_all_sessions 72.4% similar