class ChatMessage
A dataclass representing an individual chat message in a conversation, with support for serialization to and from dictionaries.
/tf/active/vicechatdev/vice_ai/models.py
140 - 165
simple
Purpose
ChatMessage encapsulates all data related to a single message in a chat conversation, including the message content, sender role (user or assistant), timestamp, and optional references. It provides methods for converting between object and dictionary representations, making it suitable for storage, transmission, and API interactions. This class is typically used as part of a larger chat management system to maintain conversation history.
Source Code
class ChatMessage:
"""Individual chat message in a conversation"""
id: str
role: str # 'user' or 'assistant'
content: str
timestamp: datetime
references: List[Dict] = None
def to_dict(self) -> Dict:
return {
'id': self.id,
'role': self.role,
'content': self.content,
'timestamp': self.timestamp.isoformat(),
'references': self.references or []
}
@classmethod
def from_dict(cls, data: Dict) -> 'ChatMessage':
return cls(
id=data['id'],
role=data['role'],
content=data['content'],
timestamp=datetime.fromisoformat(data['timestamp']),
references=data.get('references', [])
)
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
id: Unique identifier for the chat message, typically a string UUID or similar unique value
role: The role of the message sender, expected to be either 'user' (for human messages) or 'assistant' (for AI responses)
content: The actual text content of the message
timestamp: A datetime object representing when the message was created or sent
references: Optional list of dictionaries containing reference information (e.g., sources, citations, or related documents). Defaults to None if not provided
Return Value
Instantiation returns a ChatMessage object with all specified attributes. The to_dict() method returns a dictionary representation with 'id', 'role', 'content', 'timestamp' (as ISO format string), and 'references' keys. The from_dict() class method returns a new ChatMessage instance constructed from a dictionary.
Class Interface
Methods
to_dict(self) -> Dict
Purpose: Converts the ChatMessage instance to a dictionary representation suitable for JSON serialization, storage, or transmission
Returns: A dictionary containing 'id', 'role', 'content', 'timestamp' (as ISO format string), and 'references' (empty list if None) keys
from_dict(cls, data: Dict) -> ChatMessage
Purpose: Class method that constructs a new ChatMessage instance from a dictionary representation, typically used for deserialization
Parameters:
data: Dictionary containing 'id', 'role', 'content', 'timestamp' (ISO format string), and optionally 'references' keys
Returns: A new ChatMessage instance with attributes populated from the provided dictionary
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
id |
str | Unique identifier for the chat message | instance |
role |
str | Role of the message sender, typically 'user' or 'assistant' | instance |
content |
str | The actual text content of the message | instance |
timestamp |
datetime | Datetime object representing when the message was created | instance |
references |
List[Dict] | Optional list of reference dictionaries containing source information, citations, or related documents. Defaults to None | instance |
Dependencies
datetimetypingdataclasses
Required Imports
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
@dataclass
class ChatMessage:
id: str
role: str
content: str
timestamp: datetime
references: List[Dict] = None
def to_dict(self) -> Dict:
return {
'id': self.id,
'role': self.role,
'content': self.content,
'timestamp': self.timestamp.isoformat(),
'references': self.references or []
}
@classmethod
def from_dict(cls, data: Dict) -> 'ChatMessage':
return cls(
id=data['id'],
role=data['role'],
content=data['content'],
timestamp=datetime.fromisoformat(data['timestamp']),
references=data.get('references', [])
)
# Create a new message
msg = ChatMessage(
id=str(uuid.uuid4()),
role='user',
content='Hello, how are you?',
timestamp=datetime.now(),
references=[{'source': 'doc1.pdf', 'page': 5}]
)
# Convert to dictionary for storage/transmission
msg_dict = msg.to_dict()
print(msg_dict)
# Reconstruct from dictionary
reconstructed_msg = ChatMessage.from_dict(msg_dict)
print(reconstructed_msg.content)
Best Practices
- Always provide a unique ID when creating a ChatMessage instance, typically using uuid.uuid4()
- Use 'user' or 'assistant' as the role value to maintain consistency with common chat APIs
- Set timestamp to datetime.now() when creating new messages to accurately track message creation time
- The references attribute is optional and defaults to None; it will be converted to an empty list in to_dict()
- Use to_dict() before storing messages in databases or sending via APIs that require JSON serialization
- Use from_dict() class method to reconstruct ChatMessage objects from stored or received data
- The timestamp is serialized to ISO format string in to_dict() and must be in ISO format when using from_dict()
- This is an immutable-by-convention dataclass; avoid modifying attributes after creation for thread safety
- When working with references, ensure each reference is a dictionary with consistent keys across your application
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class ChatSession_v1 68.9% similar
-
class LLMMessage 67.3% similar
-
class ChatSession 57.4% similar
-
function add_message_to_session 56.4% similar
-
class SimpleChatMemory 53.9% similar