StateGraph
Builder for a graph of nodes and edges over an immutable State.
val graph = StateGraph<AgentState> {
node("research") { state -> state.copy(notes = search(state.question)) }
node("write") { state -> state.copy(answer = draft(state.notes)) }
edge(START, "research")
conditionalEdge("research", targets = setOf("write", END)) { state ->
if (state.notes.isEmpty()) END else "write"
}
edge("write", END)
}.compile()Execution starts at START and ends when every active branch reaches END. A node with no outgoing edge routes to END.
node returns a NodeRef. Using the references with then and conditionalEdge instead of repeating node names lets the compiler catch typos:
val graph = StateGraph<AgentState> {
val research = node("research") { ... }
val write = node("write") { ... }
START then research
conditionalEdge(research, targets = setOf(write, NodeRef.END)) { state ->
if (state.notes.isEmpty()) NodeRef.END else write
}
write then END
}.compile()Functions
Validates the graph and returns an executable CompiledGraph.
Adds a conditional edge that works with references instead of names: condition returns one of targets, so a misspelled node is a compiler error.
Adds a conditional edge from the node referenced by from. See the overload taking a node name.
Adds a conditional edge that works with references, from the node named from, usually START. See the overload taking a node reference.
Adds a conditional edge that can fan out: after from finishes, condition picks any of targets, and they run in parallel in the next step, like the targets of static edges from one node. See compile for when that needs a Reducer.
Adds a node whose job is split in two, so that it can run next to other nodes without a Reducer. work does the slow part, such as a call to a model or a service, and returns a result. update writes that result into the state.
Adds a node that is tried again when it fails, that has a time limit, or both.
Adds a node with a work and an update that is tried again when it fails, that has a time limit, or both. See the overload of a node that returns a whole state for what retry and timeout do.
Adds a node that runs its work once for each item of a list, all at the same time, when the number of items is only known at run time: summarize every document a search found, or ask a model about each line of an order. forEach reads the list from the state, and update writes the results into the state, in the order of the items.
Adds a node that runs another graph with the same state type, a subgraph. It receives the state of this graph and its result is the next state, like a node that returns a whole state.
Adds a node that runs another graph, a subgraph, on a state of its own type.