Skip to main content

Overview

The defineTool() function defines tools (functions) that language models can call during generation. Tools enable models to access external data, perform calculations, or trigger actions beyond text generation.

Function signature

Parameters

string
required
The unique name of the tool. This is what the model uses to identify and call the tool.Should be descriptive and follow snake_case convention (e.g., get_weather, search_database).
string
required
A clear description of what the tool does. This helps the model understand when and how to use it.Should explain the tool’s purpose, expected inputs, and what it returns.
z.ZodType
required
Zod schema defining the tool’s input parameters. The model will generate arguments matching this schema.

Return value

Returns the same ToolDefinition object that was passed in. This is a type-safe helper that provides IDE autocompletion and validation.

Examples

Basic tool definition

Tool with multiple parameters

Using tools with generate()

Tool execution loop

Complex parameters with nested objects

Tool with enum parameters

Multiple Tools in One Call

Controlling Tool Usage

Type Safety

The tool definition is fully type-safe:

Best Practices

Use descriptive tool names that clearly indicate their purpose. Follow the snake_case convention.
Write clear descriptions that explain what the tool does, when to use it, and what it returns. Good descriptions improve model accuracy.
Use Zod’s .describe() method on parameters to provide additional context to the model.
Always validate tool results before passing them back to the model. Handle errors gracefully.

Common Patterns

1. Database Queries

2. API Calls

3. File Operations