Build your first agents · Chapter 5 of 8
Tools and tool calls
Defining tools with zod, binding them to a model, and handling the tool calls the model makes.
Goals
- Add a described field to a tool's schema and watch its JSON Schema change.To do
- Send invalid arguments and see validation reject them.To do
- Pass the check.To do
Step 1 of 4: The read
A tool is a function with a schema
tool(fn, { name, description, schema }) from @langchain/core/tools turns an async function into a tool. The schema is a zod object: z.object({ order_id: z.string().describe("The order number") }). It says which arguments the tool takes, their types, and which ones are optional.
The schema serves twice. LangChain converts it to JSON Schema, which is what the model reads. And your code uses it to check the arguments the model sends before your function runs.
What the model sees
model.bindTools(tools) returns a model that sends each tool's name, description and JSON Schema with every call. The function itself never leaves your code. The model only knows what these three tell it, so descriptions are prompts: write them for the model, and describe each field with .describe().
A tool call and its answer
When the model wants a tool, its reply is an AIMessage with tool_calls: each call has a name, args and an id. Your code runs the tool and answers with a ToolMessage that carries the same tool_call_id. A model can ask for several calls at once, so the id is what pairs each result with its call.
Pass the whole tool call to tool.invoke(). The tool validates the args against its schema, runs your function, and returns the ToolMessage for you. If the args do not match, it throws ToolInputParsingException and your function never runs. An agent loop catches the error and sends it back as a ToolMessage with status "error", so the model can fix its call. In chapter 6, ToolNode does this for you.
Step 2 of 4: Try it: From zod to tool call
From zod to tool call
Add a field to a tool's schema and see what the model reads. Then run the model's call through the real validation, once with valid arguments and once with arguments you choose.
Mode:RealSimulatedReal: zod, LangChain's tool(), the JSON Schema conversion and the validation run in this page. Simulated: the model is scripted and does not read the schema. Its tool calls are set in advance, and in the last step you choose their arguments. The order data is fictional.
Step 3 of 4: Check
Check
Next: Question 2 of 3
Step 4 of 4: What you can do now
What you can do now
- Define a tool with tool() and a zod schema, with useful descriptions.
- Bind tools to a model and read its tool_calls.
- Answer a tool call with a ToolMessage, and handle invalid arguments.