0
# Tools System
1
2
Tool definition and execution framework for function calling and external integrations. Tools enable language models to interact with external systems, APIs, and perform computations.
3
4
## Capabilities
5
6
### Structured Tool
7
8
Base class for tools with structured input validation using schemas.
9
10
```typescript { .api }
11
/**
12
* Base class for tools with structured input validation
13
* @template SchemaT - Input schema type (Zod or JSON schema)
14
* @template SchemaOutputT - Schema output type (inferred)
15
* @template SchemaInputT - Schema input type (inferred)
16
* @template ToolOutputT - Tool execution output type
17
*/
18
abstract class StructuredTool<
19
SchemaT = z.ZodSchema,
20
SchemaOutputT = z.output<SchemaT>,
21
SchemaInputT = z.input<SchemaT>,
22
ToolOutputT = unknown
23
> extends Runnable<SchemaInputT, ToolOutputT> {
24
/** Tool name for identification */
25
name: string;
26
/** Human-readable description of tool functionality */
27
description: string;
28
/** Input validation schema (Zod or JSON schema) */
29
schema: SchemaT;
30
/** Whether tool output should be returned directly to user */
31
returnDirect: boolean;
32
/** Output format specification */
33
responseFormat?: ResponseFormat;
34
/** Whether to show detailed parsing error messages */
35
verboseParsingErrors: boolean;
36
37
constructor(fields: StructuredToolParams<SchemaT, ToolOutputT>);
38
39
/** Abstract method to implement tool functionality */
40
abstract _call(arg: SchemaOutputT, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolOutputT>;
41
42
/** Main execution method with input validation */
43
async invoke(input: SchemaInputT, config?: RunnableConfig): Promise<ToolReturnType>;
44
45
/** Legacy call method (deprecated) */
46
async call(arg: SchemaInputT, config?: RunnableConfig, tags?: string[]): Promise<ToolReturnType>;
47
}
48
```
49
50
**Usage Examples:**
51
52
```typescript
53
import { StructuredTool } from "@langchain/core/tools";
54
import { z } from "zod";
55
56
// Define a calculator tool
57
class CalculatorTool extends StructuredTool {
58
name = "calculator";
59
description = "Perform basic arithmetic operations";
60
61
schema = z.object({
62
operation: z.enum(["add", "subtract", "multiply", "divide"]),
63
a: z.number().describe("First number"),
64
b: z.number().describe("Second number")
65
});
66
67
async _call({ operation, a, b }: z.infer<typeof this.schema>): Promise<number> {
68
switch (operation) {
69
case "add": return a + b;
70
case "subtract": return a - b;
71
case "multiply": return a * b;
72
case "divide":
73
if (b === 0) throw new Error("Division by zero");
74
return a / b;
75
}
76
}
77
}
78
79
// Use the tool
80
const calculator = new CalculatorTool();
81
const result = await calculator.invoke({
82
operation: "add",
83
a: 5,
84
b: 3
85
}); // Returns 8
86
```
87
88
### Tool
89
90
Simplified tool class for string-based input.
91
92
```typescript { .api }
93
/**
94
* Tool with string input (extends StructuredTool)
95
* @template ToolOutputT - Tool output type
96
*/
97
abstract class Tool<ToolOutputT = string> extends StructuredTool<z.ZodString, string, string, ToolOutputT> {
98
/** Pre-defined string schema */
99
schema: z.ZodString;
100
101
constructor(fields: ToolParams<ToolOutputT>);
102
103
/** Call tool with string input */
104
abstract _call(arg: string, runManager?: CallbackManagerForToolRun, parentConfig?: RunnableConfig): Promise<ToolOutputT>;
105
}
106
```
107
108
**Usage Examples:**
109
110
```typescript
111
import { Tool } from "@langchain/core/tools";
112
113
// Simple string-based tool
114
class EchoTool extends Tool {
115
name = "echo";
116
description = "Echo back the input text";
117
118
async _call(input: string): Promise<string> {
119
return `Echo: ${input}`;
120
}
121
}
122
123
const echo = new EchoTool();
124
const result = await echo.invoke("Hello World"); // "Echo: Hello World"
125
```
126
127
### Dynamic Tool
128
129
Runtime-defined tool with function-based implementation.
130
131
```typescript { .api }
132
/**
133
* Tool defined at runtime with a function
134
* @template ToolOutputT - Tool output type
135
*/
136
class DynamicTool<ToolOutputT = unknown> extends Tool<ToolOutputT> {
137
/** Tool implementation function */
138
func: (input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
139
140
constructor(fields: DynamicToolInput<ToolOutputT>);
141
142
/** Execute the provided function */
143
async _call(input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig): Promise<ToolOutputT>;
144
}
145
```
146
147
**Usage Examples:**
148
149
```typescript
150
import { DynamicTool } from "@langchain/core/tools";
151
152
// Create tool from function
153
const upperCaseTool = new DynamicTool({
154
name: "uppercase",
155
description: "Convert text to uppercase",
156
func: async (input: string) => input.toUpperCase()
157
});
158
159
const result = await upperCaseTool.invoke("hello"); // "HELLO"
160
```
161
162
### Dynamic Structured Tool
163
164
Runtime-defined structured tool with schema validation.
165
166
```typescript { .api }
167
/**
168
* Structured tool defined at runtime
169
* @template SchemaT - Schema type
170
* @template SchemaOutputT - Schema output type
171
* @template SchemaInputT - Schema input type
172
* @template ToolOutputT - Tool output type
173
*/
174
class DynamicStructuredTool<
175
SchemaT = z.ZodSchema,
176
SchemaOutputT = z.output<SchemaT>,
177
SchemaInputT = z.input<SchemaT>,
178
ToolOutputT = unknown
179
> extends StructuredTool<SchemaT, SchemaOutputT, SchemaInputT, ToolOutputT> {
180
/** Tool implementation function */
181
func: (input: SchemaOutputT, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
182
183
constructor(fields: DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT>);
184
185
/** Execute the provided function */
186
async _call(input: SchemaOutputT, runManager?: CallbackManagerForToolRun, config?: RunnableConfig): Promise<ToolOutputT>;
187
}
188
```
189
190
**Usage Examples:**
191
192
```typescript
193
import { DynamicStructuredTool } from "@langchain/core/tools";
194
import { z } from "zod";
195
196
// Create structured tool from function
197
const weatherTool = new DynamicStructuredTool({
198
name: "get_weather",
199
description: "Get current weather for a location",
200
schema: z.object({
201
location: z.string().describe("City name"),
202
unit: z.enum(["celsius", "fahrenheit"]).default("celsius")
203
}),
204
func: async ({ location, unit }) => {
205
// Simulate API call
206
const temp = unit === "celsius" ? "22°C" : "72°F";
207
return `Weather in ${location}: ${temp}, sunny`;
208
}
209
});
210
211
const weather = await weatherTool.invoke({
212
location: "Paris",
213
unit: "celsius"
214
}); // "Weather in Paris: 22°C, sunny"
215
```
216
217
### Tool Factory Function
218
219
Convenient factory function for creating tools.
220
221
```typescript { .api }
222
/**
223
* Factory function for creating tools
224
* @template SchemaT - Schema type
225
* @param func - Tool implementation function
226
* @param fields - Tool configuration
227
* @returns DynamicTool or DynamicStructuredTool based on schema
228
*/
229
function tool<SchemaT = z.ZodString>(
230
func: SchemaT extends z.ZodString
231
? (input: string) => unknown | Promise<unknown>
232
: (input: z.output<SchemaT>) => unknown | Promise<unknown>,
233
fields: SchemaT extends z.ZodString
234
? { name: string; description: string; schema?: SchemaT }
235
: { name: string; description: string; schema: SchemaT }
236
): SchemaT extends z.ZodString ? DynamicTool : DynamicStructuredTool<SchemaT>;
237
```
238
239
**Usage Examples:**
240
241
```typescript
242
import { tool } from "@langchain/core/tools";
243
import { z } from "zod";
244
245
// Simple string tool
246
const greetTool = tool(
247
(name: string) => `Hello, ${name}!`,
248
{
249
name: "greet",
250
description: "Greet someone by name"
251
}
252
);
253
254
// Structured tool
255
const mathTool = tool(
256
({ x, y, operation }) => {
257
switch (operation) {
258
case "add": return x + y;
259
case "multiply": return x * y;
260
default: throw new Error("Unknown operation");
261
}
262
},
263
{
264
name: "math",
265
description: "Perform math operations",
266
schema: z.object({
267
x: z.number(),
268
y: z.number(),
269
operation: z.enum(["add", "multiply"])
270
})
271
}
272
);
273
```
274
275
### Base Toolkit
276
277
Abstract base class for organizing related tools.
278
279
```typescript { .api }
280
/**
281
* Base class for tool collections
282
*/
283
abstract class BaseToolkit {
284
/** Collection of tools in this toolkit */
285
abstract tools: StructuredToolInterface[];
286
287
/** Get all tools in the toolkit */
288
getTools(): StructuredToolInterface[];
289
}
290
```
291
292
**Usage Examples:**
293
294
```typescript
295
import { BaseToolkit } from "@langchain/core/tools";
296
297
class MathToolkit extends BaseToolkit {
298
tools = [
299
new CalculatorTool(),
300
new StatisticsTool(),
301
new GeometryTool()
302
];
303
}
304
305
const toolkit = new MathToolkit();
306
const allTools = toolkit.getTools();
307
```
308
309
## Tool Utilities
310
311
### Tool Type Checking
312
313
```typescript { .api }
314
/**
315
* Check if object is a LangChain tool
316
*/
317
function isLangChainTool(tool: unknown): tool is ToolInterface;
318
319
/**
320
* Check if tool has structured input
321
*/
322
function isStructuredTool(tool: unknown): tool is StructuredToolInterface;
323
324
/**
325
* Check if object is runnable-like tool
326
*/
327
function isRunnableToolLike(tool: unknown): tool is RunnableToolLike;
328
```
329
330
**Usage Examples:**
331
332
```typescript
333
import { isLangChainTool, isStructuredTool } from "@langchain/core/tools";
334
335
const myTool = new CalculatorTool();
336
337
if (isLangChainTool(myTool)) {
338
console.log("This is a LangChain tool");
339
}
340
341
if (isStructuredTool(myTool)) {
342
console.log("This tool has structured input");
343
console.log("Schema:", myTool.schema);
344
}
345
```
346
347
## Error Handling
348
349
### Tool Input Parsing Exception
350
351
```typescript { .api }
352
/**
353
* Exception thrown when tool input fails validation
354
*/
355
class ToolInputParsingException extends Error {
356
/** The tool that failed parsing */
357
tool: string;
358
/** Original input that failed */
359
input: unknown;
360
/** Validation error details */
361
errors: unknown[];
362
363
constructor(message: string, tool: string, input: unknown, errors: unknown[]);
364
}
365
```
366
367
**Usage Examples:**
368
369
```typescript
370
import { ToolInputParsingException } from "@langchain/core/tools";
371
372
try {
373
await calculator.invoke({
374
operation: "invalid_op", // Invalid enum value
375
a: 5,
376
b: 3
377
});
378
} catch (error) {
379
if (error instanceof ToolInputParsingException) {
380
console.log(`Tool ${error.tool} failed parsing:`, error.errors);
381
}
382
}
383
```
384
385
## Types
386
387
```typescript { .api }
388
interface StructuredToolInterface<SchemaT = any, SchemaInputT = any, ToolOutputT = any> {
389
name: string;
390
description: string;
391
schema: SchemaT;
392
invoke(input: SchemaInputT, config?: RunnableConfig): Promise<ToolReturnType>;
393
call(arg: SchemaInputT, config?: RunnableConfig): Promise<ToolReturnType>;
394
}
395
396
interface ToolInterface<SchemaT = any, SchemaInputT = any, ToolOutputT = any> extends StructuredToolInterface<SchemaT, SchemaInputT, ToolOutputT> {
397
returnDirect?: boolean;
398
responseFormat?: ResponseFormat;
399
verboseParsingErrors?: boolean;
400
}
401
402
type ResponseFormat = "content" | "content_and_artifact";
403
404
interface ToolParams<ToolOutputT = unknown> {
405
name: string;
406
description: string;
407
returnDirect?: boolean;
408
responseFormat?: ResponseFormat;
409
verboseParsingErrors?: boolean;
410
}
411
412
interface StructuredToolParams<SchemaT, ToolOutputT = unknown> extends ToolParams<ToolOutputT> {
413
schema: SchemaT;
414
}
415
416
interface DynamicToolInput<ToolOutputT = unknown> extends ToolParams<ToolOutputT> {
417
func: (input: string, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
418
}
419
420
interface DynamicStructuredToolInput<SchemaT, SchemaOutputT, ToolOutputT = unknown> extends StructuredToolParams<SchemaT, ToolOutputT> {
421
func: (input: SchemaOutputT, runManager?: CallbackManagerForToolRun, config?: RunnableConfig) => Promise<ToolOutputT>;
422
}
423
424
interface RunnableToolLike {
425
name: string;
426
description?: string;
427
parameters?: Record<string, unknown>;
428
invoke(input: unknown, config?: RunnableConfig): Promise<unknown>;
429
}
430
431
interface ToolRunnableConfig extends RunnableConfig {
432
/** Additional tool-specific configuration */
433
toolConfig?: Record<string, unknown>;
434
}
435
436
type ToolReturnType = string | { content: string; artifact?: unknown };
437
```