Sessions

Persist conversation history across application restarts

Sessions automatically save and restore conversation history, enabling persistent chats.

Diagram

Session Persistence

💬 Chat 1

💾 Session

💬 Chat 2

Quick Start

  1. Create a Session
    rust
    use praisonai::Session;
    
    // Create a new session (automatically loads if exists)
    let mut session = Session::new("user-123-chat");
    
    // Add messages
    session.add_user_message("My name is Alice").await?;
    session.add_assistant_message("Nice to meet you, Alice!").await?;
    
    // Session automatically saved to disk
  2. Load Existing Session
    rust
    use praisonai::Session;
    
    // Explicitly load an existing session
    let session = Session::load("user-123-chat")?;
    
    // Get message history
    let history = session.get_history();
    for msg in history {
        println!("{}: {}", msg.role, msg.content);
    }
  3. Use Session with Store
    rust
    use praisonai::{Session, FileSessionStore};
    use std::sync::Arc;
    
    // Create with custom directory
    let store = Arc::new(FileSessionStore::with_dir("/custom/path"));
    let session = Session::with_store("chat-123", store);

How It Works

Diagram
DiskSessionAgentUserDiskSessionAgentUserLater, new application instancechat(“My name is Alice”)Add messageSave to ~/.praisonai/sessions/Session::load(“user-123”)Read saved dataPrevious messageschat(“What’s my name?”)“Your name is Alice”

Session Methods

MethodDescription
Session::new(id)Create new session
Session::load(id)Load existing session
session.save()Save session to disk
session.add_message(msg)Add a message
session.get_history()Get message history
session.clear()Clear all messages

Configuration

OptionTypeDefaultDescription
Session directoryPath~/.praisonai/sessions/Storage location
Max messagesusize100Maximum messages to retain

Common Patterns

Multi-User Application

rust
use praisonai::{Agent, Session};

async fn handle_user(user_id: &str, message: &str) -> String {
    // Each user gets their own persistent session
    let session = Session::load(user_id)
        .unwrap_or_else(|_| Session::new(user_id));

    let agent = Agent::new()
        .name("Assistant")
        .session(session)
        .build()
        .unwrap();

    agent.chat(message).await.unwrap()
}

Best Practices

Use meaningful session IDs

Include user ID or context in session IDs for easy management.

Handle load failures

Use unwrap_or_else to create new sessions if loading fails.

Limit message history

Sessions auto-trim to max_messages to prevent unbounded growth.


Related