Sessions
Persist conversation history across application restarts
Sessions automatically save and restore conversation history, enabling persistent chats.
Quick Start
- 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 - 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); } - 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
Session Methods
| Method | Description |
|---|---|
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
| Option | Type | Default | Description |
|---|---|---|---|
| Session directory | Path | ~/.praisonai/sessions/ | Storage location |
| Max messages | usize | 100 | Maximum messages to retain |
Common Patterns
Multi-User Application
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.