Message
Represents a single message in a conversational AI interaction, discovered through Conversation objects.
USAGE
Message(
content,
role,=datetime.now(),
timestamp=dict(),
metadata=(lambda: str(uuid4()))(),
message_id )
The Message
class is a fundamental data structure in Talk Box that users typically encounter when exploring Conversation
objects returned by ChatBot
methods. This creates a natural discovery path: ChatBot
→ Conversation
→ Message
, where each layer provides progressively more detailed control over conversational AI interactions.
Discovery through the layered API:
- Start with
ChatBot.chat()
→ returnsConversation
- Explore
Conversation.get_messages()
→ returns list ofMessage
- Access individual
Message
properties for detailed message inspection
Each message encapsulates all information about individual exchanges in conversations, including text content, role information, timestamp data, and extensible metadata for storing additional context or processing information. Messages are immutable by design and include automatic timestamp generation and unique identification.
The class supports serialization to and from dictionary format for storage, transmission, and integration with external systems. The role-based system follows standard conversational AI patterns where different participants in the conversation are clearly identified.
Parameters
content : str
-
The actual text content of the message. This is the primary payload containing what was said or communicated in this message exchange.
role : str
-
The role of the message sender, indicating who or what generated this message. Standard roles include: -
"user"
: Messages from the human user -"assistant"
: Messages from the AI chatbot or assistant -"system"
: System-level messages, instructions, or metadata -"function"
: Messages from function calls or tool executions Custom roles can be used for specialized conversation flows. timestamp : datetime = datetime.now()
-
When the message was created. If not provided, automatically set to the current time using
datetime.now()
. This enables chronological ordering and time-based analysis of conversations. metadata : dict[str, Any] = dict()
-
Additional metadata about the message as a dictionary. This extensible field can store any additional context, processing information, or custom data. Examples include token counts, confidence scores, source information, or custom application data. Defaults to an empty dictionary if not provided.
message_id : str = (lambda: str(uuid4()))()
-
Unique identifier for the message. If not provided, automatically generated using
uuid4()
to ensure global uniqueness. This enables reliable message referencing and tracking across systems.
Returns
Message
-
A new Message instance with the specified content and metadata.
Examples
Creating basic messages
Create messages for different conversation participants:
from talk_box import Message
from datetime import datetime
# User message - most common type
= Message(
user_msg ="What are the key principles of machine learning?",
content="user"
role
)
# Assistant response
= Message(
assistant_msg ="Machine learning has three key principles: representation, evaluation, and optimization...",
content="assistant"
role
)
# System instruction
= Message(
system_msg ="You are a helpful AI assistant specializing in technical topics.",
content="system"
role
)
print(f"User asked: {user_msg.content}")
print(f"Message ID: {user_msg.message_id}")
print(f"Created at: {user_msg.timestamp}")
Working with metadata
Use metadata to store additional context and processing information:
# Message with rich metadata
= Message(
detailed_msg ="Here's the code implementation you requested...",
content="assistant",
role={
metadata"model": "gpt-4-turbo",
"tokens_used": 245,
"confidence": 0.92,
"sources": ["python_docs", "stackoverflow"],
"code_blocks": 2,
"execution_time": 1.3
}
)
# Access metadata
print(f"Model used: {detailed_msg.metadata['model']}")
print(f"Confidence: {detailed_msg.metadata['confidence']}")
print(f"Sources: {', '.join(detailed_msg.metadata['sources'])}")
Message serialization and persistence
Convert messages to/from dictionaries for storage and transmission:
# Create a message
= Message(
original_msg ="Serialize this message for storage",
content="user",
role={"importance": "high", "category": "technical"}
metadata
)
# Convert to dictionary (for JSON storage, API calls, etc.)
= original_msg.to_dict()
msg_dict print("Serialized message:", msg_dict)
# Reconstruct from dictionary
= Message.from_dict(msg_dict)
restored_msg print(f"Restored content: {restored_msg.content}")
print(f"Same message ID: {restored_msg.message_id == original_msg.message_id}")
Function call messages
Create messages for function calls and tool usage:
# Function call request
= Message(
function_call ="calculate_statistics",
content="function",
role={
metadata"function_name": "calculate_statistics",
"arguments": {"data": [1, 2, 3, 4, 5], "method": "mean"},
"call_id": "func_001"
}
)
# Function result
= Message(
function_result ="Statistics calculated: mean=3.0, std=1.58",
content="function",
role={
metadata"function_name": "calculate_statistics",
"result": {"mean": 3.0, "std": 1.58},
"call_id": "func_001",
"success": True
}
)
print(f"Function: {function_call.metadata['function_name']}")
print(f"Result: {function_result.content}")
Custom roles and specialized workflows
Use custom roles for specialized conversation types:
# Code review workflow
= Message(
code_submission ="def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)",
content="developer"
role
)
= Message(
code_review ="Consider using memoization to improve performance for large n values.",
content="reviewer",
role={
metadata"review_type": "performance",
"severity": "suggestion",
"line_numbers": [1]
}
)
# Documentation workflow
= Message(
doc_request ="Please document the fibonacci function",
content="doc_manager"
role
)
= Message(
documentation ="Calculates the nth Fibonacci number using recursive approach...",
content="technical_writer",
role={
metadata"doc_type": "function_docstring",
"coverage": "complete"
} )
Message validation and filtering
Messages can be validated and filtered based on their attributes:
= [user_msg, assistant_msg, system_msg, detailed_msg]
messages
# Filter by role
= [msg for msg in messages if msg.role == "user"]
user_messages = [msg for msg in messages if msg.role == "assistant"]
assistant_messages
# Filter by metadata presence
= [msg for msg in messages if msg.metadata]
messages_with_metadata
# Filter by timestamp (messages from last hour)
from datetime import timedelta
= datetime.now() - timedelta(hours=1)
recent_cutoff = [msg for msg in messages if msg.timestamp > recent_cutoff]
recent_messages
print(f"User messages: {len(user_messages)}")
print(f"Messages with metadata: {len(messages_with_metadata)}")
print(f"Recent messages: {len(recent_messages)}")
Integration with conversation systems
Messages are designed to integrate seamlessly with conversation management:
from talk_box import Conversation
# Create conversation and add messages
= Conversation()
conversation
# Add messages directly
"Hello, I need help with Python", "user")
conversation.add_message("I'd be happy to help! What specific topic?", "assistant")
conversation.add_message(
# Or add pre-created Message objects
= Message(
detailed_question ="How do I implement a binary search algorithm?",
content="user",
role={"topic": "algorithms", "difficulty": "intermediate"}
metadata
)
conversation.messages.append(detailed_question)
print(f"Conversation has {len(conversation)} messages")
Design Notes
- Immutability: Messages are dataclasses and should be treated as immutable after creation
- Timestamps: All timestamps are timezone-naive datetime objects in local time
- Unique IDs: Message IDs are UUID4 strings, globally unique across all systems
- Metadata Flexibility: Metadata dictionaries can contain any JSON-serializable data
- Role Standards: While standard roles are recommended, custom roles are fully supported
- Serialization Safety: All fields serialize safely to JSON via the
to_dict()
method
The Message class provides the foundation for all conversational AI interactions in Talk Box, enabling rich, traceable, and extensible communication between users and AI systems.