Skip to main content

openai_agents/session/
mod.rs

1//! Session management for conversation history
2
3use async_trait::async_trait;
4use serde_json::Value;
5
6use crate::error::Result;
7
8/// Trait for session storage
9#[async_trait]
10pub trait Session: Send + Sync {
11    /// Get items from the session
12    async fn get_items(&self, limit: Option<usize>) -> Result<Vec<Value>>;
13
14    /// Add items to the session
15    async fn add_items(&self, items: Vec<Value>) -> Result<()>;
16
17    /// Remove and return the most recent item
18    async fn pop_item(&self) -> Result<Option<Value>>;
19
20    /// Clear all items from the session
21    async fn clear_session(&self) -> Result<()>;
22}
23
24/// Session settings
25#[derive(Debug, Clone, Default)]
26pub struct SessionSettings {
27    /// Maximum number of items to keep in session
28    pub max_items: Option<usize>,
29}
30
31#[cfg(feature = "sqlite-session")]
32pub mod sqlite;
33
34#[cfg(feature = "sqlite-session")]
35pub use sqlite::SqliteSession;
36
37/// In-memory session implementation (for testing and simple use cases)
38pub struct InMemorySession {
39    items: std::sync::Arc<tokio::sync::Mutex<Vec<Value>>>,
40}
41
42impl InMemorySession {
43    /// Create a new in-memory session
44    pub fn new() -> Self {
45        Self {
46            items: std::sync::Arc::new(tokio::sync::Mutex::new(Vec::new())),
47        }
48    }
49}
50
51impl Default for InMemorySession {
52    fn default() -> Self {
53        Self::new()
54    }
55}
56
57#[async_trait]
58impl Session for InMemorySession {
59    async fn get_items(&self, limit: Option<usize>) -> Result<Vec<Value>> {
60        let items = self.items.lock().await;
61        if let Some(n) = limit {
62            let start = items.len().saturating_sub(n);
63            Ok(items[start..].to_vec())
64        } else {
65            Ok(items.clone())
66        }
67    }
68
69    async fn add_items(&self, new_items: Vec<Value>) -> Result<()> {
70        let mut items = self.items.lock().await;
71        items.extend(new_items);
72        Ok(())
73    }
74
75    async fn pop_item(&self) -> Result<Option<Value>> {
76        let mut items = self.items.lock().await;
77        Ok(items.pop())
78    }
79
80    async fn clear_session(&self) -> Result<()> {
81        let mut items = self.items.lock().await;
82        items.clear();
83        Ok(())
84    }
85}