Skip to main content
Tool Calling lets on-device LLMs invoke functions you define — turning a text model into an agent that can fetch data, perform calculations, or interact with system APIs. The SDK handles prompt formatting, tool call parsing, execution, and multi-turn orchestration.

Overview

The tool calling flow:
  1. Register tools with definitions and handler closures
  2. Generate with tools — the LLM decides when and which tools to call
  3. Auto-execution — the SDK runs your handlers and feeds results back to the LLM
  4. Final response — the LLM produces a natural language answer incorporating tool results

Basic Usage

Setup

Register Tools

Each tool needs a ToolDefinition and a handler closure that receives arguments and returns a result dictionary:
Call clearTools() before registering tools to ensure a clean state — especially important if your app re-registers tools across different screens or sessions.

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

Returns a 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

Tool handlers run in an async context. If your handler accesses @MainActor-isolated state, use await MainActor.run {} inside the closure.

Best Practices

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.
Call clearTools() at the start of each session or screen to prevent stale tool registrations from interfering with new ones.
Set maxToolCalls to a reasonable bound (2–5) to prevent runaway loops where the LLM repeatedly calls tools without converging on a final answer.
Always validate and provide defaults for arguments in your handler. The LLM may omit optional parameters or pass unexpected values.
Tool handlers block the generation loop. For slow operations (network calls, database queries), consider timeouts to prevent the UI from hanging.
Tool calling works best with lower temperature values (0.3–0.7). Higher temperatures increase the chance of malformed tool call syntax.

LLM Generation

Text generation basics

LLM Chat

Multi-turn conversations

VLM

Vision Language Models

Best Practices

Performance optimization