Stateful Core

The Stateful Core provides a robust framework for managing persistent state in AI environments, enabling long-running sessions, conversation history, and complex stateful interactions.

Overview

The stateful system provides:
  • Persistent State: State that survives across sessions
  • State Serialization: Save and load environment state
  • State Versioning: Track state changes over time
  • Atomic Updates: Ensure state consistency
  • State Synchronization: Multi-instance state management

Generated Documentation

Detailed API documentation is available for:

Core Concepts

StatefulEnvironment

The base class for stateful environments:
from synth_ai.environments.stateful.core import StatefulEnvironment

class ChatEnvironment(StatefulEnvironment):
    def __init__(self, session_id: str):
        super().__init__(
            session_id=session_id,
            state_file=f"sessions/{session_id}.json"
        )
        
        # Initialize default state
        if not self.state.exists():
            self.state.conversation = []
            self.state.user_preferences = {}
            self.state.context = {}
    
    def add_message(self, role: str, content: str):
        """Add message to conversation."""
        message = {
            "role": role,
            "content": content,
            "timestamp": self.current_time(),
            "id": self.generate_id()
        }
        
        self.state.conversation.append(message)
        self.save_state()  # Persist changes
        
        return message

State Management

The state system provides structured access to persistent data:
# Access state properties
conversation = env.state.conversation
preferences = env.state.user_preferences

# Modify state
env.state.context["last_topic"] = "weather"
env.state.user_preferences["language"] = "english"

# Save changes
env.save_state()

# Load state from disk
env.load_state()

# Reset state
env.reset_state()

Persistence Backends

File-based Storage

Default JSON file storage:
env = StatefulEnvironment(
    session_id="user123",
    state_file="states/user123.json",
    backup_interval=300  # Backup every 5 minutes
)

Database Storage

Use database backends for scalability:
from synth_ai.environments.stateful.storage import DatabaseStorage

env = StatefulEnvironment(
    session_id="user123",
    storage=DatabaseStorage(
        connection_string="postgresql://user:pass@host/db",
        table_name="environment_states"
    )
)