StudyVisuallyStart studying
Part 06 · LangChain / LangGraph · Card 6 of 14

tool() with Zod

Define a tool once with a Zod schema. LangChain turns it into the JSON schema the model needs.

Last updated

Analogy

Write the Zod schema you'd write anyway, and get the API docs for free.

Code example

search-tool.tsTypeScript
import { tool } from "@langchain/core/tools";
import { z } from "zod";
const searchDocs = tool(
async ({ query }) => JSON.stringify(await retriever.invoke(query)),
{
name: "searchDocs",
description: "Search the team's engineering docs",
schema: z.object({ query: z.string() }),
},
);

In an agent

The same Zod schema documents the tool for the model and validates its arguments.

Questions people ask

How do I define a tool with Zod in LangChain?

Use the tool function from @langchain/core/tools. Pass an async function and an object with a name, a description and a Zod schema for the arguments. LangChain converts the Zod schema into the JSON schema the model needs, and checks the model's arguments against it before your function runs.

Why define agent tools with Zod schemas?

One schema does two jobs. It documents the tool for the model, because it becomes the JSON schema in the request, and it validates the arguments the model sends back. You avoid writing the same shape twice, and bad arguments are caught before your code touches a database or an API.