Overview
Function calling works in two steps:- Request: Send a request with tool definitions. The model may request to call one or more tools.
- Execute & Respond: Execute the requested functions and send the results back to the model.
Tool Definition
A tool is defined using theTool interface:
FunctionDefinition
| Property | Type | Description |
|---|---|---|
name | string | The name of the function (must be unique, a-z, A-Z, 0-9, _, -) |
description | string | Description of what the function does. Highly recommended - helps the model understand when to use it |
parameters | Record<string, unknown> | JSON Schema object describing the function parameters |
Parameters Schema
Theparameters field uses JSON Schema format:
Tool Choice
Thetool_choice parameter controls when and which tools the model should call:
| Value | Type | Description |
|---|---|---|
"auto" | string | Let the model decide whether to call tools (default) |
"none" | string | Don’t call any tools, even if provided |
{ type: "function", function: { name: "function_name" } } | object | Force the model to call a specific function |
ToolChoice Type
Tool Call Object Structure
When the model requests a tool call, you receive aToolCall object:
| Property | Type | Description |
|---|---|---|
id | string | Unique identifier for this tool call |
type | string | Type of tool call (typically "function") |
function | object | Function call details |
function.name | string | Name of the function to call |
function.arguments | string | JSON string containing the function arguments |
Parsing Arguments
Complete Example
Here’s a complete end-to-end example with error handling:Streaming with Tools
Thestream() method also supports tools. For details about streaming, see the Stream Method documentation.
Best Practices
1. Always Provide Descriptions
Descriptions help the model understand when to use each function:2. Use Clear Parameter Names
3. Mark Required Parameters
4. Handle Multiple Tool Calls
Models can request multiple tool calls in a single response. UsePromise.all() to execute them in parallel: