🔍 Code Extractor

function clear_session_v1

Maturity: 39

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.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
264 - 271
Complexity:
simple

Purpose

This function is used to reset a chat session by removing all conversation history while maintaining the session structure. It's typically called when a user wants to start a fresh conversation or clear their chat history. The function uses a lock to ensure thread-safe access to the shared chat_sessions dictionary and immediately persists changes to disk to prevent data loss.

Source Code

def clear_session(session_id):
    """Clear a chat session"""
    with session_lock:
        if session_id in chat_sessions:
            chat_sessions[session_id]['messages'] = []
            chat_sessions[session_id]['updated_at'] = datetime.now()
            # Persist to disk while holding lock
            save_session_to_disk(session_id)

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 cleared. This ID must exist in the chat_sessions dictionary for the operation to have any effect. If the session_id doesn't exist, the function silently does nothing.

Return Value

This function returns None (implicit). It performs side effects by modifying the global chat_sessions dictionary and writing to disk via save_session_to_disk().

Dependencies

  • datetime
  • threading

Required Imports

from datetime import datetime
from threading import Lock

Usage Example

from datetime import datetime
from threading import Lock

# Global setup (typically at module level)
chat_sessions = {
    'session_123': {
        'messages': [{'role': 'user', 'content': 'Hello'}],
        'updated_at': datetime.now()
    }
}
session_lock = Lock()

def save_session_to_disk(session_id):
    # Mock implementation
    print(f"Saving session {session_id} to disk")

# Clear the session
clear_session('session_123')

# After clearing, chat_sessions['session_123']['messages'] will be empty
print(chat_sessions['session_123']['messages'])  # Output: []

Best Practices

  • Ensure session_lock is properly initialized as a threading.Lock() before calling this function
  • The function assumes chat_sessions is a global dictionary; ensure it's properly initialized
  • Always check if session_id exists before calling if you need to handle non-existent sessions differently
  • The save_session_to_disk() function must be defined and should handle its own error cases
  • Consider adding error handling around save_session_to_disk() to prevent lock deadlocks if disk operations fail
  • This function holds a lock during disk I/O which could cause performance bottlenecks under high concurrency; consider async persistence if needed
  • The function silently does nothing if session_id doesn't exist; add logging or return values if you need to track this behavior

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function add_message_to_session 75.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 73.8% similar

    Flask route handler that clears the current user's chat session, deletes associated session data from memory and disk, and creates a new empty session.

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • function get_or_create_session 72.5% similar

    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.

    From: /tf/active/vicechatdev/docchat/app.py
  • function api_clear_chat_session 71.1% similar

    Flask API endpoint that clears the chat history for a specific chat session identified by session_id.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function update_session_settings 70.7% similar

    Updates the settings (model, mode, options) for an existing chat session and persists the changes to disk.

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