Context

Struct Context 

Source
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

Source

pub fn new() -> Self

Create a new empty context.

Source

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);
Source

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;
Source

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);
Source

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);
Source

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);
Source

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"
    );
Source

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()));
Source

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;
Source

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;
Source

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;
Source

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);
Source

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);
Source

pub async fn chat_history_len(&self) -> usize

Get the number of messages in the chat history.

Source

pub async fn is_chat_history_empty(&self) -> bool

Check if the chat history is empty.

Source

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");
Source

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 Clone for Context

Source§

fn clone(&self) -> Context

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Context

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Context

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Context

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Context

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,