🔍 Code Extractor

function load_chat_session_from_file

Maturity: 44

Loads a chat session from a JSON file stored in the CHAT_SESSIONS_DIR directory using the provided session_id as the filename.

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
152 - 164
Complexity:
simple

Purpose

This function retrieves persisted chat session data from the filesystem. It reads a JSON file corresponding to the given session_id, deserializes it, and reconstructs a ChatSession object. This is typically used for session persistence and recovery in a chat application, allowing users to resume previous conversations or for the system to restore chat state after restarts.

Source Code

def load_chat_session_from_file(session_id):
    """Load chat session from file"""
    try:
        file_path = os.path.join(CHAT_SESSIONS_DIR, f"{session_id}.json")
        if os.path.exists(file_path):
            with open(file_path, 'r') as f:
                data = json.load(f)
            chat_session = ChatSession.from_dict(data)
            logger.info(f"📂 Chat session loaded from file: {session_id}")
            return chat_session
    except Exception as e:
        logger.error(f"❌ Failed to load chat session {session_id}: {e}")
    return None

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. This is used to construct the filename ({session_id}.json) to locate the corresponding session file in the CHAT_SESSIONS_DIR directory. Expected to be a valid filename-safe string.

Return Value

Returns a ChatSession object reconstructed from the JSON file if the file exists and is successfully loaded. Returns None if the file does not exist, if there's an error during file reading/parsing, or if the ChatSession.from_dict() method fails. The ChatSession object contains the complete state of a chat conversation including messages, metadata, and other session-specific data.

Dependencies

  • os
  • json
  • logging

Required Imports

import os
import json
import logging

Usage Example

import os
import json
import logging

# Setup requirements
CHAT_SESSIONS_DIR = './chat_sessions'
os.makedirs(CHAT_SESSIONS_DIR, exist_ok=True)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())

# Define ChatSession class (simplified example)
class ChatSession:
    def __init__(self, session_id, messages=None):
        self.session_id = session_id
        self.messages = messages or []
    
    @classmethod
    def from_dict(cls, data):
        return cls(data['session_id'], data.get('messages', []))
    
    def to_dict(self):
        return {'session_id': self.session_id, 'messages': self.messages}

# Usage
session_id = 'abc123'
loaded_session = load_chat_session_from_file(session_id)

if loaded_session:
    print(f"Session loaded: {loaded_session.session_id}")
    print(f"Messages: {loaded_session.messages}")
else:
    print("Session not found or failed to load")

Best Practices

  • Ensure CHAT_SESSIONS_DIR exists and is writable before calling this function
  • The function returns None on any error, so always check the return value before using it
  • The ChatSession class must implement a from_dict() class method for proper deserialization
  • Session IDs should be sanitized to prevent directory traversal attacks (e.g., using secure_filename or similar validation)
  • Consider implementing file locking if multiple processes/threads might access the same session file simultaneously
  • The function silently catches all exceptions - consider more specific exception handling for production use
  • Ensure proper logging configuration is in place to capture the info and error messages

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_all_chat_sessions 84.9% similar

    Loads all chat session data from JSON files stored in a designated directory and returns them as a dictionary indexed by session ID.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function save_chat_session_to_file 82.9% similar

    Persists a chat session object to a JSON file in the designated chat sessions directory, using the session's ID as the filename.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function load_all_sessions 79.4% similar

    Loads all chat session data from JSON files stored in a sessions directory into memory on application startup.

    From: /tf/active/vicechatdev/docchat/app.py
  • function save_session_to_disk_v1 74.1% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings for storage.

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • function save_session_to_disk 72.6% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings.

    From: /tf/active/vicechatdev/docchat/app.py
← Back to Browse