🔍 Code Extractor

function load_all_chat_sessions

Maturity: 44

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
99 - 113
Complexity:
simple

Purpose

This function is responsible for initializing or restoring the application's chat session state by reading all persisted chat session files from disk. It's typically used during application startup or when refreshing the in-memory chat session cache. The function ensures the necessary directories exist, iterates through all JSON files in the chat sessions directory, loads each session using a helper function, and aggregates them into a dictionary for easy access by session ID.

Source Code

def load_all_chat_sessions():
    """Load all chat sessions from files"""
    chat_sessions = {}
    try:
        ensure_directories()
        for filename in os.listdir(CHAT_SESSIONS_DIR):
            if filename.endswith('.json'):
                session_id = filename[:-5]  # Remove .json extension
                chat_session = load_chat_session_from_file(session_id)
                if chat_session:
                    chat_sessions[session_id] = chat_session
        logger.info(f"📂 Loaded {len(chat_sessions)} chat sessions from files")
    except Exception as e:
        logger.error(f"❌ Failed to load chat sessions: {e}")
    return chat_sessions

Return Value

Returns a dictionary where keys are session IDs (strings extracted from filenames without the .json extension) and values are chat session objects loaded from their respective JSON files. Returns an empty dictionary if no sessions are found or if an error occurs during loading. The structure of each chat session object depends on the implementation of load_chat_session_from_file().

Dependencies

  • os
  • json
  • logging

Required Imports

import os
import json
import logging

Usage Example

# Assuming required module-level variables and functions are defined:
# CHAT_SESSIONS_DIR = './data/chat_sessions'
# logger = logging.getLogger(__name__)
# def ensure_directories(): ...
# def load_chat_session_from_file(session_id): ...

import os
import json
import logging

# Load all chat sessions at application startup
chat_sessions = load_all_chat_sessions()

# Access a specific session
if 'session_123' in chat_sessions:
    session_data = chat_sessions['session_123']
    print(f"Loaded session with {len(session_data.get('messages', []))} messages")

# Check how many sessions were loaded
print(f"Total sessions loaded: {len(chat_sessions)}")

Best Practices

  • This function depends on module-level variables (CHAT_SESSIONS_DIR, logger) and helper functions (ensure_directories, load_chat_session_from_file) that must be properly defined before calling
  • The function silently catches all exceptions and returns an empty dictionary on failure, so check logs for error details
  • Session IDs are derived from filenames by removing the .json extension, so ensure filenames follow this convention
  • The function only processes files ending with .json extension, other files in the directory are ignored
  • Consider calling this function during application initialization to populate the in-memory session cache
  • For large numbers of sessions, this function may have performance implications as it loads all sessions synchronously
  • The function uses load_chat_session_from_file() which may return None for invalid sessions, these are automatically filtered out

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_all_sessions 91.7% 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 load_chat_session_from_file 84.9% similar

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

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function save_chat_session_to_file 73.1% 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 save_session_to_disk_v1 71.4% 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 on_load 69.0% similar

    Blueprint initialization hook that loads persisted chat sessions from disk when the DocChat blueprint is registered with the Flask application.

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