Message

Represents a single message in a conversational AI interaction, discovered through Conversation objects.

USAGE

Message(
    content,
    role,
    timestamp=datetime.now(),
    metadata=dict(),
    message_id=(lambda: str(uuid4()))(),
)

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: ChatBotConversationMessage, where each layer provides progressively more detailed control over conversational AI interactions.

Discovery through the layered API:

  1. Start with ChatBot.chat() → returns Conversation
  2. Explore Conversation.get_messages() → returns list of Message
  3. 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.

Message Serialization

Messages support full serialization to and from dictionary format for storage and transmission:

The serialization format preserves all message information including timestamps and metadata, enabling reliable persistence and reconstruction.

Examples


Creating basic messages

Create messages for different conversation participants:

from talk_box import Message
from datetime import datetime

# User message - most common type
user_msg = Message(
    content="What are the key principles of machine learning?",
    role="user"
)

# Assistant response
assistant_msg = Message(
    content="Machine learning has three key principles: representation, evaluation, and optimization...",
    role="assistant"
)

# System instruction
system_msg = Message(
    content="You are a helpful AI assistant specializing in technical topics.",
    role="system"
)

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
detailed_msg = Message(
    content="Here's the code implementation you requested...",
    role="assistant",
    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
original_msg = Message(
    content="Serialize this message for storage",
    role="user",
    metadata={"importance": "high", "category": "technical"}
)

# Convert to dictionary (for JSON storage, API calls, etc.)
msg_dict = original_msg.to_dict()
print("Serialized message:", msg_dict)

# Reconstruct from dictionary
restored_msg = Message.from_dict(msg_dict)
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
function_call = Message(
    content="calculate_statistics",
    role="function",
    metadata={
        "function_name": "calculate_statistics",
        "arguments": {"data": [1, 2, 3, 4, 5], "method": "mean"},
        "call_id": "func_001"
    }
)

# Function result
function_result = Message(
    content="Statistics calculated: mean=3.0, std=1.58",
    role="function",
    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
code_submission = Message(
    content="def fibonacci(n): return n if n <= 1 else fibonacci(n-1) + fibonacci(n-2)",
    role="developer"
)

code_review = Message(
    content="Consider using memoization to improve performance for large n values.",
    role="reviewer",
    metadata={
        "review_type": "performance",
        "severity": "suggestion",
        "line_numbers": [1]
    }
)

# Documentation workflow
doc_request = Message(
    content="Please document the fibonacci function",
    role="doc_manager"
)

documentation = Message(
    content="Calculates the nth Fibonacci number using recursive approach...",
    role="technical_writer",
    metadata={
        "doc_type": "function_docstring",
        "coverage": "complete"
    }
)

Message validation and filtering

Messages can be validated and filtered based on their attributes:

messages = [user_msg, assistant_msg, system_msg, detailed_msg]

# Filter by role
user_messages = [msg for msg in messages if msg.role == "user"]
assistant_messages = [msg for msg in messages if msg.role == "assistant"]

# Filter by metadata presence
messages_with_metadata = [msg for msg in messages if msg.metadata]

# Filter by timestamp (messages from last hour)
from datetime import timedelta
recent_cutoff = datetime.now() - timedelta(hours=1)
recent_messages = [msg for msg in messages if msg.timestamp > recent_cutoff]

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
conversation.add_message("Hello, I need help with Python", "user")
conversation.add_message("I'd be happy to help! What specific topic?", "assistant")

# Or add pre-created Message objects
detailed_question = Message(
    content="How do I implement a binary search algorithm?",
    role="user",
    metadata={"topic": "algorithms", "difficulty": "intermediate"}
)
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.