0
# Prebuilt Agents & Components
1
2
Ready-to-use agent implementations and tool integration for common AI agent patterns like ReAct, function calling, and tool execution with minimal setup required.
3
4
## Capabilities
5
6
### ReAct Agent
7
8
Implementation of the ReAct (Reasoning and Acting) pattern that combines reasoning and action-taking for complex problem solving.
9
10
```typescript { .api }
11
/**
12
* Create a ReAct agent that reasons and acts iteratively
13
*/
14
function createReactAgent(params: CreateReactAgentParams): CompiledStateGraph;
15
16
interface CreateReactAgentParams {
17
/** Language model for reasoning */
18
llm: BaseLLM;
19
20
/** Available tools for the agent */
21
tools: ToolType[];
22
23
/** Optional state schema (defaults to MessagesAnnotation) */
24
state?: StateSchema;
25
26
/** Optional system message */
27
systemMessage?: string;
28
29
/** Custom prompt template */
30
promptTemplate?: PromptTemplate;
31
32
/** Tool calling mode */
33
toolCallingMode?: "any" | "auto" | "none";
34
35
/** Maximum iterations before stopping */
36
maxIterations?: number;
37
}
38
39
/**
40
* Create annotation for ReAct agents
41
*/
42
function createReactAgentAnnotation(): Annotation<AgentState>;
43
44
interface AgentState {
45
messages: BaseMessage[];
46
isLastStepFinal?: boolean;
47
remainingSteps?: number;
48
}
49
```
50
51
**Usage Example:**
52
53
```typescript
54
import { createReactAgent } from "@langchain/langgraph/prebuilt";
55
import { ChatOpenAI } from "@langchain/openai";
56
import { TavilySearchResults } from "@langchain/community/tools/tavily_search";
57
58
const model = new ChatOpenAI({ model: "gpt-4" });
59
const tools = [new TavilySearchResults({ maxResults: 3 })];
60
61
const agent = createReactAgent({
62
llm: model,
63
tools,
64
systemMessage: "You are a helpful research assistant.",
65
maxIterations: 10
66
});
67
68
const result = await agent.invoke({
69
messages: [{ role: "user", content: "What's the weather in Paris?" }]
70
});
71
```
72
73
### Agent Executor
74
75
General-purpose agent executor that manages tool calling and state transitions for various agent architectures.
76
77
```typescript { .api }
78
/**
79
* Create a general agent executor
80
*/
81
function createAgentExecutor(config: AgentExecutorConfig): CompiledStateGraph;
82
83
interface AgentExecutorConfig {
84
/** Agent runnable for decision making */
85
agentRunnable: Runnable;
86
87
/** Available tools */
88
tools: ToolType[];
89
90
/** State schema */
91
state?: StateSchema;
92
93
/** Maximum execution steps */
94
maxExecutionTime?: number;
95
96
/** Maximum iterations */
97
maxIterations?: number;
98
99
/** Early stopping method */
100
earlyStoppingMethod?: "force" | "generate";
101
}
102
103
interface AgentExecutorState {
104
input: string;
105
chatHistory?: BaseMessage[];
106
agentOutcome?: AgentAction | AgentFinish;
107
intermediateSteps: Array<[AgentAction, string]>;
108
}
109
```
110
111
### Function Calling Executor
112
113
Specialized executor for function-calling language models with structured tool integration.
114
115
```typescript { .api }
116
/**
117
* Create a function calling executor for structured tool use
118
*/
119
function createFunctionCallingExecutor(
120
params: FunctionCallingExecutorParams
121
): CompiledStateGraph;
122
123
interface FunctionCallingExecutorParams {
124
/** Function-calling capable model */
125
model: BaseLLM;
126
127
/** Tools to make available */
128
tools: ToolType[];
129
130
/** Optional system message */
131
systemMessage?: string;
132
}
133
134
interface FunctionCallingExecutorState {
135
messages: BaseMessage[];
136
toolCalls?: ToolCall[];
137
toolResults?: ToolResult[];
138
}
139
```
140
141
**Usage Example:**
142
143
```typescript
144
import { createFunctionCallingExecutor } from "@langchain/langgraph/prebuilt";
145
import { ChatOpenAI } from "@langchain/openai";
146
147
const executor = createFunctionCallingExecutor({
148
model: new ChatOpenAI({ model: "gpt-3.5-turbo" }),
149
tools: [weatherTool, calculatorTool],
150
systemMessage: "You are a helpful assistant with access to tools."
151
});
152
153
const result = await executor.invoke({
154
messages: [
155
{ role: "user", content: "What's 15 * 23 and what's the weather like?" }
156
]
157
});
158
```
159
160
## Tool Integration
161
162
### Tool Node
163
164
Specialized graph node for executing tools with proper error handling and result formatting.
165
166
```typescript { .api }
167
/**
168
* Graph node that executes tools based on tool calls
169
*/
170
class ToolNode {
171
constructor(tools: ToolType[], options?: ToolNodeOptions);
172
173
/** Execute tools from tool calls in messages */
174
invoke(
175
state: { messages: BaseMessage[] },
176
config?: RunnableConfig
177
): Promise<{ messages: BaseMessage[] }>;
178
}
179
180
interface ToolNodeOptions {
181
/** Custom name for the node */
182
name?: string;
183
184
/** Tags for the node */
185
tags?: string[];
186
187
/** Handle tool errors gracefully */
188
handleToolErrors?: boolean;
189
190
/** Custom error message format */
191
errorMessageFormat?: (error: Error, toolCall: ToolCall) => string;
192
}
193
```
194
195
### Tool Executor
196
197
Low-level tool execution utility with flexible invocation patterns.
198
199
```typescript { .api }
200
/**
201
* Utility for executing individual tools
202
*/
203
class ToolExecutor {
204
constructor(tools: ToolType[]);
205
206
/** Execute a tool by name with arguments */
207
invoke(args: ToolExecutorArgs): Promise<string>;
208
209
/** Batch execute multiple tools */
210
batch(argsList: ToolExecutorArgs[]): Promise<string[]>;
211
}
212
213
interface ToolExecutorArgs {
214
tool: string;
215
toolInput: any;
216
}
217
218
/**
219
* Interface for tool invocation
220
*/
221
interface ToolInvocationInterface {
222
tool: string;
223
toolInput: any;
224
toolCallId?: string;
225
}
226
```
227
228
**Usage Example:**
229
230
```typescript
231
import { ToolNode, ToolExecutor } from "@langchain/langgraph/prebuilt";
232
233
// Using ToolNode in a graph
234
const toolNode = new ToolNode([searchTool, calculatorTool], {
235
handleToolErrors: true,
236
errorMessageFormat: (error, toolCall) =>
237
`Error executing ${toolCall.name}: ${error.message}`
238
});
239
240
const graph = new StateGraph(MessagesAnnotation)
241
.addNode("agent", agentNode)
242
.addNode("tools", toolNode)
243
.addConditionalEdges("agent", shouldUseTools, {
244
tools: "tools",
245
end: END
246
})
247
.addEdge("tools", "agent");
248
249
// Using ToolExecutor directly
250
const executor = new ToolExecutor([calculatorTool]);
251
const result = await executor.invoke({
252
tool: "calculator",
253
toolInput: { expression: "15 * 23" }
254
});
255
```
256
257
### Tool Conditions
258
259
Conditional logic for routing between tool execution and completion based on agent decisions.
260
261
```typescript { .api }
262
/**
263
* Condition function for tool routing
264
*/
265
function toolsCondition(
266
state: { messages: BaseMessage[] }
267
): "tools" | "__end__";
268
269
/**
270
* Enhanced tool condition with custom routing
271
*/
272
function createToolsCondition(options: {
273
toolsNode?: string;
274
endNode?: string;
275
}): (state: { messages: BaseMessage[] }) => string;
276
```
277
278
**Usage Example:**
279
280
```typescript
281
import { toolsCondition } from "@langchain/langgraph/prebuilt";
282
283
const graph = new StateGraph(MessagesAnnotation)
284
.addNode("agent", agentNode)
285
.addNode("tools", toolNode)
286
.addConditionalEdges("agent", toolsCondition)
287
.addEdge("tools", "agent")
288
.compile();
289
```
290
291
## Message Handling
292
293
### Messages Annotation
294
295
Pre-configured state annotation optimized for message-based agent workflows.
296
297
```typescript { .api }
298
/**
299
* Pre-defined annotation for message-based agents
300
*/
301
const MessagesAnnotation: Annotation<MessagesState>;
302
303
interface MessagesState {
304
messages: BaseMessage[];
305
}
306
307
/**
308
* Zod schema for messages state
309
*/
310
const MessagesZodState: ZodType<MessagesState>;
311
312
/**
313
* Messages metadata for Zod integration
314
*/
315
const MessagesZodMeta: ZodMeta;
316
```
317
318
### Message Reducers
319
320
State reducers specifically designed for managing message collections in conversational agents.
321
322
```typescript { .api }
323
/**
324
* Reducer that appends new messages to existing ones
325
*/
326
function messagesStateReducer(
327
current: BaseMessage[],
328
update: BaseMessage[]
329
): BaseMessage[];
330
331
/**
332
* Alias for messagesStateReducer
333
*/
334
const addMessages: typeof messagesStateReducer;
335
336
/**
337
* Special constant to clear all messages
338
*/
339
const REMOVE_ALL_MESSAGES: symbol;
340
```
341
342
**Usage Example:**
343
344
```typescript
345
import { MessagesAnnotation, addMessages, REMOVE_ALL_MESSAGES } from "@langchain/langgraph";
346
347
const ChatState = Annotation.Root({
348
messages: Annotation<BaseMessage[]>({
349
reducer: addMessages,
350
default: () => []
351
}),
352
context: Annotation<Record<string, any>>({
353
reducer: (current, update) => ({ ...current, ...update }),
354
default: () => ({})
355
})
356
});
357
358
// Clear messages
359
const clearedState = {
360
messages: [REMOVE_ALL_MESSAGES]
361
};
362
```
363
364
### Typed Nodes
365
366
Utility for creating type-safe nodes that work with specific message formats.
367
368
```typescript { .api }
369
/**
370
* Create a typed node for message processing
371
*/
372
function typedNode<T>(
373
func: (input: T) => T | Promise<T>
374
): (input: T) => Promise<T>;
375
```
376
377
## Human-in-the-Loop Components
378
379
### Human Interrupt Configuration
380
381
Configuration for human interaction points in agent workflows.
382
383
```typescript { .api }
384
/**
385
* Configuration for human interrupts
386
*/
387
interface HumanInterruptConfig {
388
/** Message to display to human */
389
message?: string;
390
391
/** Required approval type */
392
approvalType?: "simple" | "detailed" | "custom";
393
394
/** Timeout for human response */
395
timeout?: number;
396
397
/** Default action if timeout occurs */
398
defaultAction?: "approve" | "reject" | "retry";
399
}
400
401
/**
402
* Human action request structure
403
*/
404
interface ActionRequest {
405
type: "approval" | "input" | "choice";
406
prompt: string;
407
options?: string[];
408
required?: boolean;
409
}
410
411
/**
412
* Human response to action request
413
*/
414
interface HumanResponse {
415
approved?: boolean;
416
input?: string;
417
choice?: string;
418
metadata?: Record<string, any>;
419
}
420
421
/**
422
* Human interrupt data
423
*/
424
interface HumanInterrupt {
425
request: ActionRequest;
426
response?: HumanResponse;
427
timestamp: string;
428
userId?: string;
429
}
430
```
431
432
## Agent Utilities
433
434
### Agent Naming
435
436
Utilities for managing agent names and identities in multi-agent systems.
437
438
```typescript { .api }
439
/**
440
* Add agent name context to workflow
441
*/
442
function withAgentName<T>(
443
name: string,
444
mode: AgentNameMode = "append"
445
): (input: T) => T;
446
447
type AgentNameMode = "append" | "prepend" | "replace";
448
```
449
450
**Usage Example:**
451
452
```typescript
453
import { withAgentName } from "@langchain/langgraph/prebuilt";
454
455
const namedAgent = withAgentName("SearchAgent", "prepend");
456
457
const graph = new StateGraph(MessagesAnnotation)
458
.addNode("agent", namedAgent(agentNode))
459
.compile();
460
```
461
462
## Advanced Agent Patterns
463
464
### Multi-Agent Coordination
465
466
```typescript
467
// Create multiple specialized agents
468
const researchAgent = createReactAgent({
469
llm: model,
470
tools: [searchTool, wikipediaTool],
471
systemMessage: "You are a research specialist."
472
});
473
474
const analysisAgent = createReactAgent({
475
llm: model,
476
tools: [calculatorTool, chartTool],
477
systemMessage: "You are a data analysis specialist."
478
});
479
480
// Coordinate them in a workflow
481
const coordinator = new StateGraph(MessagesAnnotation)
482
.addNode("research", researchAgent)
483
.addNode("analysis", analysisAgent)
484
.addNode("router", routerNode)
485
.addEdge(START, "router")
486
.addConditionalEdges("router", routeToAgent)
487
.compile();
488
```
489
490
### Custom Agent State
491
492
```typescript
493
// Define custom agent state
494
const CustomAgentState = Annotation.Root({
495
messages: Annotation<BaseMessage[]>({
496
reducer: addMessages,
497
default: () => []
498
}),
499
task_status: Annotation<string>({
500
reducer: (_, new_status) => new_status,
501
default: () => "pending"
502
}),
503
artifacts: Annotation<Record<string, any>>({
504
reducer: (current, update) => ({ ...current, ...update }),
505
default: () => ({})
506
})
507
});
508
509
const customAgent = createReactAgent({
510
llm: model,
511
tools,
512
state: CustomAgentState
513
});
514
```