class ConversationState
A dataclass that represents the complete state of a conversation, including its metadata, exchanges, and lifecycle information.
/tf/active/vicechatdev/e-ink-llm/session_manager.py
30 - 40
simple
Purpose
ConversationState serves as a data container for tracking and managing conversation sessions. It stores all relevant information about a conversation including its unique identifier, user association, timing information, exchange history, current status, and contextual metadata. This class is typically used in conversation management systems, chatbots, or dialogue systems to maintain state across multiple interactions.
Source Code
class ConversationState:
"""Represents the state of a conversation"""
conversation_id: str
user_id: Optional[str]
created_at: str
last_activity: str
total_exchanges: int
status: str # 'active', 'completed', 'archived'
exchanges: List[Exchange]
context_summary: str
metadata: Dict[str, Any]
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
- | - |
Parameter Details
conversation_id: Unique identifier for the conversation, typically a string UUID or similar unique value
user_id: Optional identifier for the user participating in the conversation. Can be None for anonymous conversations
created_at: ISO format timestamp string indicating when the conversation was initiated
last_activity: ISO format timestamp string indicating the most recent activity in the conversation
total_exchanges: Integer count of the total number of exchanges (message pairs) in the conversation
status: String indicating the current state of the conversation. Valid values are 'active', 'completed', or 'archived'
exchanges: List of Exchange objects representing the conversation history, where each Exchange contains a user message and assistant response
context_summary: String containing a summary or description of the conversation context, useful for maintaining conversation continuity
metadata: Dictionary containing arbitrary additional information about the conversation, allowing for flexible extension of conversation properties
Return Value
As a dataclass, instantiation returns a ConversationState object with all specified attributes initialized. The dataclass decorator automatically generates __init__, __repr__, __eq__, and other methods. The object can be converted to a dictionary using asdict() from the dataclasses module.
Class Interface
Methods
__init__(conversation_id: str, user_id: Optional[str], created_at: str, last_activity: str, total_exchanges: int, status: str, exchanges: List[Exchange], context_summary: str, metadata: Dict[str, Any]) -> None
Purpose: Automatically generated constructor by @dataclass decorator that initializes all instance attributes
Parameters:
conversation_id: Unique identifier for the conversationuser_id: Optional user identifiercreated_at: ISO timestamp of conversation creationlast_activity: ISO timestamp of last activitytotal_exchanges: Count of exchangesstatus: Conversation status stringexchanges: List of Exchange objectscontext_summary: Summary of conversation contextmetadata: Additional metadata dictionary
Returns: None (constructor)
__repr__() -> str
Purpose: Automatically generated string representation method by @dataclass decorator
Returns: String representation of the ConversationState object showing all attributes
__eq__(other: object) -> bool
Purpose: Automatically generated equality comparison method by @dataclass decorator
Parameters:
other: Another object to compare with
Returns: True if all attributes are equal, False otherwise
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
conversation_id |
str | Unique identifier for the conversation | instance |
user_id |
Optional[str] | Optional identifier for the user participating in the conversation | instance |
created_at |
str | ISO format timestamp string of when the conversation was created | instance |
last_activity |
str | ISO format timestamp string of the most recent activity | instance |
total_exchanges |
int | Total count of message exchanges in the conversation | instance |
status |
str | Current status of the conversation: 'active', 'completed', or 'archived' | instance |
exchanges |
List[Exchange] | List of Exchange objects representing the conversation history | instance |
context_summary |
str | Summary or description of the conversation context | instance |
metadata |
Dict[str, Any] | Dictionary containing arbitrary additional information about the conversation | instance |
Dependencies
dataclassestyping
Required Imports
from dataclasses import dataclass
from typing import Dict, List, Optional, Any
Usage Example
from dataclasses import dataclass, asdict
from typing import Dict, List, Optional, Any
from datetime import datetime
import uuid
# Assuming Exchange class is defined
@dataclass
class Exchange:
user_message: str
assistant_response: str
timestamp: str
@dataclass
class ConversationState:
conversation_id: str
user_id: Optional[str]
created_at: str
last_activity: str
total_exchanges: int
status: str
exchanges: List[Exchange]
context_summary: str
metadata: Dict[str, Any]
# Create a new conversation state
conversation = ConversationState(
conversation_id=str(uuid.uuid4()),
user_id="user123",
created_at=datetime.now().isoformat(),
last_activity=datetime.now().isoformat(),
total_exchanges=0,
status="active",
exchanges=[],
context_summary="Initial conversation about Python",
metadata={"source": "web", "language": "en"}
)
# Add an exchange
exchange = Exchange(
user_message="Hello",
assistant_response="Hi there!",
timestamp=datetime.now().isoformat()
)
conversation.exchanges.append(exchange)
conversation.total_exchanges += 1
conversation.last_activity = datetime.now().isoformat()
# Convert to dictionary for serialization
conversation_dict = asdict(conversation)
# Update status
conversation.status = "completed"
Best Practices
- Always initialize conversation_id with a unique value (e.g., using uuid.uuid4())
- Use ISO format strings for created_at and last_activity timestamps for consistency and parseability
- Update last_activity timestamp whenever the conversation state changes
- Increment total_exchanges counter when adding new exchanges to the exchanges list
- Ensure status only contains valid values: 'active', 'completed', or 'archived'
- Use the metadata dictionary for extensible properties rather than adding new attributes
- Consider using asdict() from dataclasses module when serializing to JSON or database
- Keep context_summary updated to maintain conversation continuity across sessions
- Handle user_id as Optional to support both authenticated and anonymous conversations
- Validate that exchanges list length matches total_exchanges for data integrity
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class ConversationContext 78.5% similar
-
class Exchange 72.0% similar
-
class ConversationTurn 69.9% similar
-
class ChatSession_v1 68.6% similar
-
class ConversationReference 67.4% similar