🔍 Code Extractor

function get_or_create_session

Maturity: 44

Retrieves an existing chat session by ID or creates a new one if it doesn't exist, with thread-safe access and persistent storage support.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
223 - 240
Complexity:
moderate

Purpose

This function manages chat session lifecycle in a web application. It provides thread-safe access to chat sessions stored in memory, attempts to load sessions from disk if not in memory, and creates new sessions with default structure if they don't exist. It's designed for multi-user chat applications where session persistence and concurrent access are important.

Source Code

def get_or_create_session(session_id):
    """Get or create a chat session"""
    with session_lock:
        if session_id not in chat_sessions:
            # Try loading from disk first
            session_data = load_session_from_disk(session_id)
            if session_data:
                chat_sessions[session_id] = session_data
            else:
                # Create new session
                chat_sessions[session_id] = {
                    'messages': [],
                    'created_at': datetime.now(),
                    'updated_at': datetime.now(),
                    'settings': {}  # Store user settings
                }
                save_session_to_disk(session_id)
        return chat_sessions[session_id]

Parameters

Name Type Default Kind
session_id - - positional_or_keyword

Parameter Details

session_id: Unique identifier for the chat session. Expected to be a string (likely UUID or similar). Used as a key to retrieve or create session data from the in-memory dictionary and disk storage.

Return Value

Returns a dictionary representing the chat session with the following structure: {'messages': list of chat messages, 'created_at': datetime object of session creation, 'updated_at': datetime object of last update, 'settings': dictionary for user-specific settings}. The returned dictionary is a reference to the session stored in the global chat_sessions dictionary.

Dependencies

  • datetime
  • threading

Required Imports

from datetime import datetime
from threading import Lock

Usage Example

from datetime import datetime
from threading import Lock

# Required global setup
session_lock = Lock()
chat_sessions = {}

def load_session_from_disk(session_id):
    # Implementation to load from disk
    return None

def save_session_to_disk(session_id):
    # Implementation to save to disk
    pass

# Usage
session_id = 'user-123-session'
session_data = get_or_create_session(session_id)

# Access session data
print(session_data['messages'])
print(session_data['created_at'])

# Add a message to the session
session_data['messages'].append({'role': 'user', 'content': 'Hello'})
session_data['updated_at'] = datetime.now()

Best Practices

  • Always use this function to access chat sessions rather than directly accessing the chat_sessions dictionary to ensure thread safety
  • The function uses a lock to prevent race conditions in multi-threaded environments, so avoid holding references to the lock elsewhere
  • Ensure load_session_from_disk and save_session_to_disk are properly implemented before using this function
  • The returned dictionary is mutable and shared across all callers, so modifications will affect the global state
  • Consider implementing session expiration logic to prevent unbounded memory growth
  • The function creates sessions with empty settings; populate these as needed for your application
  • Remember to call save_session_to_disk after modifying session data to persist changes

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_chat_session 78.7% similar

    Creates a new chat session for a specific document section by generating a unique session ID, initializing a ChatSession object, storing it in application state with thread-safe locking, and persisting it to file.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function get_chat_session 77.5% similar

    Retrieves a chat session by its unique session ID, first checking an in-memory cache, then falling back to loading from persistent file storage if not found in memory.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function add_message_to_session 73.7% similar

    Adds a message to a chat session with thread-safe locking, storing role, content, timestamp, and optional metadata/references, then persists the session to disk.

    From: /tf/active/vicechatdev/docchat/app.py
  • function clear_session_v1 72.5% similar

    Clears all messages from a chat session identified by session_id, resets the session's updated timestamp, and persists the changes to disk in a thread-safe manner.

    From: /tf/active/vicechatdev/docchat/app.py
  • function save_chat_session_to_file 67.7% 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
← Back to Browse