🔍 Code Extractor

class ChatSessionService

Maturity: 46

Service class for managing chat sessions, including creation, retrieval, message management, and configuration updates for document section-based conversations.

File:
/tf/active/vicechatdev/vice_ai/services.py
Lines:
875 - 951
Complexity:
moderate

Purpose

ChatSessionService provides a high-level interface for managing chat sessions associated with document sections. It handles the complete lifecycle of chat sessions including creation with optional configuration, message history management, session retrieval by ID or section, configuration updates, and history clearing. The service acts as an intermediary between application logic and the database layer, encapsulating all chat session-related operations.

Source Code

class ChatSessionService:
    """Service for managing Chat Sessions"""
    
    def __init__(self, db_manager: DatabaseManager):
        self.db = db_manager
    
    def create_chat_session(
        self, 
        section_id: str, 
        document_id: str,
        config: ChatConfiguration = None
    ) -> ChatSession:
        """Create a new chat session for a section"""
        session_id = str(uuid.uuid4())
        
        if config is None:
            config = ChatConfiguration()
        
        chat_session = ChatSession(
            id=session_id,
            section_id=section_id,
            document_id=document_id,
            config=config
        )
        
        # Save the chat session
        success = self.db.save_chat_session(chat_session)
        
        return chat_session
    
    def get_chat_session(self, session_id: str) -> Optional[ChatSession]:
        """Get a chat session by ID"""
        return self.db.get_chat_session(session_id)
    
    def get_chat_session_by_section(self, section_id: str) -> Optional[ChatSession]:
        """Get a chat session by section ID"""
        return self.db.get_chat_session_by_section(section_id)
    
    def add_message_to_session(
        self,
        session_id: str,
        role: str,
        content: str,
        references: List[Dict] = None
    ) -> bool:
        """Add a message to a chat session"""
        chat_session = self.get_chat_session(session_id)
        if not chat_session:
            return False
        
        chat_session.add_message(role, content, references)
        return self.db.save_chat_session(chat_session)
    
    def update_chat_config(
        self,
        session_id: str,
        config: ChatConfiguration
    ) -> bool:
        """Update chat session configuration"""
        chat_session = self.get_chat_session(session_id)
        if not chat_session:
            return False
        
        chat_session.config = config
        chat_session.updated_at = datetime.now()
        return self.db.save_chat_session(chat_session)
    
    def clear_chat_history(self, session_id: str) -> bool:
        """Clear chat history but keep configuration"""
        chat_session = self.get_chat_session(session_id)
        if not chat_session:
            return False
        
        chat_session.messages = []
        chat_session.references = []
        chat_session.updated_at = datetime.now()
        return self.db.save_chat_session(chat_session)

Parameters

Name Type Default Kind
bases - -

Parameter Details

db_manager: An instance of DatabaseManager that provides database operations for persisting and retrieving chat sessions. This is the only required dependency for instantiating the service and must implement methods like save_chat_session, get_chat_session, and get_chat_session_by_section.

Return Value

Instantiation returns a ChatSessionService object. Methods return various types: create_chat_session returns a ChatSession object with generated UUID; get methods return Optional[ChatSession] (None if not found); modification methods (add_message_to_session, update_chat_config, clear_chat_history) return bool indicating success/failure.

Class Interface

Methods

__init__(self, db_manager: DatabaseManager)

Purpose: Initialize the ChatSessionService with a database manager

Parameters:

  • db_manager: DatabaseManager instance for database operations

Returns: None (constructor)

create_chat_session(self, section_id: str, document_id: str, config: ChatConfiguration = None) -> ChatSession

Purpose: Create a new chat session for a document section with optional configuration

Parameters:

  • section_id: Unique identifier of the document section this chat session is associated with
  • document_id: Unique identifier of the parent document
  • config: Optional ChatConfiguration object; if None, uses default configuration

Returns: ChatSession object with generated UUID, associated section/document IDs, and configuration

get_chat_session(self, session_id: str) -> Optional[ChatSession]

Purpose: Retrieve a chat session by its unique session ID

Parameters:

  • session_id: Unique identifier of the chat session to retrieve

Returns: ChatSession object if found, None if session does not exist

get_chat_session_by_section(self, section_id: str) -> Optional[ChatSession]

Purpose: Retrieve a chat session associated with a specific document section

Parameters:

  • section_id: Unique identifier of the document section

Returns: ChatSession object if found, None if no session exists for the section

add_message_to_session(self, session_id: str, role: str, content: str, references: List[Dict] = None) -> bool

Purpose: Add a new message to an existing chat session's message history

Parameters:

  • session_id: Unique identifier of the chat session
  • role: Role of the message sender (e.g., 'user', 'assistant', 'system')
  • content: Text content of the message
  • references: Optional list of reference dictionaries containing source information (e.g., page numbers, line numbers)

Returns: True if message was successfully added and saved, False if session not found or save failed

update_chat_config(self, session_id: str, config: ChatConfiguration) -> bool

Purpose: Update the configuration settings of an existing chat session

Parameters:

  • session_id: Unique identifier of the chat session
  • config: New ChatConfiguration object to replace the existing configuration

Returns: True if configuration was successfully updated and saved, False if session not found or save failed

clear_chat_history(self, session_id: str) -> bool

Purpose: Clear all messages and references from a chat session while preserving its configuration

Parameters:

  • session_id: Unique identifier of the chat session to clear

Returns: True if history was successfully cleared and saved, False if session not found or save failed

Attributes

Name Type Description Scope
db DatabaseManager Database manager instance used for all persistence operations including saving and retrieving chat sessions instance

Dependencies

  • uuid
  • typing
  • datetime

Required Imports

import uuid
from typing import List, Dict, Optional
from datetime import datetime
from models import ChatSession, ChatConfiguration, DatabaseManager

Usage Example

from models import DatabaseManager, ChatConfiguration
from chat_session_service import ChatSessionService

# Initialize the service
db_manager = DatabaseManager(connection_string='your_db_connection')
chat_service = ChatSessionService(db_manager)

# Create a new chat session
config = ChatConfiguration(model='gpt-4', temperature=0.7)
session = chat_service.create_chat_session(
    section_id='section_123',
    document_id='doc_456',
    config=config
)

# Add messages to the session
chat_service.add_message_to_session(
    session_id=session.id,
    role='user',
    content='What is this section about?'
)

chat_service.add_message_to_session(
    session_id=session.id,
    role='assistant',
    content='This section discusses...',
    references=[{'page': 1, 'line': 5}]
)

# Retrieve the session
retrieved_session = chat_service.get_chat_session(session.id)

# Update configuration
new_config = ChatConfiguration(model='gpt-4', temperature=0.5)
chat_service.update_chat_config(session.id, new_config)

# Clear history while keeping config
chat_service.clear_chat_history(session.id)

Best Practices

  • Always check return values from modification methods (add_message_to_session, update_chat_config, clear_chat_history) as they return False if the session doesn't exist
  • Create a single ChatSessionService instance per database connection and reuse it throughout the application lifecycle
  • Provide a ChatConfiguration during session creation to avoid using default configuration
  • Use get_chat_session_by_section when you need to retrieve a session associated with a specific document section
  • The service automatically updates the updated_at timestamp when modifying sessions
  • Session IDs are automatically generated as UUIDs; do not attempt to provide custom IDs
  • The service does not handle database connection management; ensure DatabaseManager is properly initialized before instantiation
  • Clear chat history preserves the session configuration, making it suitable for resetting conversations without losing settings

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class ChatSession 85.4% similar

    A class that manages a chat session associated with a specific document section, tracking messages, context documents, references, and timestamps.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • class ChatSession_v1 78.1% similar

    A dataclass representing a chat session associated with a specific text section in a document, managing conversation messages, context, and references.

    From: /tf/active/vicechatdev/vice_ai/models.py
  • class TextSectionService 72.8% similar

    Service class for managing TextSection entities, providing CRUD operations, versioning, chat functionality, and search capabilities.

    From: /tf/active/vicechatdev/vice_ai/services.py
  • function create_chat_session 68.9% 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 api_create_chat_session 66.6% similar

    Flask API endpoint that creates or retrieves a chat session associated with a specific document section, ensuring proper validation and linking between documents, sections, and chat sessions.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
← Back to Browse