Overview
The tool calling flow:- Register tools with definitions and handler closures
- Generate with tools — the LLM decides when and which tools to call
- Auto-execution — the SDK runs your handlers and feeds results back to the LLM
- Final response — the LLM produces a natural language answer incorporating tool results
Basic Usage
Setup
Register Tools
Each tool needs aToolDefinition and a handler closure that receives arguments and returns a result dictionary:
Ensure LLM is Loaded
Tool calling requires a loaded LLM model. The LLM processes the prompt and decides which tools to invoke:API Reference
Tool Management
ToolDefinition
ToolParameter
ToolValue
Tagged union for tool arguments and return values:ToolCallingOptions
generateWithTools
ToolCallingResult:
ToolCall
ToolResult
Examples
Weather Tool
Calculator Tool
Current Time Tool
Multi-Tool Chat Flow
Register multiple tools and let the LLM chain them together:Complete SwiftUI Example
Error Handling
Best Practices
Write clear tool descriptions
Write clear tool descriptions
The LLM decides which tools to call based on their
description and parameter descriptions. Be specific — vague descriptions lead to incorrect tool selection or hallucinated arguments.Clear tools between sessions
Clear tools between sessions
Call
clearTools() at the start of each session or screen to prevent stale tool registrations
from interfering with new ones.Limit maxToolCalls
Limit maxToolCalls
Set
maxToolCalls to a reasonable bound (2–5) to prevent runaway loops where the LLM repeatedly
calls tools without converging on a final answer.Validate tool arguments
Validate tool arguments
Always validate and provide defaults for arguments in your handler. The LLM may omit optional parameters or pass unexpected values.
Keep handlers fast
Keep handlers fast
Tool handlers block the generation loop. For slow operations (network calls, database queries),
consider timeouts to prevent the UI from hanging.
Use lower temperature
Use lower temperature
Tool calling works best with lower temperature values (0.3–0.7). Higher temperatures increase the chance of malformed tool call syntax.
Related
LLM Generation
Text generation basics
LLM Chat
Multi-turn conversations
VLM
Vision Language Models
Best Practices
Performance optimization