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
Parameters Schema
Theparameters field uses JSON Schema format:
Tool Choice
Thetool_choice parameter controls when and which tools the model should call:
ToolChoice Type
Tool Call Object Structure
When the model requests a tool call, you receive aToolCall object:
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: