Skip to main content

AgentState

Trait AgentState 

Source
pub trait AgentState {
    // Required methods
    fn get<'life0, 'life1, 'async_trait, T>(
        &'life0 self,
        key: &'life1 str,
    ) -> Pin<Box<dyn Future<Output = Result<Option<T>, LangGraphError>> + Send + 'async_trait>>
       where T: 'async_trait + DeserializeOwned + Send + Sync,
             Self: 'async_trait,
             'life0: 'async_trait,
             'life1: 'async_trait;
    fn set<'life0, 'life1, 'async_trait, T>(
        &'life0 self,
        key: &'life1 str,
        value: T,
    ) -> Pin<Box<dyn Future<Output = Result<bool, LangGraphError>> + Send + 'async_trait>>
       where T: 'async_trait + Serialize + Send + Sync,
             Self: 'async_trait,
             'life0: 'async_trait,
             'life1: 'async_trait;
    fn snapshot<'life0, 'async_trait>(
        &'life0 self,
        step: usize,
        node_keys: Vec<String>,
    ) -> Pin<Box<dyn Future<Output = Result<(), ()>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait;
}
Expand description

Trait defining the interface for workflow state management.

Implement this trait to create custom state backends that can be used with the workflow engine. The state is shared across all nodes in a graph and persists throughout the execution lifecycle.

§Type Safety

The trait uses Rust’s type system to ensure type-safe serialization and deserialization. Values are stored as JSON internally but accessed with full compile-time type checking.

§Concurrency Requirements

State implementations must be thread-safe (Send + Sync) since they may be accessed concurrently by parallel nodes.

§Example - Custom State Implementation

use langgraph4rust::*;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(Clone)]
struct PersistentState {
    data: Arc<RwLock<HashMap<String, String>>>,
}

impl PersistentState {
    pub fn new() -> Self {
        Self {
            data: Arc::new(RwLock::new(HashMap::new())),
        }
    }
}

#[async_trait::async_trait]
impl AgentState for PersistentState {
    async fn get<T: serde::de::DeserializeOwned + Send + Sync>(&self, key: &str) -> Result<Option<T>, LangGraphError> {
        let data = self.data.read().await;
        match data.get(key) {
            Some(value) => Ok(serde_json::from_str(value).ok()),
            None => Ok(None),
        }
    }

    async fn set<T: serde::Serialize + Send + Sync>(&self, key: &str, value: T) -> Result<bool, LangGraphError> {
        let json = serde_json::to_string(&value)
            .map_err(|e| LangGraphError::StateError(e.to_string()))?;
        let mut data = self.data.write().await;
        data.insert(key.to_string(), json);
        Ok(true)
    }

    async fn snapshot(&self, _step: usize, _node_keys: Vec<String>) -> Result<(), ()> {
        Ok(())
    }
}

Required Methods§

Source

fn get<'life0, 'life1, 'async_trait, T>( &'life0 self, key: &'life1 str, ) -> Pin<Box<dyn Future<Output = Result<Option<T>, LangGraphError>> + Send + 'async_trait>>
where T: 'async_trait + DeserializeOwned + Send + Sync, Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Retrieve a value from the state by key.

Attempts to deserialize the stored JSON value into the requested type T.

§Type Parameters
  • T: The target type to deserialize into. Must implement:
    • DeserializeOwned: Can be deserialized from owned data
    • Send: Safe to transfer between threads
    • Sync: Safe to share between threads
§Arguments
  • key - The string key to look up in the state
§Returns
  • Ok(Some(T)) if the key exists and deserialization succeeds
  • Ok(None) if the key does not exist
  • Err(LangGraphError) if deserialization fails or an I/O error occurs
§Errors

Returns LangGraphError::StateError when:

  • The stored value cannot be deserialized into type T
  • An internal storage error occurs
§Example
use langgraph4rust::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), LangGraphError> {
    let state = Arc::new(DefaultMemoryState::new());

    // Get a string value
    let name: Option<String> = state.get("user_name").await?;

    // Get an integer value
    let count: Option<i32> = state.get("counter").await?;

    // Get a complex type (must implement Deserialize)
    let data: Option<Vec<String>> = state.get("items").await?;
    Ok(())
}
Source

fn set<'life0, 'life1, 'async_trait, T>( &'life0 self, key: &'life1 str, value: T, ) -> Pin<Box<dyn Future<Output = Result<bool, LangGraphError>> + Send + 'async_trait>>
where T: 'async_trait + Serialize + Send + Sync, Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Store a value in the state under the given key.

Serializes the value to JSON and stores it. If the key already exists, its value will be overwritten.

§Type Parameters
  • T: The type of value to store. Must implement:
    • Serialize: Can be serialized to JSON
    • Send: Safe to transfer between threads
    • Sync: Safe to share between threads
§Arguments
  • key - The string key to associate with the value
  • value - The value to store (will be serialized to JSON)
§Returns
  • Ok(true) on successful storage
  • Err(LangGraphError) if serialization fails or an I/O error occurs
§Errors

Returns LangGraphError::StateError when:

  • The value cannot be serialized to JSON
  • An internal storage error occurs
§Example
use langgraph4rust::*;
use std::collections::HashMap;
use std::sync::Arc;

#[tokio::main]
async fn main() -> Result<(), LangGraphError> {
    let state = Arc::new(DefaultMemoryState::new());

    // Store primitive types
    state.set("name", "Alice").await?;
    state.set("age", 30).await?;
    state.set("active", true).await?;

    // Store complex types
    state.set("tags", vec!["rust", "workflow"]).await?;
    state.set("metadata", HashMap::from([("version", "1.0")])).await?;
    Ok(())
}
Source

fn snapshot<'life0, 'async_trait>( &'life0 self, step: usize, node_keys: Vec<String>, ) -> Pin<Box<dyn Future<Output = Result<(), ()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Save a snapshot of the current state at the given execution step.

Provides a hook for state backends to persist checkpoints at critical points during workflow execution. The default implementation is a no-op; custom backends can override this to write the state to a database, file system, or other durable storage.

Unlike set, snapshot does not modify the runtime state — it is intended solely for checkpointing purposes. The workflow engine calls this method automatically before each step’s node execution to create recovery points.

§Arguments
  • step - The current execution step number (1-indexed)
  • node_keys - The names of the nodes about to be executed in this step
§Returns
  • Ok(()) on successful snapshot
  • Err(()) if the snapshot operation fails

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§