Skip to main content

Overview

Tools enable LLMs to interact with external systems through function calling. The Pi AI toolkit uses TypeBox schemas for type-safe tool definitions with automatic validation.

Tool Definition

Define tools with TypeBox schemas:
string
required
Unique tool identifier. Used by the model to specify which tool to call.
string
required
Natural language description of what the tool does. Helps the model decide when to use it.
TSchema
required
TypeBox schema defining the tool’s parameters. Must be a TypeBox Type.Object().

Example

TypeBox Schemas

TypeBox provides runtime type validation and TypeScript type inference.

Basic Types

StringEnum Helper

Use StringEnum() instead of Type.Enum() for better compatibility with Google’s API and other providers that don’t support anyOf/const patterns.

Complex Types

Type Inference

TypeBox schemas provide automatic TypeScript type inference:

Tool Calling

When models call tools, they return ToolCall objects:

Handling Tool Calls

Streaming Tool Calls

Tool arguments are progressively parsed during streaming:
During toolcall_delta events:
  • Arguments may be incomplete or missing fields
  • String values may be truncated mid-word
  • Arrays may be partially populated
  • At minimum, arguments will be an empty object {}
  • Google provider doesn’t support streaming - you get one toolcall_delta with full arguments

Tool Result Messages

Tool results support both text and images:

Text Results

Image Results

Error Results

Validation

Validate tool arguments against schemas using AJV.

validateToolCall()

Validate a tool call’s arguments:
Tool[]
required
Array of tool definitions to search.
ToolCall
required
The tool call to validate.
any
The validated (and potentially coerced) arguments.
Throws Error if tool is not found or validation fails.

Example

validateToolArguments()

Validate arguments when you already have the tool:
Same as validateToolCall() but takes the tool directly instead of searching.

Complete Example

Full tool calling workflow with validation: