openai_agents_rust/
memory.rs

1use async_trait::async_trait;
2use std::collections::HashMap;
3use std::sync::Arc;
4use tokio::sync::RwLock;
5use crate::error::AgentError;
6
7/// Trait representing a generic memory store.
8#[async_trait]
9pub trait Memory: Send + Sync {
10    /// Store a value under a given key.
11    async fn set(&self, key: &str, value: String) -> Result<(), AgentError>;
12
13    /// Retrieve a value for a given key.
14    async fn get(&self, key: &str) -> Result<Option<String>, AgentError>;
15}
16
17/// Simple in‑memory implementation used for a single session.
18#[derive(Clone, Default)]
19pub struct SessionMemory {
20    inner: Arc<RwLock<HashMap<String, String>>>,
21}
22
23#[async_trait]
24impl Memory for SessionMemory {
25    async fn set(&self, key: &str, value: String) -> Result<(), AgentError> {
26        let mut map = self.inner.write().await;
27        map.insert(key.to_string(), value);
28        Ok(())
29    }
30
31    async fn get(&self, key: &str) -> Result<Option<String>, AgentError> {
32        let map = self.inner.read().await;
33        Ok(map.get(key).cloned())
34    }
35}