🔍 Code Extractor

class ChatSession

Maturity: 50

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

File:
/tf/active/vicechatdev/vice_ai/complex_app.py
Lines:
345 - 396
Complexity:
moderate

Purpose

ChatSession represents an interactive chat conversation tied to a document section. It maintains the conversation history, manages message flow between user and assistant, tracks references generated during the chat, and persists session state to file storage. This class is designed for document-based conversational AI applications where context and references need to be maintained across multiple interactions.

Source Code

class ChatSession:
    """Represents a chat session for a document section"""
    
    def __init__(self, session_id, section_id, document_id):
        self.id = session_id
        self.section_id = section_id
        self.document_id = document_id
        self.messages = []  # List of {'role': 'user'/'assistant', 'content': '...', 'timestamp': '...'}
        self.context_documents = []  # Documents provided as context
        self.references = []  # References generated during chat
        self.created_at = datetime.now()
        self.updated_at = datetime.now()
    
    def add_message(self, role, content, references=None):
        """Add a message to the chat session"""
        message = {
            'role': role,
            'content': content,
            'timestamp': datetime.now().isoformat(),
            'references': references or []
        }
        self.messages.append(message)
        self.updated_at = datetime.now()
        
        # Add references to session references
        if references:
            self.references.extend(references)
        
        # Save session to file after adding message
        save_chat_session_to_file(self)
    
    def to_dict(self):
        return {
            'id': self.id,
            'section_id': self.section_id,
            'document_id': self.document_id,
            'messages': self.messages,
            'context_documents': self.context_documents,
            'references': self.references,
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }
    
    @classmethod
    def from_dict(cls, data):
        session = cls(data['id'], data['section_id'], data['document_id'])
        session.messages = data.get('messages', [])
        session.context_documents = data.get('context_documents', [])
        session.references = data.get('references', [])
        session.created_at = datetime.fromisoformat(data.get('created_at', datetime.now().isoformat()))
        session.updated_at = datetime.fromisoformat(data.get('updated_at', datetime.now().isoformat()))
        return session

Parameters

Name Type Default Kind
bases - -

Parameter Details

session_id: Unique identifier for the chat session. Used to distinguish between different chat sessions and for persistence/retrieval operations.

section_id: Identifier of the document section this chat session is associated with. Links the conversation to a specific part of a document.

document_id: Identifier of the parent document containing the section. Provides document-level context for the chat session.

Return Value

Instantiation returns a ChatSession object with initialized attributes. The add_message method returns None but has side effects (updates messages list, saves to file). The to_dict method returns a dictionary representation of the session with all attributes serialized. The from_dict class method returns a new ChatSession instance reconstructed from dictionary data.

Class Interface

Methods

__init__(self, session_id, section_id, document_id)

Purpose: Initialize a new chat session with identifiers and empty message/reference lists

Parameters:

  • session_id: Unique identifier for this chat session
  • section_id: Identifier of the document section associated with this chat
  • document_id: Identifier of the parent document

Returns: None (constructor)

add_message(self, role, content, references=None)

Purpose: Add a new message to the chat session, update timestamps, accumulate references, and persist to file

Parameters:

  • role: The role of the message sender, typically 'user' or 'assistant'
  • content: The text content of the message
  • references: Optional list of reference objects/dictionaries associated with this message

Returns: None (side effects: appends to messages list, updates updated_at, extends references list, saves to file)

to_dict(self) -> dict

Purpose: Serialize the chat session to a dictionary format suitable for JSON storage or transmission

Returns: Dictionary containing all session attributes with datetime objects converted to ISO format strings

from_dict(cls, data) -> ChatSession

Purpose: Class method to reconstruct a ChatSession instance from a dictionary representation

Parameters:

  • data: Dictionary containing serialized session data with keys: id, section_id, document_id, messages, context_documents, references, created_at, updated_at

Returns: New ChatSession instance with all attributes restored from the dictionary data

Attributes

Name Type Description Scope
id str Unique identifier for this chat session instance
section_id str Identifier of the document section this chat is associated with instance
document_id str Identifier of the parent document instance
messages list[dict] List of message dictionaries, each containing 'role', 'content', 'timestamp', and 'references' keys instance
context_documents list List of documents provided as context for the chat session instance
references list Accumulated list of all references generated during the chat session instance
created_at datetime Timestamp when the chat session was created instance
updated_at datetime Timestamp of the last update to the chat session (updated on each message addition) instance

Dependencies

  • datetime

Required Imports

from datetime import datetime

Usage Example

# Create a new chat session
session = ChatSession(
    session_id='sess_123',
    section_id='sec_456',
    document_id='doc_789'
)

# Add a user message
session.add_message(
    role='user',
    content='What is the main topic of this section?'
)

# Add an assistant response with references
session.add_message(
    role='assistant',
    content='The main topic is machine learning.',
    references=[{'source': 'page 5', 'text': 'ML definition'}]
)

# Convert to dictionary for storage/transmission
session_dict = session.to_dict()

# Reconstruct from dictionary
restored_session = ChatSession.from_dict(session_dict)

# Access messages
for msg in restored_session.messages:
    print(f"{msg['role']}: {msg['content']}")

Best Practices

  • Always provide unique session_id, section_id, and document_id when instantiating to avoid conflicts
  • Use add_message method rather than directly modifying the messages list to ensure proper timestamp tracking and persistence
  • The add_message method automatically saves the session to file, so be aware of I/O operations on each message addition
  • When passing references to add_message, ensure they are in list format even for single references
  • Use to_dict for serialization before storing in databases or sending over network
  • Use from_dict class method for deserialization to properly reconstruct datetime objects
  • The session automatically tracks updated_at timestamp on each message addition
  • References are accumulated across all messages in the session.references list
  • Ensure the save_chat_session_to_file function is properly implemented before using this class
  • Messages are stored in chronological order; avoid manually reordering the messages list

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class ChatSession_v1 89.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 ChatSessionService 85.4% similar

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

    From: /tf/active/vicechatdev/vice_ai/services.py
  • function create_chat_session 74.1% 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
  • class DataAnalysisSession 72.0% similar

    A dataclass representing a data analysis session that is linked to a specific text section within a document, managing conversation messages, analysis results, plots, and configuration.

    From: /tf/active/vicechatdev/vice_ai/models.py
  • function api_create_chat_session 68.4% 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