pub struct Context { /* private fields */ }
Expand description
Context for sharing data between tasks in a graph execution.
Provides thread-safe storage for workflow state and dedicated chat history management. The context is shared across all tasks in a workflow execution.
§Examples
§Basic Usage
use graph_flow::Context;
let context = Context::new();
// Store different types of data
context.set("user_id", 12345).await;
context.set("name", "Alice".to_string()).await;
context.set("settings", vec!["opt1", "opt2"]).await;
// Retrieve data
let user_id: Option<i32> = context.get("user_id").await;
let name: Option<String> = context.get("name").await;
let settings: Option<Vec<String>> = context.get("settings").await;
§Chat History
use graph_flow::Context;
let context = Context::new();
// Add messages
context.add_user_message("Hello".to_string()).await;
context.add_assistant_message("Hi there!".to_string()).await;
// Get message history
let history = context.get_chat_history().await;
let last_5 = context.get_last_messages(5).await;
Implementations§
Source§impl Context
impl Context
Sourcepub fn with_max_chat_messages(max: usize) -> Self
pub fn with_max_chat_messages(max: usize) -> Self
Create a new context with a maximum chat history size.
When the chat history exceeds this size, older messages are automatically removed.
§Examples
use graph_flow::Context;
let context = Context::with_max_chat_messages(50);
// Chat history will be limited to 50 messages
for i in 0..100 {
context.add_user_message(format!("Message {}", i)).await;
}
assert_eq!(context.chat_history_len().await, 50);
Sourcepub async fn set(&self, key: impl Into<String>, value: impl Serialize)
pub async fn set(&self, key: impl Into<String>, value: impl Serialize)
Set a value in the context.
The value must be serializable. Most common Rust types are supported.
§Examples
use graph_flow::Context;
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct UserData {
id: u32,
name: String,
}
let context = Context::new();
// Store primitive types
context.set("count", 42).await;
context.set("name", "Alice".to_string()).await;
context.set("active", true).await;
// Store complex types
let user = UserData { id: 1, name: "Bob".to_string() };
context.set("user", user).await;
Sourcepub async fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T>
pub async fn get<T: DeserializeOwned>(&self, key: &str) -> Option<T>
Get a value from the context.
Returns None
if the key doesn’t exist or if deserialization fails.
§Examples
use graph_flow::Context;
let context = Context::new();
context.set("count", 42).await;
let count: Option<i32> = context.get("count").await;
assert_eq!(count, Some(42));
let missing: Option<String> = context.get("missing").await;
assert_eq!(missing, None);
Sourcepub async fn remove(&self, key: &str) -> Option<Value>
pub async fn remove(&self, key: &str) -> Option<Value>
Remove a value from the context.
Returns the removed value if it existed.
§Examples
use graph_flow::Context;
let context = Context::new();
context.set("temp", "value".to_string()).await;
let removed = context.remove("temp").await;
assert!(removed.is_some());
let value: Option<String> = context.get("temp").await;
assert_eq!(value, None);
Sourcepub async fn clear(&self)
pub async fn clear(&self)
Clear all regular context data (does not affect chat history).
§Examples
use graph_flow::Context;
let context = Context::new();
context.set("key1", "value1".to_string()).await;
context.set("key2", "value2".to_string()).await;
context.add_user_message("Hello".to_string()).await;
context.clear().await;
// Regular data is cleared
let value: Option<String> = context.get("key1").await;
assert_eq!(value, None);
// Chat history is preserved
assert_eq!(context.chat_history_len().await, 1);
Sourcepub fn get_sync<T: DeserializeOwned>(&self, key: &str) -> Option<T>
pub fn get_sync<T: DeserializeOwned>(&self, key: &str) -> Option<T>
Synchronous version of get for use in edge conditions.
This method should only be used when you’re certain the data exists and when async is not available (e.g., in edge condition closures).
§Examples
use graph_flow::{Context, GraphBuilder};
let context = Context::new();
context.set("condition", true).await;
// Used in edge conditions
let graph = GraphBuilder::new("test")
.add_conditional_edge(
"task1",
|ctx| ctx.get_sync::<bool>("condition").unwrap_or(false),
"task2",
"task3"
);
Sourcepub fn set_sync(&self, key: impl Into<String>, value: impl Serialize)
pub fn set_sync(&self, key: impl Into<String>, value: impl Serialize)
Synchronous version of set for use when async is not available.
§Examples
use graph_flow::Context;
let context = Context::new();
context.set_sync("key", "value".to_string());
let value: Option<String> = context.get_sync("key");
assert_eq!(value, Some("value".to_string()));
Sourcepub async fn add_user_message(&self, content: String)
pub async fn add_user_message(&self, content: String)
Add a user message to the chat history.
§Examples
use graph_flow::Context;
let context = Context::new();
context.add_user_message("Hello, assistant!".to_string()).await;
Sourcepub async fn add_assistant_message(&self, content: String)
pub async fn add_assistant_message(&self, content: String)
Add an assistant message to the chat history.
§Examples
use graph_flow::Context;
let context = Context::new();
context.add_assistant_message("Hello! How can I help you?".to_string()).await;
Sourcepub async fn add_system_message(&self, content: String)
pub async fn add_system_message(&self, content: String)
Add a system message to the chat history.
§Examples
use graph_flow::Context;
let context = Context::new();
context.add_system_message("Session started".to_string()).await;
Sourcepub async fn get_chat_history(&self) -> ChatHistory
pub async fn get_chat_history(&self) -> ChatHistory
Get a clone of the current chat history.
§Examples
use graph_flow::Context;
let context = Context::new();
context.add_user_message("Hello".to_string()).await;
let history = context.get_chat_history().await;
assert_eq!(history.len(), 1);
Sourcepub async fn clear_chat_history(&self)
pub async fn clear_chat_history(&self)
Clear the chat history.
§Examples
use graph_flow::Context;
let context = Context::new();
context.add_user_message("Hello".to_string()).await;
assert_eq!(context.chat_history_len().await, 1);
context.clear_chat_history().await;
assert_eq!(context.chat_history_len().await, 0);
Sourcepub async fn chat_history_len(&self) -> usize
pub async fn chat_history_len(&self) -> usize
Get the number of messages in the chat history.
Sourcepub async fn is_chat_history_empty(&self) -> bool
pub async fn is_chat_history_empty(&self) -> bool
Check if the chat history is empty.
Sourcepub async fn get_last_messages(&self, n: usize) -> Vec<SerializableMessage>
pub async fn get_last_messages(&self, n: usize) -> Vec<SerializableMessage>
Get the last N messages from chat history.
§Examples
use graph_flow::Context;
let context = Context::new();
context.add_user_message("Message 1".to_string()).await;
context.add_user_message("Message 2".to_string()).await;
context.add_user_message("Message 3".to_string()).await;
let last_two = context.get_last_messages(2).await;
assert_eq!(last_two.len(), 2);
assert_eq!(last_two[0].content, "Message 2");
assert_eq!(last_two[1].content, "Message 3");
Sourcepub async fn get_all_messages(&self) -> Vec<SerializableMessage>
pub async fn get_all_messages(&self) -> Vec<SerializableMessage>
Get all messages from chat history as SerializableMessage.
§Examples
use graph_flow::Context;
let context = Context::new();
context.add_user_message("Hello".to_string()).await;
context.add_assistant_message("Hi there!".to_string()).await;
let all_messages = context.get_all_messages().await;
assert_eq!(all_messages.len(), 2);
Trait Implementations§
Source§impl<'de> Deserialize<'de> for Context
impl<'de> Deserialize<'de> for Context
Source§fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>where
D: Deserializer<'de>,
Auto Trait Implementations§
impl Freeze for Context
impl !RefUnwindSafe for Context
impl Send for Context
impl Sync for Context
impl Unpin for Context
impl !UnwindSafe for Context
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more