This repository was archived by the owner on Apr 14, 2026. It is now read-only.
forked from Abraxas-365/langchain-rust
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlanggraph_persistence_basic.rs
More file actions
74 lines (65 loc) · 2.46 KB
/
langgraph_persistence_basic.rs
File metadata and controls
74 lines (65 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use langchain_ai_rust::langgraph::{
function_node, InMemorySaver, MessagesState, RunnableConfig, StateGraph, END, START,
};
use langchain_ai_rust::schemas::messages::Message;
/// Basic persistence example for LangGraph
///
/// This example demonstrates:
/// 1. Creating a graph with a checkpointer
/// 2. Invoking the graph with a thread_id
/// 3. Retrieving state and state history
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a simple node
let mock_llm = function_node("mock_llm", |_state: &MessagesState| async move {
use std::collections::HashMap;
let mut update = HashMap::new();
update.insert(
"messages".to_string(),
serde_json::to_value(vec![Message::new_ai_message("hello world")])?,
);
Ok(update)
});
// Build the graph
let mut graph = StateGraph::<MessagesState>::new();
graph.add_node("mock_llm", mock_llm)?;
graph.add_edge(START, "mock_llm");
graph.add_edge("mock_llm", END);
// Create checkpointer
let checkpointer = std::sync::Arc::new(InMemorySaver::new());
// Compile with checkpointer
let compiled = graph.compile_with_persistence(Some(checkpointer.clone()), None)?;
// Invoke with config (includes thread_id)
let config = RunnableConfig::with_thread_id("thread-1");
let initial_state = MessagesState::with_messages(vec![Message::new_human_message("hi!")]);
let final_state = compiled
.invoke_with_config(Some(initial_state), &config)
.await?;
println!("Final messages:");
for message in &final_state.messages {
println!(
" {}: {}",
message.message_type.to_string(),
message.content
);
}
// Get the latest state
let snapshot = compiled.get_state(&config).await?;
println!("\nLatest checkpoint:");
println!(" Thread ID: {}", snapshot.thread_id());
println!(" Checkpoint ID: {:?}", snapshot.checkpoint_id());
println!(" Next nodes: {:?}", snapshot.next);
println!(" Created at: {}", snapshot.created_at);
// Get state history
let history = compiled.get_state_history(&config).await?;
println!("\nState history ({} checkpoints):", history.len());
for (i, snapshot) in history.iter().enumerate() {
println!(
" {}: checkpoint_id={:?}, step={:?}",
i + 1,
snapshot.checkpoint_id(),
snapshot.metadata.get("step")
);
}
Ok(())
}