0
# Graph Construction
1
2
Core graph building functionality for creating stateful workflows with typed state management, node orchestration, and conditional routing.
3
4
## Capabilities
5
6
### StateGraph
7
8
Primary graph class for building workflows with typed state management and automatic state propagation between nodes.
9
10
```typescript { .api }
11
/**
12
* Creates a stateful workflow graph with typed state management
13
* @param stateSchema - State definition using Annotation
14
*/
15
class StateGraph<SD extends StateDefinition> {
16
constructor(stateSchema: SD);
17
18
/** Add a processing node to the graph */
19
addNode(key: string, action: NodeType<SD>): StateGraph<SD>;
20
21
/** Add a direct edge between two nodes */
22
addEdge(start: string, end: string): StateGraph<SD>;
23
24
/** Add conditional routing based on state */
25
addConditionalEdges(
26
source: string,
27
path: (state: StateType<SD>) => string | string[],
28
pathMap?: Record<string, string>
29
): StateGraph<SD>;
30
31
/** Set the entry point for the graph */
32
setEntryPoint(key: string): StateGraph<SD>;
33
34
/** Set the finish point for the graph */
35
setFinishPoint(key: string): StateGraph<SD>;
36
37
/** Compile the graph into an executable form */
38
compile(options?: PregelOptions): CompiledStateGraph;
39
}
40
41
interface PregelOptions {
42
checkpointer?: BaseCheckpointSaver;
43
interruptBefore?: string[];
44
interruptAfter?: string[];
45
debug?: boolean;
46
}
47
```
48
49
**Usage Example:**
50
51
```typescript
52
import { StateGraph, Annotation, START, END } from "@langchain/langgraph";
53
54
// Define state structure
55
const WorkflowState = Annotation.Root({
56
input: Annotation<string>(),
57
result: Annotation<string>(),
58
step: Annotation<number>({
59
reducer: (x: number, y: number) => y, // Replace with new value
60
default: () => 0,
61
}),
62
});
63
64
// Create nodes
65
async function processInput(state: typeof WorkflowState.State) {
66
return {
67
result: `Processed: ${state.input}`,
68
step: state.step + 1,
69
};
70
}
71
72
async function finalizeOutput(state: typeof WorkflowState.State) {
73
return {
74
result: `${state.result} - Finalized`,
75
step: state.step + 1,
76
};
77
}
78
79
// Build graph
80
const graph = new StateGraph(WorkflowState)
81
.addNode("process", processInput)
82
.addNode("finalize", finalizeOutput)
83
.addEdge(START, "process")
84
.addEdge("process", "finalize")
85
.addEdge("finalize", END)
86
.compile();
87
```
88
89
### Graph
90
91
Basic graph builder without built-in state management, providing maximum flexibility for custom state handling.
92
93
```typescript { .api }
94
/**
95
* Creates a basic workflow graph without automatic state management
96
*/
97
class Graph {
98
constructor();
99
100
/** Add a processing node to the graph */
101
addNode(key: string, action: NodeType): Graph;
102
103
/** Add a direct edge between two nodes */
104
addEdge(start: string, end: string): Graph;
105
106
/** Add conditional routing logic */
107
addConditionalEdges(
108
source: string,
109
path: (input: any) => string | string[],
110
pathMap?: Record<string, string>
111
): Graph;
112
113
/** Compile the graph into an executable form */
114
compile(options?: PregelOptions): CompiledGraph;
115
}
116
```
117
118
### MessageGraph
119
120
Specialized graph for message-based workflows, optimized for conversational AI and message processing patterns.
121
122
```typescript { .api }
123
/**
124
* Creates a message-oriented workflow graph
125
*/
126
class MessageGraph {
127
constructor();
128
129
/** Add a message processing node */
130
addNode(key: string, action: (messages: Messages) => Messages): MessageGraph;
131
132
/** Add edge between message nodes */
133
addEdge(start: string, end: string): MessageGraph;
134
135
/** Add conditional message routing */
136
addConditionalEdges(
137
source: string,
138
path: (messages: Messages) => string | string[],
139
pathMap?: Record<string, string>
140
): MessageGraph;
141
142
/** Compile the message graph */
143
compile(options?: PregelOptions): CompiledGraph;
144
}
145
146
type Messages = Array<{
147
role: string;
148
content: string;
149
[key: string]: any;
150
}>;
151
```
152
153
### State Definition & Annotation
154
155
System for defining typed state schemas with reducers and default values for graph state management.
156
157
```typescript { .api }
158
/**
159
* Helper class for defining state schemas
160
*/
161
class Annotation {
162
/** Create a root state annotation */
163
static Root<T extends StateDefinition>(fields: T): AnnotationRoot<T>;
164
165
/** Create a field annotation */
166
static <T>(options?: {
167
reducer?: SingleReducer<T, any>;
168
default?: () => T;
169
}): Annotation<T>;
170
}
171
172
interface AnnotationRoot<SD extends StateDefinition> {
173
State: StateType<SD>;
174
Update: UpdateType<SD>;
175
}
176
177
type StateDefinition = Record<string, any>;
178
179
type SingleReducer<ValueType, UpdateType = ValueType> = (
180
left: ValueType,
181
right: UpdateType
182
) => ValueType;
183
```
184
185
**Usage Example:**
186
187
```typescript
188
// Define complex state with reducers
189
const ChatState = Annotation.Root({
190
messages: Annotation<string[]>({
191
reducer: (x: string[], y: string[]) => x.concat(y),
192
default: () => [],
193
}),
194
context: Annotation<Record<string, any>>({
195
reducer: (x, y) => ({ ...x, ...y }),
196
default: () => ({}),
197
}),
198
user_id: Annotation<string>(),
199
});
200
201
type ChatStateType = typeof ChatState.State;
202
// Results in: { messages: string[], context: Record<string, any>, user_id: string }
203
```
204
205
### Compiled Graphs
206
207
Runtime representations of compiled graphs that can be executed with various configuration options.
208
209
```typescript { .api }
210
/**
211
* Compiled version of StateGraph ready for execution
212
*/
213
class CompiledStateGraph extends Pregel {
214
/** Execute the graph with given input */
215
invoke(
216
input: StateType<any>,
217
config?: LangGraphRunnableConfig
218
): Promise<StateType<any>>;
219
220
/** Stream execution results */
221
stream(
222
input: StateType<any>,
223
config?: LangGraphRunnableConfig
224
): AsyncIterableIterator<StateType<any>>;
225
226
/** Get current state snapshot */
227
getState(config: LangGraphRunnableConfig): Promise<StateSnapshot>;
228
229
/** Update state at current checkpoint */
230
updateState(
231
config: LangGraphRunnableConfig,
232
values: UpdateType<any>
233
): Promise<void>;
234
}
235
236
/**
237
* Compiled version of basic Graph
238
*/
239
class CompiledGraph extends Pregel {
240
invoke(input: any, config?: LangGraphRunnableConfig): Promise<any>;
241
stream(input: any, config?: LangGraphRunnableConfig): AsyncIterableIterator<any>;
242
}
243
```
244
245
## Node Types
246
247
```typescript { .api }
248
/** Node function for StateGraph */
249
type NodeType<SD> = (
250
state: StateType<SD>,
251
config?: LangGraphRunnableConfig
252
) => Promise<UpdateType<SD>> | UpdateType<SD>;
253
254
/** State type derived from state definition */
255
type StateType<SD> = {
256
[K in keyof SD]: SD[K] extends Annotation<infer T> ? T : never;
257
};
258
259
/** Update type for partial state updates */
260
type UpdateType<SD> = Partial<StateType<SD>>;
261
```
262
263
## Advanced Graph Features
264
265
### Conditional Routing
266
267
```typescript
268
// Route based on state content
269
const routeByContent = (state: typeof MyState.State) => {
270
if (state.needsApproval) return "approval";
271
if (state.hasErrors) return "error_handler";
272
return "continue";
273
};
274
275
graph.addConditionalEdges("process", routeByContent, {
276
approval: "human_review",
277
error_handler: "fix_errors",
278
continue: "finalize",
279
});
280
```
281
282
### Multiple Entry/Exit Points
283
284
```typescript
285
// Multiple entry points
286
graph
287
.addEdge(START, "router")
288
.addConditionalEdges("router", routeToProcessor)
289
.addEdge("processor_a", END)
290
.addEdge("processor_b", END);
291
```