0
# Graph Construction
1
2
Core functionality for building and managing stateful workflow graphs. Supports nodes, edges, conditional routing, and subgraph composition.
3
4
## Capabilities
5
6
### StateGraph Creation
7
8
Create and configure state graphs with custom state types and serialization.
9
10
```java { .api }
11
/**
12
* Creates a new StateGraph with the specified state factory
13
* @param stateFactory Factory for creating agent states
14
*/
15
StateGraph<State> StateGraph(AgentStateFactory<State> stateFactory);
16
17
/**
18
* Creates a new StateGraph with channels and state serializer
19
* @param channels State schema defining how state values are updated
20
* @param stateSerializer Serializer for state objects
21
*/
22
StateGraph<State> StateGraph(Map<String, Channel<?>> channels, StateSerializer<State> stateSerializer);
23
24
/**
25
* Creates a new StateGraph with channels and state factory
26
* @param channels State schema defining how state values are updated
27
* @param stateFactory Factory for creating agent states
28
*/
29
StateGraph<State> StateGraph(Map<String, Channel<?>> channels, AgentStateFactory<State> stateFactory);
30
```
31
32
**Usage Example:**
33
34
```java
35
import org.bsc.langgraph4j.StateGraph;
36
import org.bsc.langgraph4j.state.AgentState;
37
38
// Simple state class
39
class MyState extends AgentState {
40
public MyState(Map<String, Object> initData) {
41
super(initData);
42
}
43
}
44
45
// Create state graph with factory
46
StateGraph<MyState> workflow = new StateGraph<>(MyState::new);
47
48
// Or with channels for complex state management
49
Map<String, Channel<?>> channels = Map.of(
50
"messages", Channels.appender(ArrayList::new)
51
);
52
StateGraph<MyState> workflowWithChannels = new StateGraph<>(channels, MyState::new);
53
```
54
55
### Node Addition
56
57
Add nodes with various action types and behaviors.
58
59
```java { .api }
60
/**
61
* Adds a node with an asynchronous action
62
* @param id Unique identifier for the node
63
* @param action Asynchronous action to execute
64
* @return This StateGraph for method chaining
65
* @throws GraphStateException if node ID is invalid or already exists
66
*/
67
StateGraph<State> addNode(String id, AsyncNodeAction<State> action);
68
69
/**
70
* Adds a node with a configuration-aware asynchronous action
71
* @param id Unique identifier for the node
72
* @param action Configuration-aware asynchronous action
73
* @return This StateGraph for method chaining
74
* @throws GraphStateException if node ID is invalid or already exists
75
*/
76
StateGraph<State> addNode(String id, AsyncNodeActionWithConfig<State> action);
77
78
/**
79
* Adds a node that behaves as conditional edges
80
* @param id Unique identifier for the node
81
* @param action Command action to determine next target node
82
* @param mappings Mappings of command results to target nodes
83
* @return This StateGraph for method chaining
84
* @throws GraphStateException if mappings are empty or node already exists
85
*/
86
StateGraph<State> addNode(String id, AsyncCommandAction<State> action, Map<String, String> mappings);
87
88
/**
89
* Adds a compiled subgraph as a node
90
* @param id Unique identifier for the subgraph node
91
* @param subGraph Compiled subgraph to execute
92
* @return This StateGraph for method chaining
93
* @throws GraphStateException if node ID is invalid or already exists
94
*/
95
StateGraph<State> addNode(String id, CompiledGraph<State> subGraph);
96
97
/**
98
* Adds a state graph as a node (compiled during parent compilation)
99
* @param id Unique identifier for the subgraph node
100
* @param subGraph State graph to include as subgraph
101
* @return This StateGraph for method chaining
102
* @throws GraphStateException if node ID is invalid or already exists
103
*/
104
StateGraph<State> addNode(String id, StateGraph<State> subGraph);
105
```
106
107
**Usage Examples:**
108
109
```java
110
// Simple async node
111
workflow.addNode("processor", (state) ->
112
CompletableFuture.completedFuture(Map.of("processed", true))
113
);
114
115
// Configuration-aware node
116
workflow.addNode("configurable", (state, config) -> {
117
String threadId = config.threadId().orElse("default");
118
return CompletableFuture.completedFuture(Map.of("thread", threadId));
119
});
120
121
// Conditional node with routing
122
workflow.addNode("router",
123
(state, config) -> {
124
boolean condition = state.value("ready").orElse(false);
125
return CompletableFuture.completedFuture(
126
new Command(condition ? "success" : "failure", Map.of())
127
);
128
},
129
Map.of(
130
"success", "success_node",
131
"failure", "failure_node"
132
)
133
);
134
135
// Subgraph node
136
StateGraph<MyState> subWorkflow = new StateGraph<>(MyState::new);
137
// ... configure subWorkflow ...
138
workflow.addNode("sub_process", subWorkflow);
139
```
140
141
### Edge Management
142
143
Define routing between nodes with simple and conditional edges.
144
145
```java { .api }
146
/**
147
* Adds a simple edge between two nodes
148
* @param sourceId Source node identifier
149
* @param targetId Target node identifier
150
* @return This StateGraph for method chaining
151
* @throws GraphStateException if source ID is invalid or edge conflicts
152
*/
153
StateGraph<State> addEdge(String sourceId, String targetId);
154
155
/**
156
* Adds conditional edges based on command action results
157
* @param sourceId Source node identifier
158
* @param condition Command action to determine routing
159
* @param mappings Map of command results to target node IDs
160
* @return This StateGraph for method chaining
161
* @throws GraphStateException if mappings are empty or edge conflicts
162
*/
163
StateGraph<State> addConditionalEdges(String sourceId, AsyncCommandAction<State> condition, Map<String, String> mappings);
164
165
/**
166
* Adds conditional edges using edge action (alternative form)
167
* @param sourceId Source node identifier
168
* @param condition Edge action returning target node ID
169
* @param mappings Map of edge results to target node IDs
170
* @return This StateGraph for method chaining
171
* @throws GraphStateException if mappings are empty or edge conflicts
172
*/
173
StateGraph<State> addConditionalEdges(String sourceId, AsyncEdgeAction<State> condition, Map<String, String> mappings);
174
```
175
176
**Usage Examples:**
177
178
```java
179
// Simple sequential edges
180
workflow.addEdge(StateGraph.START, "first_node");
181
workflow.addEdge("first_node", "second_node");
182
workflow.addEdge("second_node", StateGraph.END);
183
184
// Conditional routing
185
workflow.addConditionalEdges("decision_node",
186
(state, config) -> {
187
int value = state.<Integer>value("score").orElse(0);
188
String route = value > 50 ? "high" : "low";
189
return CompletableFuture.completedFuture(new Command(route, Map.of()));
190
},
191
Map.of(
192
"high", "high_score_handler",
193
"low", "low_score_handler"
194
)
195
);
196
```
197
198
### Graph Compilation
199
200
Compile the state graph into an executable form with optional configuration.
201
202
```java { .api }
203
/**
204
* Compiles the state graph into a compiled graph with default configuration
205
* @return Compiled graph ready for execution
206
* @throws GraphStateException if graph validation fails
207
*/
208
CompiledGraph<State> compile();
209
210
/**
211
* Compiles the state graph with specific configuration
212
* @param config Compilation configuration
213
* @return Compiled graph ready for execution
214
* @throws GraphStateException if graph validation fails
215
*/
216
CompiledGraph<State> compile(CompileConfig config);
217
```
218
219
**Usage Examples:**
220
221
```java
222
// Basic compilation
223
CompiledGraph<MyState> app = workflow.compile();
224
225
// Compilation with configuration
226
CompileConfig config = CompileConfig.builder()
227
.checkpointSaver(new MemorySaver())
228
.interruptBefore("human_review")
229
.build();
230
231
CompiledGraph<MyState> app = workflow.compile(config);
232
```
233
234
### Graph Visualization
235
236
Generate diagram representations of the graph structure.
237
238
```java { .api }
239
/**
240
* Generates a graph representation with specified type and title
241
* @param type Diagram format (PLANTUML or MERMAID)
242
* @param title Title for the diagram
243
* @return Graph representation containing diagram code
244
*/
245
GraphRepresentation getGraph(GraphRepresentation.Type type, String title);
246
247
/**
248
* Generates a graph representation with conditional edge control
249
* @param type Diagram format
250
* @param title Title for the diagram
251
* @param printConditionalEdges Whether to include conditional edges in diagram
252
* @return Graph representation containing diagram code
253
*/
254
GraphRepresentation getGraph(GraphRepresentation.Type type, String title, boolean printConditionalEdges);
255
```
256
257
**Usage Examples:**
258
259
```java
260
// Generate PlantUML diagram
261
GraphRepresentation diagram = workflow.getGraph(
262
GraphRepresentation.Type.PLANTUML,
263
"My Workflow"
264
);
265
System.out.println(diagram.content());
266
267
// Generate Mermaid diagram without conditional edges
268
GraphRepresentation mermaid = workflow.getGraph(
269
GraphRepresentation.Type.MERMAID,
270
"Simplified View",
271
false
272
);
273
```
274
275
## Constants
276
277
```java { .api }
278
// Built-in node identifiers
279
static final String START = "__START__"; // Entry point identifier
280
static final String END = "__END__"; // Exit point identifier
281
```
282
283
## Graph Validation
284
285
Graph validation occurs during compilation and checks for:
286
287
- Valid entry point (START node with outgoing edge)
288
- All referenced nodes exist
289
- No duplicate node IDs
290
- Valid edge mappings for conditional edges
291
- Proper subgraph configuration
292
- Interrupt node existence
293
294
**Common Validation Errors:**
295
296
- `missingEntryPoint`: No edge from START node
297
- `duplicateNodeError`: Node ID already exists
298
- `invalidNodeIdentifier`: Using reserved END as node ID
299
- `missingNodeReferencedByEdge`: Edge references non-existent node
300
- `edgeMappingIsEmpty`: Conditional edge has no mappings