🔍 Code Extractor

class ChatSession_v1

Maturity: 48

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

File:
/tf/active/vicechatdev/vice_ai/models.py
Lines:
168 - 238
Complexity:
moderate

Purpose

ChatSession manages the state and lifecycle of a chat conversation tied to a document section. It stores messages exchanged between users and AI, maintains context documents for reference, tracks citations/references, and handles configuration settings. The class provides methods for adding messages, serializing to/from dictionaries for persistence, and automatically manages timestamps. It's designed for applications that need to maintain conversational context within document-based workflows.

Source Code

class ChatSession:
    """Chat session associated with a text section"""
    id: str
    section_id: str
    document_id: str
    messages: List[Dict] = None  # Store as dicts for JSON serialization
    context_documents: List[str] = None
    references: List[Dict] = None
    config: ChatConfiguration = None
    created_at: datetime = None
    updated_at: datetime = None
    
    def __post_init__(self):
        if self.messages is None:
            self.messages = []
        if self.context_documents is None:
            self.context_documents = []
        if self.references is None:
            self.references = []
        if self.config is None:
            self.config = ChatConfiguration()
        if self.created_at is None:
            self.created_at = datetime.now()
        if self.updated_at is None:
            self.updated_at = datetime.now()
    
    def add_message(self, role: str, content: str, references: List[Dict] = None):
        """Add a message to the chat session"""
        message = {
            'id': str(uuid.uuid4()),
            '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)
    
    def to_dict(self) -> Dict:
        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,
            'config': self.config.to_dict() if self.config else {},
            'created_at': self.created_at.isoformat(),
            'updated_at': self.updated_at.isoformat()
        }
    
    @classmethod
    def from_dict(cls, data: Dict) -> 'ChatSession':
        config_data = data.get('config', {})
        config = ChatConfiguration.from_dict(config_data) if config_data else ChatConfiguration()
        
        return cls(
            id=data['id'],
            section_id=data['section_id'],
            document_id=data['document_id'],
            messages=data.get('messages', []),
            context_documents=data.get('context_documents', []),
            references=data.get('references', []),
            config=config,
            created_at=datetime.fromisoformat(data.get('created_at', datetime.now().isoformat())),
            updated_at=datetime.fromisoformat(data.get('updated_at', datetime.now().isoformat()))
        )

Parameters

Name Type Default Kind
bases - -

Parameter Details

id: Unique identifier for the chat session (string). Should be unique across all sessions.

section_id: Identifier of the text section this chat session is associated with (string). Links the conversation to a specific document section.

document_id: Identifier of the parent document containing the section (string). Provides document-level context.

messages: List of message dictionaries containing conversation history. Each message has id, role, content, timestamp, and references. Defaults to empty list if None.

context_documents: List of document identifiers or paths that provide context for the chat. Defaults to empty list if None.

references: List of reference dictionaries containing citations or sources mentioned in the conversation. Defaults to empty list if None.

config: ChatConfiguration object containing chat-specific settings. Defaults to new ChatConfiguration() if None.

created_at: Datetime when the session was created. Auto-set to current time if None.

updated_at: Datetime when the session was last modified. Auto-set to current time if None and updated on message additions.

Return Value

Instantiation returns a ChatSession object with all attributes initialized. The to_dict() method returns a dictionary representation suitable for JSON serialization. The from_dict() class method returns a new ChatSession instance reconstructed from a dictionary.

Class Interface

Methods

__post_init__(self) -> None

Purpose: Initializes default values for optional attributes after dataclass initialization. Called automatically after __init__.

Returns: None. Modifies instance attributes in place.

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

Purpose: Adds a new message to the chat session with automatic ID generation, timestamp, and reference tracking. Updates the session's updated_at timestamp.

Parameters:

  • role: The role of the message sender (e.g., 'user', 'assistant', 'system')
  • content: The text content of the message
  • references: Optional list of reference dictionaries to attach to this message. Also added to session-level references.

Returns: None. Modifies self.messages and self.references lists in place and updates self.updated_at.

to_dict(self) -> Dict

Purpose: Serializes the ChatSession instance to a dictionary suitable for JSON serialization or database storage.

Returns: Dictionary containing all session attributes with datetime objects converted to ISO format strings and config converted to dict.

from_dict(cls, data: Dict) -> 'ChatSession'

Purpose: Class method that reconstructs a ChatSession instance from a dictionary representation, handling datetime parsing and config reconstruction.

Parameters:

  • data: Dictionary containing serialized ChatSession data, typically from to_dict() output or database

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 text section this session is associated with instance
document_id str Identifier of the parent document instance
messages List[Dict] List of message dictionaries, each containing id, role, content, timestamp, and references. Initialized to empty list if None. instance
context_documents List[str] List of document identifiers or paths providing context for the chat. Initialized to empty list if None. instance
references List[Dict] Accumulated list of all references from all messages in the session. Initialized to empty list if None. instance
config ChatConfiguration Configuration object for chat-specific settings. Initialized to new ChatConfiguration() if None. instance
created_at datetime Timestamp when the session was created. Auto-set to current time if None. instance
updated_at datetime Timestamp when the session was last updated. Auto-set to current time if None and updated when messages are added. instance

Dependencies

  • uuid
  • datetime
  • typing
  • dataclasses

Required Imports

import uuid
from datetime import datetime
from typing import List, Dict
from dataclasses import dataclass

Usage Example

from datetime import datetime
from typing import List, Dict
from dataclasses import dataclass
import uuid

# Assuming ChatConfiguration is defined
session = ChatSession(
    id=str(uuid.uuid4()),
    section_id='section_123',
    document_id='doc_456'
)

# Add a user message
session.add_message(
    role='user',
    content='What is this section about?',
    references=[{'source': 'page 5', 'text': 'relevant excerpt'}]
)

# Add an assistant response
session.add_message(
    role='assistant',
    content='This section discusses...',
    references=[{'source': 'page 6', 'text': 'supporting evidence'}]
)

# Serialize to dictionary for storage
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 use unique IDs for session_id, section_id, and document_id to avoid conflicts
  • Call add_message() rather than directly modifying the messages list to ensure proper timestamp updates and reference tracking
  • Use to_dict() for serialization before storing in databases or JSON files
  • Use from_dict() class method for deserialization to ensure proper object reconstruction
  • The __post_init__ method automatically initializes None values, so you can create minimal instances with just required IDs
  • References are accumulated across all messages - check self.references for a complete list of all citations
  • The updated_at timestamp is automatically updated when messages are added, useful for tracking session activity
  • Ensure ChatConfiguration class is properly defined before using ChatSession
  • Message dictionaries include auto-generated UUIDs and ISO format timestamps for consistency

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class ChatSession 89.1% 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 ChatSessionService 78.1% 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
  • class DataAnalysisSession 77.6% 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
  • class DataAnalysisSession_v1 74.6% similar

    A dataclass representing a statistical analysis session that is linked to specific document sections, managing analysis state, messages, plots, and configuration.

    From: /tf/active/vicechatdev/vice_ai/models.py
  • class TextSection 73.7% similar

    A dataclass representing a text section entity with versioning, chat interface, data analysis capabilities, and metadata management.

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