Build a support ticket agent
In this tutorial you build a support ticket agent, one piece at a time. It classifies a ticket with a tool, drafts a reply that streams out token by token, records the conversation, and then waits for a person to approve the reply before it sends it. The wait survives a restart: you approve the ticket from a second run of the program.
You don’t need an API key. A small function stands in for the model, so every run gives the same output. The program follows the example agent in the framework repository (examples/dotnet-agent and examples/rust-agent), adapted to the published packages and to a SQLite file.
What you’ll build
Section titled “What you’ll build”The agent is a graph of three nodes, with a pause between the second and the third:
- Classify calls the
classify_tickettool and stores the category. - DraftReply streams a reply, stores it, and writes the customer’s message and the reply to a history store.
- The run pauses for a person to approve the reply. The program exits.
- SendReply runs when someone approves, in a new run of the program.
The first run (dotnet run or cargo run) prints the nodes as they start and the reply as it streams, then stops at the pause:
-> Classify-> DraftReplyThanks for writing in. Your ticket is with our billing team, and they will reply within one business day.Paused after DraftReply, before SendReply.The second run (dotnet run -- approve or cargo run -- approve) shows the reviewer the draft, approves it, and reads the conversation back:
Review T-1001 (billing): Thanks for writing in. Your ticket is with our billing team, and they will reply within one business day.Completed: category billing, status sent (approved by dana@example.com)[User] My invoice total looks wrong this month[Assistant] Thanks for writing in. Your ticket is with our billing team, and they will reply within one business day.Both languages print exactly this.
Before you start
Section titled “Before you start”- Do the Quickstart first. This tutorial assumes you know what a node, an edge and a run are.
- Have the .NET 10 SDK or a Rust toolchain, as listed in Requirements.
- You need no database server. The SQLite stores are built into the packages.
1. Create the project
Section titled “1. Create the project”dotnet new console -n TicketAgentcd TicketAgentdotnet add package Datalium.Strata.Hosting --version 0.9.0-preview.2Datalium.Strata.Hosting brings the engine, the [StrataTool] source generator and the SQLite stores. Replace Program.cs with these lines. Each step adds code to this file.
using System.Text.Json;using Datalium.Strata.Graph;using Datalium.Strata.Interruption;using Datalium.Strata.Memory;using Datalium.Strata.Storage.Memory;using Datalium.Strata.Streaming;using Datalium.Strata.Tools;using Microsoft.EntityFrameworkCore;
const string TicketId = "T-1001";const string DbPath = "tickets.db";cargo new ticket-agentcd ticket-agentSet the dependencies in Cargo.toml. datalium-strata-memory has the SQLite stores.
[dependencies]chrono = "0.4"datalium-strata = "=0.9.0-preview.2"datalium-strata-memory = "=0.9.0-preview.2"serde = { version = "1", features = ["derive"] }serde_json = "1"tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }Replace src/main.rs with these lines. Each step adds code to this file. Until the last step, the compiler warns about imports you don’t use yet.
use std::io::Write;use std::sync::Arc;use std::time::Duration;
use datalium_strata::checkpoint::{GraphExecutionResult, HumanSignal};use datalium_strata::context::{NodeContext, RunConfig};use datalium_strata::graph::StateGraph;use datalium_strata::history::{ChatMessage, HistoryStore, MessageRole};use datalium_strata::prelude::*;use datalium_strata::store::CheckpointStore;use datalium_strata::streaming::StreamChunkType;use datalium_strata_memory::checkpoint::SqliteCheckpointStore;use datalium_strata_memory::history::SqliteHistoryStore;use serde::{Deserialize, Serialize};
const TICKET_ID: &str = "T-1001";const DB_PATH: &str = "tickets.db";2. Define the ticket state
Section titled “2. Define the ticket state”The state is the data that moves through the graph. Every node gets the current ticket and returns a new one. It holds what the next nodes need: the ticket’s subject, its category, the draft reply and a status. State explains the rules.
Add the record at the end of Program.cs. Types go after the top-level code, so keep it last as the file grows.
public sealed record Ticket( string TicketId, string Subject, string? Category = null, string? Draft = null, string Status = "open");Add the struct after the constants. Strata saves the state as JSON, so it derives Serialize and Deserialize.
#[derive(Debug, Clone, Serialize, Deserialize)]struct Ticket { ticket_id: String, subject: String, category: Option<String>, draft: Option<String>, status: String,}
impl Ticket { fn new(ticket_id: &str, subject: &str) -> Self { Ticket { ticket_id: ticket_id.to_string(), subject: subject.to_string(), category: None, draft: None, status: "open".to_string(), } }}3. Write a tool
Section titled “3. Write a tool”A tool is a function that your code, or a model, calls by name with JSON arguments. Strata generates its schema and its dispatch code when you compile. This one sorts a subject line into a category by keywords. In a real agent it might call your ticketing system.
Create TicketTools.cs. The class must be partial: the source generator adds the part that dispatches calls to your method.
using Datalium.Strata.Tools;
public partial class TicketTools{ [StrataTool(Name = "classify_ticket", Description = "Classifies a support ticket subject line into a category.")] public static string ClassifyTicket(string subject) { var lowered = subject.ToLowerInvariant(); return lowered.Contains("invoice") || lowered.Contains("bill") ? "billing" : lowered.Contains("crash") || lowered.Contains("error") ? "technical" : "general"; }}Add the arguments struct and the tool after the state. The macro generates a handle for the tool named ClassifyTicketTool.
#[derive(Deserialize, StrataSchema)]struct ClassifyArgs { subject: String,}
#[strata_tool( name = "classify_ticket", description = "Classifies a support ticket subject line into a category.")]async fn classify_ticket(args: ClassifyArgs) -> Result<String, StrataError> { let subject = args.subject.to_lowercase(); let category = if subject.contains("invoice") || subject.contains("bill") { "billing" } else if subject.contains("crash") || subject.contains("error") { "technical" } else { "general" }; Ok(category.to_string())}Define tools covers the argument types, the schema a model sees, and tool errors.
4. Call the tool from a node
Section titled “4. Call the tool from a node”Put the tool in a ToolRegistry, and build a graph whose first node calls it. Each call through a registry is traced and reported as run events.
Add this after the constants:
var tools = new ToolRegistry().Register(new TicketTools());
var graph = new StateGraph<Ticket>() .AddNode("Classify", async (state, ctx, ct) => { var arguments = JsonSerializer.Serialize(new { subject = state.Subject }); var json = await tools.DispatchToolAsync("classify_ticket", arguments, ToolCallContext.From(ctx), ct); var category = JsonDocument.Parse(json).RootElement.GetProperty("result").GetString(); return state with { Category = category }; }) .Compile();The tool’s result comes back as JSON, {"result": "billing"}, so the node reads the result property.
Add main after the tool:
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let mut tools = ToolRegistry::new(); tools.register(Box::new(ClassifyTicketTool)); let tools = Arc::new(tools);
let graph = Arc::new( StateGraph::<Ticket>::new() .add_async_node("Classify", move |state: Ticket, ctx: NodeContext| { let tools = tools.clone(); async move { let arguments = serde_json::json!({ "subject": state.subject }).to_string(); let category = tools .dispatch_with("classify_ticket", &arguments, ToolCallContext::from(&ctx)) .await .expect("classify_ticket failed"); Ticket { category: Some(category), ..state } } }) .compile() .expect("the graph is valid"), );
Ok(())}The tool’s result comes back as the String it returned. The graph is in an Arc because a streaming run, in the next step, needs one.
Classify is an async node. Besides the state, it gets a NodeContext: the thread ID, the run’s stream and history store, and more. ToolCallContext.From(ctx) / ToolCallContext::from(&ctx) passes that context on to the tool call, so the call is linked to this run and node.
5. Open the stores and run it
Section titled “5. Open the stores and run it”A run needs a checkpoint store, where Strata saves a thread when it stops before the end. This agent also needs a history store for the conversation. Both SQLite stores can share one file, tickets.db.
Add this after the graph. Describe goes just before the Ticket record.
if (args is not ["approve"]){ File.Delete(DbPath); // a new ticket starts from an empty file}
using var checkpoints = new EfCoreCheckpointStore(new CheckpointDbContext( new DbContextOptionsBuilder<CheckpointDbContext>().UseSqlite($"Data Source={DbPath}").Options));using var history = new EfCoreHistoryStore(new HistoryDbContext( new DbContextOptionsBuilder<HistoryDbContext>().UseSqlite($"Data Source={DbPath}").Options));var options = new RunOptions { History = history };
var ticket = new Ticket(TicketId, "My invoice total looks wrong this month");var (reader, completion) = graph.RunStreaming(TicketId, ticket, checkpoints, options);await foreach (var chunk in reader.ReadAllAsync()){ if (chunk.Type == StreamChunkType.NodeStart) { Console.WriteLine($"-> {chunk.NodeName}"); } else if (chunk.Type == StreamChunkType.Token) { Console.Write(chunk.Payload); }}
Console.WriteLine();Console.WriteLine(Describe(await completion));
static string Describe(GraphExecutionResult<Ticket> result) => result switch{ GraphExecutionResult<Ticket>.Completed done => $"Completed: category {done.State.Category}, status {done.State.Status}", GraphExecutionResult<Ticket>.Interrupted paused => $"Paused after {paused.SuspendedNode}, before {paused.NextNode}.", GraphExecutionResult<Ticket>.Failed failed => $"Failed: {failed.Message}", _ => result.ToString(),};RunOptions.History gives the history store to every async node’s context.
Add the first line at the top of main, and the rest between the graph and Ok(()). describe goes after main.
let approve = std::env::args().nth(1).as_deref() == Some("approve");
// ... the tools and the graph ...
if !approve { let _ = std::fs::remove_file(DB_PATH); // a new ticket starts from an empty file }
let checkpoints = Arc::new(SqliteCheckpointStore::open(DB_PATH)?); let history = Arc::new(SqliteHistoryStore::open(DB_PATH)?); let config = RunConfig::new().with_history(history.clone());
let ticket = Ticket::new(TICKET_ID, "My invoice total looks wrong this month"); let (handle, mut chunks) = graph.run_streaming_with(TICKET_ID, ticket, checkpoints.clone(), config); while let Some(chunk) = chunks.recv().await { match chunk.chunk_type { StreamChunkType::NodeStart => println!("-> {}", chunk.node_name), StreamChunkType::Token => { print!("{}", chunk.content); std::io::stdout().flush()?; } _ => {} } } println!(); println!("{}", describe(&handle.await?));fn describe(result: &GraphExecutionResult<Ticket>) -> String { match result { GraphExecutionResult::Completed(state) => format!( "Completed: category {}, status {}", state.category.as_deref().unwrap_or("-"), state.status ), GraphExecutionResult::Interrupted { suspended_node, next_node, .. } => { format!("Paused after {suspended_node}, before {next_node}.") } GraphExecutionResult::Failed(StrataError::ExecutionAborted(message)) => { format!("Failed: {message}") } GraphExecutionResult::Failed(error) => format!("Failed: {error:?}"), _ => "The run ended early.".to_string(), }}RunConfig::with_history gives the history store to every async node’s context.
RunStreaming / run_streaming_with starts the run in the background and hands you a reader of stream chunks and the run’s result. The engine sends a NodeStart chunk before each node. The thread ID, T-1001, names this ticket’s thread. Step 8 uses it to find the ticket again.
The file is deleted when the program runs without arguments, so every run starts a fresh ticket. Step 8 adds an approve argument that keeps the file.
Run it now with dotnet run or cargo run:
-> Classify
Completed: category billing, status openThe tool classified the ticket as billing.
6. Stream a draft reply and record it
Section titled “6. Stream a draft reply and record it”The next node writes the reply. A real agent would ask a model, and send each token to the reader as it arrives. Here, DraftTokens / draft_tokens splits a fixed reply into words, and a short sleep stands in for the model’s latency.
Add the node after Classify, and an edge to it, before .Compile():
.AddNode("DraftReply", async (state, ctx, ct) => { var draft = ""; foreach (var token in DraftTokens(state.Category!)) { await Task.Delay(50, ct); // stands in for a model's latency if (ctx.Stream is { } stream) { await stream.EmitTokenAsync(token, ct); }
draft += token; }
var now = DateTimeOffset.UtcNow; await ctx.History!.AppendAsync(ctx.ThreadId, new ChatMessage(MessageRole.User, state.Subject.AsMemory(), now), ct); await ctx.History!.AppendAsync(ctx.ThreadId, new ChatMessage(MessageRole.Assistant, draft.AsMemory(), now), ct); return state with { Draft = draft }; }) .AddEdge("Classify", "DraftReply")Add the token generator before Describe:
static IEnumerable<string> DraftTokens(string category){ var reply = $"Thanks for writing in. Your ticket is with our {category} team, and they will reply within one business day."; var words = reply.Split(' '); for (var i = 0; i < words.Length; i++) { yield return i == 0 ? words[i] : " " + words[i]; }}Add the node after Classify, and an edge to it, before .compile():
.add_async_node("DraftReply", |state: Ticket, ctx: NodeContext| async move { let mut draft = String::new(); for token in draft_tokens(state.category.as_deref().unwrap_or("general")) { tokio::time::sleep(Duration::from_millis(50)).await; // stands in for a model's latency if let Some(stream) = ctx.stream() { stream.emit_token(&token).await.expect("the stream is open"); } draft.push_str(&token); }
let history = ctx.history().expect("the run has a history store"); let now = chrono::Utc::now(); for (role, content) in [ (MessageRole::User, state.subject.as_str()), (MessageRole::Assistant, draft.as_str()), ] { let message = ChatMessage { role, content: Arc::from(content), timestamp: now, }; history .append(ctx.thread_id(), message) .await .expect("history write failed"); } Ticket { draft: Some(draft), ..state } }) .add_edge("Classify", "DraftReply")Add the token generator after main:
fn draft_tokens(category: &str) -> Vec<String> { let reply = format!( "Thanks for writing in. Your ticket is with our {category} team, and they will reply within one business day." ); reply .split(' ') .enumerate() .map(|(i, word)| { if i == 0 { word.to_string() } else { format!(" {word}") } }) .collect()}The node does three things:
- It streams. Under a streaming run, the node’s context carries the run’s stream, and
EmitTokenAsync/emit_tokensends aTokenchunk to your reader. Under a plainRunAsync/runthere is no stream, so the node checks for one first. - It records the conversation. It appends the customer’s message and the draft to the history store, keyed by the thread ID. The conversation lives there, not in the state, so checkpoints stay small. See State, history and long-term memory.
- It stores the draft in the state, where the reviewer reads it in step 8.
Run it now. The reply appears a word at a time:
-> Classify-> DraftReplyThanks for writing in. Your ticket is with our billing team, and they will reply within one business day.Completed: category billing, status open7. Pause for approval
Section titled “7. Pause for approval”Nothing should reach the customer before a person reads the draft. An interrupt boundary on DraftReply stops the run after that node: Strata saves the thread, with its state and the node to run next, to the checkpoint store, and the run returns Interrupted.
Add these after the Classify to DraftReply edge, before .Compile():
.AddInterruptBoundary("DraftReply") .AddNode("SendReply", (state, ctx, _) => ValueTask.FromResult(state with { Status = $"sent (approved by {ctx.Decision!.Reviewer})" })) .AddEdge("DraftReply", "SendReply")Add these after the Classify to DraftReply edge, before .compile():
.add_interrupt_boundary("DraftReply") .add_async_node("SendReply", |state: Ticket, ctx: NodeContext| { let reviewer = &ctx .decision() .expect("SendReply runs after an approval") .reviewer; std::future::ready(Ticket { status: format!("sent (approved by {reviewer})"), ..state }) }) .add_edge("DraftReply", "SendReply")SendReply would send the reply. Here it only sets the status. It reads who approved from the recorded decision, ctx.Decision / ctx.decision(), which a resume sets for every node after the boundary.
Run it now:
-> Classify-> DraftReplyThanks for writing in. Your ticket is with our billing team, and they will reply within one business day.Paused after DraftReply, before SendReply.The program exits, and nothing of the ticket stays in memory. It is in tickets.db. If you installed the strata CLI, you can see it waiting:
strata thread list --storage tickets.db --status interrupted+-----------+--------------+-------------+-------------+-------------+----------------------+| Thread ID | Current Node | Sequence ID | State | Waiting For | Updated At |+-----------+--------------+-------------+-------------+-------------+----------------------+| T-1001 | DraftReply | 0 | interrupted | - | 2026-10-30T15:29:53Z |+-----------+--------------+-------------+-------------+-------------+----------------------+8. Approve after a restart
Section titled “8. Approve after a restart”The reviewer’s answer comes in a new process. It builds the same graph from your code, opens the same file, shows the reviewer the draft, and resumes the thread with a HumanSignal.
Add this right after the options line:
if (args is ["approve"]){ var checkpoint = await checkpoints.LoadAsync(TicketId); var pending = checkpoint!.FrozenState.Deserialize<Ticket>()!; Console.WriteLine($"Review {pending.TicketId} ({pending.Category}): {pending.Draft}");
var resumed = await graph.ResumeAsync(TicketId, HumanSignal.Approve("dana@example.com"), checkpoints, options); Console.WriteLine(Describe(resumed));
return;}Add this right after the config line:
if approve { let checkpoint = checkpoints .load(TICKET_ID) .await? .expect("the ticket has a checkpoint"); let pending: Ticket = serde_json::from_value(checkpoint.frozen_state)?; println!( "Review {} ({}): {}", pending.ticket_id, pending.category.unwrap_or_default(), pending.draft.unwrap_or_default() );
let signal = HumanSignal::approve("dana@example.com"); let resumed = graph .resume_with(TICKET_ID, signal, checkpoints.clone(), config) .await; println!("{}", describe(&resumed));
return Ok(()); }The checkpoint’s frozen state is the ticket as DraftReply left it, saved as JSON. The resume loads the thread, records the decision, and continues at SendReply. It gets the same run options, so nodes after the boundary have the history store too. The reviewer is an identity, such as an email address. Strata saves it in later checkpoints, so never put a credential there.
Run it now. Start a ticket with dotnet run or cargo run, then approve it in a second run with dotnet run -- approve or cargo run -- approve:
Review T-1001 (billing): Thanks for writing in. Your ticket is with our billing team, and they will reply within one business day.Completed: category billing, status sent (approved by dana@example.com)A waiting thread can be answered once. Approve it again and the resume is refused, with nothing run:
Failed: checkpoint for thread 'T-1001' was already resumed9. Read the history back
Section titled “9. Read the history back”Last, show the conversation that DraftReply recorded. It is in the same file, so the new process reads it too.
Add this in the approve block, before return;:
await foreach (var message in history.GetHistoryAsync(TicketId)) { Console.WriteLine($"[{message.Role}] {message.Content}"); }GetHistoryAsync streams the most recent messages, 50 by default, oldest first.
Add this in the approve block, before return Ok(());:
for message in history.get_history(TICKET_ID, 50).await? { println!("[{:?}] {}", message.role, message.content); }get_history returns at most the 50 most recent messages, oldest first, as a Vec.
Run it now, both commands again. The second one prints the output shown at the top of this page:
Review T-1001 (billing): Thanks for writing in. Your ticket is with our billing team, and they will reply within one business day.Completed: category billing, status sent (approved by dana@example.com)[User] My invoice total looks wrong this month[Assistant] Thanks for writing in. Your ticket is with our billing team, and they will reply within one business day.The full program
Section titled “The full program”Program.cs:
using System.Text.Json;using Datalium.Strata.Graph;using Datalium.Strata.Interruption;using Datalium.Strata.Memory;using Datalium.Strata.Storage.Memory;using Datalium.Strata.Streaming;using Datalium.Strata.Tools;using Microsoft.EntityFrameworkCore;
const string TicketId = "T-1001";const string DbPath = "tickets.db";
var tools = new ToolRegistry().Register(new TicketTools());
var graph = new StateGraph<Ticket>() .AddNode("Classify", async (state, ctx, ct) => { var arguments = JsonSerializer.Serialize(new { subject = state.Subject }); var json = await tools.DispatchToolAsync("classify_ticket", arguments, ToolCallContext.From(ctx), ct); var category = JsonDocument.Parse(json).RootElement.GetProperty("result").GetString(); return state with { Category = category }; }) .AddNode("DraftReply", async (state, ctx, ct) => { var draft = ""; foreach (var token in DraftTokens(state.Category!)) { await Task.Delay(50, ct); // stands in for a model's latency if (ctx.Stream is { } stream) { await stream.EmitTokenAsync(token, ct); }
draft += token; }
var now = DateTimeOffset.UtcNow; await ctx.History!.AppendAsync(ctx.ThreadId, new ChatMessage(MessageRole.User, state.Subject.AsMemory(), now), ct); await ctx.History!.AppendAsync(ctx.ThreadId, new ChatMessage(MessageRole.Assistant, draft.AsMemory(), now), ct); return state with { Draft = draft }; }) .AddInterruptBoundary("DraftReply") .AddNode("SendReply", (state, ctx, _) => ValueTask.FromResult(state with { Status = $"sent (approved by {ctx.Decision!.Reviewer})" })) .AddEdge("Classify", "DraftReply") .AddEdge("DraftReply", "SendReply") .Compile();
if (args is not ["approve"]){ File.Delete(DbPath); // a new ticket starts from an empty file}
using var checkpoints = new EfCoreCheckpointStore(new CheckpointDbContext( new DbContextOptionsBuilder<CheckpointDbContext>().UseSqlite($"Data Source={DbPath}").Options));using var history = new EfCoreHistoryStore(new HistoryDbContext( new DbContextOptionsBuilder<HistoryDbContext>().UseSqlite($"Data Source={DbPath}").Options));var options = new RunOptions { History = history };
if (args is ["approve"]){ var checkpoint = await checkpoints.LoadAsync(TicketId); var pending = checkpoint!.FrozenState.Deserialize<Ticket>()!; Console.WriteLine($"Review {pending.TicketId} ({pending.Category}): {pending.Draft}");
var resumed = await graph.ResumeAsync(TicketId, HumanSignal.Approve("dana@example.com"), checkpoints, options); Console.WriteLine(Describe(resumed));
await foreach (var message in history.GetHistoryAsync(TicketId)) { Console.WriteLine($"[{message.Role}] {message.Content}"); }
return;}
var ticket = new Ticket(TicketId, "My invoice total looks wrong this month");var (reader, completion) = graph.RunStreaming(TicketId, ticket, checkpoints, options);await foreach (var chunk in reader.ReadAllAsync()){ if (chunk.Type == StreamChunkType.NodeStart) { Console.WriteLine($"-> {chunk.NodeName}"); } else if (chunk.Type == StreamChunkType.Token) { Console.Write(chunk.Payload); }}
Console.WriteLine();Console.WriteLine(Describe(await completion));
static IEnumerable<string> DraftTokens(string category){ var reply = $"Thanks for writing in. Your ticket is with our {category} team, and they will reply within one business day."; var words = reply.Split(' '); for (var i = 0; i < words.Length; i++) { yield return i == 0 ? words[i] : " " + words[i]; }}
static string Describe(GraphExecutionResult<Ticket> result) => result switch{ GraphExecutionResult<Ticket>.Completed done => $"Completed: category {done.State.Category}, status {done.State.Status}", GraphExecutionResult<Ticket>.Interrupted paused => $"Paused after {paused.SuspendedNode}, before {paused.NextNode}.", GraphExecutionResult<Ticket>.Failed failed => $"Failed: {failed.Message}", _ => result.ToString(),};
public sealed record Ticket( string TicketId, string Subject, string? Category = null, string? Draft = null, string Status = "open");TicketTools.cs:
using Datalium.Strata.Tools;
public partial class TicketTools{ [StrataTool(Name = "classify_ticket", Description = "Classifies a support ticket subject line into a category.")] public static string ClassifyTicket(string subject) { var lowered = subject.ToLowerInvariant(); return lowered.Contains("invoice") || lowered.Contains("bill") ? "billing" : lowered.Contains("crash") || lowered.Contains("error") ? "technical" : "general"; }}Cargo.toml:
[package]name = "ticket-agent"version = "0.1.0"edition = "2024"
[dependencies]chrono = "0.4"datalium-strata = "=0.9.0-preview.2"datalium-strata-memory = "=0.9.0-preview.2"serde = { version = "1", features = ["derive"] }serde_json = "1"tokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }src/main.rs:
use std::io::Write;use std::sync::Arc;use std::time::Duration;
use datalium_strata::checkpoint::{GraphExecutionResult, HumanSignal};use datalium_strata::context::{NodeContext, RunConfig};use datalium_strata::graph::StateGraph;use datalium_strata::history::{ChatMessage, HistoryStore, MessageRole};use datalium_strata::prelude::*;use datalium_strata::store::CheckpointStore;use datalium_strata::streaming::StreamChunkType;use datalium_strata_memory::checkpoint::SqliteCheckpointStore;use datalium_strata_memory::history::SqliteHistoryStore;use serde::{Deserialize, Serialize};
const TICKET_ID: &str = "T-1001";const DB_PATH: &str = "tickets.db";
#[derive(Debug, Clone, Serialize, Deserialize)]struct Ticket { ticket_id: String, subject: String, category: Option<String>, draft: Option<String>, status: String,}
impl Ticket { fn new(ticket_id: &str, subject: &str) -> Self { Ticket { ticket_id: ticket_id.to_string(), subject: subject.to_string(), category: None, draft: None, status: "open".to_string(), } }}
#[derive(Deserialize, StrataSchema)]struct ClassifyArgs { subject: String,}
#[strata_tool( name = "classify_ticket", description = "Classifies a support ticket subject line into a category.")]async fn classify_ticket(args: ClassifyArgs) -> Result<String, StrataError> { let subject = args.subject.to_lowercase(); let category = if subject.contains("invoice") || subject.contains("bill") { "billing" } else if subject.contains("crash") || subject.contains("error") { "technical" } else { "general" }; Ok(category.to_string())}
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let approve = std::env::args().nth(1).as_deref() == Some("approve");
let mut tools = ToolRegistry::new(); tools.register(Box::new(ClassifyTicketTool)); let tools = Arc::new(tools);
let graph = Arc::new( StateGraph::<Ticket>::new() .add_async_node("Classify", move |state: Ticket, ctx: NodeContext| { let tools = tools.clone(); async move { let arguments = serde_json::json!({ "subject": state.subject }).to_string(); let category = tools .dispatch_with("classify_ticket", &arguments, ToolCallContext::from(&ctx)) .await .expect("classify_ticket failed"); Ticket { category: Some(category), ..state } } }) .add_async_node("DraftReply", |state: Ticket, ctx: NodeContext| async move { let mut draft = String::new(); for token in draft_tokens(state.category.as_deref().unwrap_or("general")) { tokio::time::sleep(Duration::from_millis(50)).await; // stands in for a model's latency if let Some(stream) = ctx.stream() { stream.emit_token(&token).await.expect("the stream is open"); } draft.push_str(&token); }
let history = ctx.history().expect("the run has a history store"); let now = chrono::Utc::now(); for (role, content) in [ (MessageRole::User, state.subject.as_str()), (MessageRole::Assistant, draft.as_str()), ] { let message = ChatMessage { role, content: Arc::from(content), timestamp: now, }; history .append(ctx.thread_id(), message) .await .expect("history write failed"); } Ticket { draft: Some(draft), ..state } }) .add_interrupt_boundary("DraftReply") .add_async_node("SendReply", |state: Ticket, ctx: NodeContext| { let reviewer = &ctx .decision() .expect("SendReply runs after an approval") .reviewer; std::future::ready(Ticket { status: format!("sent (approved by {reviewer})"), ..state }) }) .add_edge("Classify", "DraftReply") .add_edge("DraftReply", "SendReply") .compile() .expect("the graph is valid"), );
if !approve { let _ = std::fs::remove_file(DB_PATH); // a new ticket starts from an empty file }
let checkpoints = Arc::new(SqliteCheckpointStore::open(DB_PATH)?); let history = Arc::new(SqliteHistoryStore::open(DB_PATH)?); let config = RunConfig::new().with_history(history.clone());
if approve { let checkpoint = checkpoints .load(TICKET_ID) .await? .expect("the ticket has a checkpoint"); let pending: Ticket = serde_json::from_value(checkpoint.frozen_state)?; println!( "Review {} ({}): {}", pending.ticket_id, pending.category.unwrap_or_default(), pending.draft.unwrap_or_default() );
let signal = HumanSignal::approve("dana@example.com"); let resumed = graph .resume_with(TICKET_ID, signal, checkpoints.clone(), config) .await; println!("{}", describe(&resumed));
for message in history.get_history(TICKET_ID, 50).await? { println!("[{:?}] {}", message.role, message.content); } return Ok(()); }
let ticket = Ticket::new(TICKET_ID, "My invoice total looks wrong this month"); let (handle, mut chunks) = graph.run_streaming_with(TICKET_ID, ticket, checkpoints.clone(), config); while let Some(chunk) = chunks.recv().await { match chunk.chunk_type { StreamChunkType::NodeStart => println!("-> {}", chunk.node_name), StreamChunkType::Token => { print!("{}", chunk.content); std::io::stdout().flush()?; } _ => {} } } println!(); println!("{}", describe(&handle.await?)); Ok(())}
fn draft_tokens(category: &str) -> Vec<String> { let reply = format!( "Thanks for writing in. Your ticket is with our {category} team, and they will reply within one business day." ); reply .split(' ') .enumerate() .map(|(i, word)| { if i == 0 { word.to_string() } else { format!(" {word}") } }) .collect()}
fn describe(result: &GraphExecutionResult<Ticket>) -> String { match result { GraphExecutionResult::Completed(state) => format!( "Completed: category {}, status {}", state.category.as_deref().unwrap_or("-"), state.status ), GraphExecutionResult::Interrupted { suspended_node, next_node, .. } => { format!("Paused after {suspended_node}, before {next_node}.") } GraphExecutionResult::Failed(StrataError::ExecutionAborted(message)) => { format!("Failed: {message}") } GraphExecutionResult::Failed(error) => format!("Failed: {error:?}"), _ => "The run ended early.".to_string(), }}What you learned
Section titled “What you learned”| You built | What it is | Go further |
|---|---|---|
The Ticket state |
The typed data that moves through a graph and is saved in checkpoints. | State |
The classify_ticket tool |
A function with a generated schema, called by name through a ToolRegistry. |
Define tools, Tool middleware |
Classify and DraftReply |
Async nodes, which get a NodeContext with the thread ID, the stream and the history store. |
Graphs, nodes and edges |
| The streamed draft | Token chunks that a node sends to the reader of a streaming run. | Observe runs |
| The conversation | Messages in a history store, kept out of the state. | State, history and long-term memory |
| The pause and the approval | An interrupt boundary, a HumanSignal, and the decision the resume records. |
Human-in-the-loop, Pause for approval |
| The restart | A thread saved in a SQLite file and resumed by another process. | Threads and checkpoints, Choose a store, Use SQLite |
From here, you can:
- Handle a rejection. Give the boundary a reject route, let the reviewer correct the draft with an override, or set a time limit on the approval. Pause for approval shows all three.
- Use a real model. Replace the token generator with a model call, and let the model choose the tools. Follow Build an LLM agent, or see Call a model and Build an agent.
- Run it as a service. The framework’s example runs this agent in the .NET Generic Host. Hosting shows how to register the stores and the graph and configure them from settings.
Before you build something real, read the Known limitations.