StateGraph<TState>

Models & Types · AiDotNet.Agentic.Graph

A builder for a typed state graph: register nodes (state transformers), wire them with fixed or conditional edges (cycles allowed), set an entry point, then Compile into an executable CompiledStateGraph.

For Beginners

Think of building a flowchart. AddNode adds a box that does some work on your data; AddEdge draws an arrow to the next box; AddConditionalEdges draws arrows that depend on the data; SetEntryPoint marks where to start. Arrows can loop back to create cycles. Compile turns the flowchart into something you can run.

How It Works

This is the AiDotNet counterpart to LangGraph’s StateGraph, but fully typed: there are no stringly-typed state dictionaries — TState is your own type, checked by the compiler. Routing is explicit: a node has at most one fixed edge or one conditional router; reaching End finishes the run.

Example:

Constructors

Constructor Summary
StateGraph()

Methods

Method Summary
CompiledStateGraph<TState> Compile() Validates the graph and produces an executable CompiledStateGraph.
StateGraph<TState> AddConditionalEdges(string from, Func<TState, string> router) Adds conditional edges: after from runs, the router inspects the state and returns the next node name (or End).
StateGraph<TState> AddEdge(string from, string to) Adds a fixed edge: after from runs, flow always moves to to.
StateGraph<TState> AddFanOutNode(string name, Func<TState, IEnumerable<TItem>> map, Func<TItem, CancellationToken, Task<TResult>> branch, Func<TState, IReadOnlyList<TResult>, TState> reduce, int? maxDegreeOfParallelism) Adds a dynamic fan-out (map-reduce) node: it derives a set of items from the current state, runs a branch over each item in parallel, then reduces the branch results back into the state.
StateGraph<TState> AddInterruptBefore(string name) Marks a node as a human-in-the-loop interrupt point: a run pauses just before this node so a human can review (and optionally edit) the state, then resume.
StateGraph<TState> AddNode(string name, Func<TState, CancellationToken, Task<TState>> node) Adds a synchronous node that transforms the state.
StateGraph<TState> AddNode(string name, Func<TState, TState> node) Adds a synchronous node that transforms the state.
StateGraph<TState> AddRewardGatedEdges(string from, Func<TState, double> reward, double threshold, string ifMeetsThreshold, string ifBelowThreshold) Adds reward-gated routing after a node: a scoring function rates the state, and flow goes to ifMeetsThreshold when the score is at least threshold, else to ifBelowThreshold.
StateGraph<TState> AddSubgraph(string name, CompiledStateGraph<TState> subgraph) Adds a node that runs an entire compiled graph as a single step (a subgraph), threading the same state in and out.
StateGraph<TState> SetEntryPoint(string name) Sets the node where execution begins.

Fields

Field Summary
string End The terminal node name; route here to finish the run.