How to create custom Tools
This guide assumes familiarity with the following concepts:
When constructing your own agent, you will need to provide it with a
list of Tools that it can use. While LangChain includes some prebuilt
tools, it can often be more useful to use tools that use custom logic.
This guide will walk you through how to use these Dynamic
tools.
In this guide, we will walk through how to do define a tool for two functions:
- A multiplier function that will multiply two numbers by each other
- A made up search function that always returns the string โLangChainโ
The biggest difference here is that the first function requires an object with multiple input fields, while the second one only accepts an object with a single field. Some older agents only work with functions that require single inputs, so itโs important to understand the distinction.
DynamicStructuredTool
โ
Newer and more advanced agents can handle more flexible tools that take
multiple inputs. You can use the
DynamicStructuredTool
class to declare them. Hereโs an example - note that tools must always
return strings!
import { DynamicStructuredTool } from "@langchain/core/tools";
import { z } from "zod";
const multiplyTool = new DynamicStructuredTool({
name: "multiply",
description: "multiply two numbers together",
schema: z.object({
a: z.number().describe("the first number to multiply"),
b: z.number().describe("the second number to multiply"),
}),
func: async ({ a, b }: { a: number; b: number }) => {
return (a * b).toString();
},
});
await multiplyTool.invoke({ a: 8, b: 9 });
"72"
DynamicTool
โ
For older agents that require tools which accept only a single input,
you can pass the relevant parameters to the
DynamicTool
class. This is useful when working with older agents that only support
tools that accept a single input. In this case, no schema is required:
import { DynamicTool } from "@langchain/core/tools";
const searchTool = new DynamicTool({
name: "search",
description: "look things up online",
func: async (_input: string) => {
return "LangChain";
},
});
await searchTool.invoke("foo");
"LangChain"
Next stepsโ
Youโve now seen how to create custom tools.
Next, you might be interested in learning more about how to handle errors in your tool calls.