Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tools.md

255 lines9.3 KB

1---
2title: Tools
3id: tools
4order: 1
5description: "Give the model a function it can call. Define a tool with toolDefinition(), pass it to chat(), and the model can look up data and take actions."
6keywords:
7 - tanstack ai
8 - tools
9 - function calling
10 - toolDefinition
11 - isomorphic tools
12 - server tools
13 - client tools
14 - type safety
15---
16​
17A tool is a function the model can call, such as a weather lookup or an order query. `chat()` runs the function and sends the result back.
18​
19You describe the function and its input. The model decides when to call it.
20​
21## Add your first tool
22​
23You need a working chat route first. If you do not have one, start with the [Quick Start](../getting-started/quick-start).
24​
25### 1. Install Zod
26​
27The tool input is a Zod schema. Any [Standard Schema](https://standardschema.dev) library or a plain JSON Schema also works.
28​
29<!-- ::start:tabs variant="package-manager" mode="install" -->
30​
31react: zod
32vue: zod
33solid: zod
34svelte: zod
35preact: zod
36angular: zod
37octane: zod
38vanilla: zod
39​
40<!-- ::end:tabs -->
41​
42### 2. Define the tool and pass it to `chat()`
43​
44Open your chat route. Add the tool and put it in `tools`:
45​
46```typescript
47// api/chat.ts
48import {
49 chat,
50 chatParamsFromRequest,
51 toServerSentEventsResponse,
52 toolDefinition,
53} from "@tanstack/ai";
54import { openaiText } from "@tanstack/ai-openai";
55import { z } from "zod";
56​
57const getWeather = toolDefinition({
58 name: "get_weather",
59 description: "Get the current weather for a city",
60 inputSchema: z.object({
61 city: z.string().meta({ description: "City name, for example Oslo" }),
62 }),
63 outputSchema: z.object({
64 city: z.string(),
65 temperature: z.number(),
66 conditions: z.string(),
67 }),
68}).server(async ({ city }) => {
69 // Call a real weather API here.
70 return { city, temperature: 21, conditions: "sunny" };
71});
72​
73export async function POST(request: Request) {
74 const { messages, threadId, runId } = await chatParamsFromRequest(request);
75​
76 const stream = chat({
77 adapter: openaiText("gpt-6.1-sol"),
78 messages,
79 threadId,
80 runId,
81 tools: [getWeather],
82 });
83​
84 return toServerSentEventsResponse(stream);
86```
87​
88### 3. Ask a question that needs the tool
89​
90Your client code does not change. In your chat, ask "What is the weather in Oslo?"
91​
92The model calls `get_weather`, gets `21` and `sunny`, and answers with the weather. The assistant message now also has a `tool-call` part for the call. To show it in your UI, see [Tool Architecture](./tool-architecture).
93​
94## How it works
95​
961. `chat()` sends the name, the description, and the input schema of each tool to the model.
972. The model decides that it needs a tool. It sends a tool call with the input.
983. `chat()` checks the input against your schema and runs your `.server()` function.
994. `chat()` sends the result back to the model.
1005. The model writes its answer, or it calls another tool. This loop is the [agentic cycle](../chat/agentic-cycle).
101​
102The description matters. The model reads it to decide when to call the tool, so say what the tool does and when to use it.
103​
104`toolDefinition()` is shared code. Add `.server()` to run the tool on the server, or `.client()` to run it in the browser. The same definition works in any server framework and any UI framework.
105​
106## What to read next
107​
108| You want to | Read |
109| --- | --- |
110| Read a database or call an API with a secret key | [Server Tools](./server-tools) |
111| Change the page, read `localStorage`, or use a browser API | [Client Tools](./client-tools) |
112| Ask the user before a tool runs | [Tool Approval Flow](./tool-approval) |
113| Use the provider's own web search or code runner | [Provider Tools](./provider-tools) |
114| Use the tools of an MCP server | [MCP Server Tools](./mcp) |
115| Keep a long tool list cheap | [Lazy Tool Discovery](./lazy-tool-discovery) |
116| Let browser agents call your client tools | [WebMCP Tools](./webmcp) |
117| Let the model write one program that calls many tools | [Code Mode](../code-mode/code-mode) |
118| Know how a tool call moves between model, server, and browser | [Tool Architecture](./tool-architecture) |
119​
120## Advanced
121​
122### Run tools one at a time
123​
124When the model calls several server tools in one turn, they start at the same time. The model gets the results in the order of its calls. Some tools must not overlap, for example a tool that writes a file and a tool that runs the tests.
125​
126Set `toolExecution: 'sequential'` on `chat()` to run the tools of each turn one at a time, in call order:
127​
128```ts
129import { chat, toolDefinition } from '@tanstack/ai'
130import { openaiText } from '@tanstack/ai-openai'
131import { z } from 'zod'
132​
133const writeFile = toolDefinition({
134 name: 'write_file',
135 description: 'Write a file',
136 inputSchema: z.object({ path: z.string(), content: z.string() }),
137}).server(async ({ path }) => ({ written: path }))
138​
139const runTests = toolDefinition({
140 name: 'run_tests',
141 description: 'Run the test suite',
142 inputSchema: z.object({}),
143}).server(async () => ({ passed: true }))
144​
145const stream = chat({
146 adapter: openaiText('gpt-6.1-sol'),
147 messages: [{ role: 'user', content: 'Fix the bug, then run the tests.' }],
148 threadId: 'thread-1',
149 tools: [writeFile, runTests],
150 toolExecution: 'sequential',
151})
152```
153​
154This option does not change client tools. The client runs them as their calls arrive.
155​
156### Choose when the model calls a tool
157​
158Your weather assistant gives advice before it looks up the weather. Or you want a plain text answer, with no tool calls at all. Set `toolChoice`, and the model does what you ask.
159​
160Make the model call `get_weather` first:
161​
162```ts group=tool-choice
163import {
164 chat,
165 toServerSentEventsResponse,
166 toolDefinition,
167 type ChatMiddleware,
168} from '@tanstack/ai'
169import { openaiText } from '@tanstack/ai-openai'
170import { z } from 'zod'
171​
172const getWeather = toolDefinition({
173 name: 'get_weather',
174 description: 'Get the current weather for a city',
175 inputSchema: z.object({ city: z.string() }),
176}).server(async ({ city }) => ({ city, temperature: 21 }))
177​
178// Force the tool on the first model call only.
179const weatherFirst: ChatMiddleware = {
180 name: 'weather-first',
181 onConfig: (ctx) => {
182 if (ctx.phase === 'beforeModel' && ctx.iteration === 0) {
183 return { toolChoice: { type: 'tool', name: 'get_weather' } }
184 }
185 },
187​
188export async function POST(request: Request) {
189 const { messages, threadId } = await request.json()
190​
191 const stream = chat({
192 adapter: openaiText('gpt-6.1-sol'),
193 messages,
194 threadId,
195 tools: [getWeather],
196 middleware: [weatherFirst],
197 })
198​
199 return toServerSentEventsResponse(stream)
201```
202​
203The first model call must call `get_weather`. The next call goes back to the default, so the model answers with the forecast.
204​
205Your client code does not change. `toolChoice` is a server option.
206​
207#### The values
208​
209| Value | What the model does |
210| --- | --- |
211| `'auto'` | It decides. |
212| `'none'` | It calls no tool. |
213| `'required'` | It must call a tool. |
214| `{ type: 'tool', name }` | It must call the tool with this name. |
215​
216#### Set it for the whole run
217​
218`chat({ toolChoice })` applies to every model call of the run. With `'required'` or a named tool, the model never writes a text answer. The run stops at the loop limit, after a tool result.
219​
220For one lookup and nothing more, stop after one call:
221​
222```ts group=tool-choice
223import { maxIterations } from '@tanstack/ai'
224​
225const oneLookup = chat({
226 adapter: openaiText('gpt-6.1-sol'),
227 messages: [{ role: 'user', content: 'Weather in Oslo?' }],
228 threadId: 'thread-1',
229 tools: [getWeather],
230 toolChoice: 'required',
231 agentLoopStrategy: maxIterations(1),
232})
233```
234​
235In `chat({ toolChoice: { type: 'tool', name } })`, your editor suggests the names of the tools that you pass. Any other string also works, for example the name of a provider tool.
236​
237Do you need a text answer on the last call? Return `{ toolChoice: 'none' }` from a middleware. See [Change the tool choice of a call](../advanced/middleware#change-the-tool-choice-of-a-call).
238​
239#### Rules for every adapter
240​
241- If the request has no tools, the adapter sends no tool choice.
242- A tool choice in `modelOptions` wins over `toolChoice`, for example `tool_choice` on OpenAI.
243- The adapter sends the name as you give it. It does not make sure that a tool has this name.
244​
245#### Provider notes
246​
247OpenAI, Grok, Groq, Mistral, OpenRouter, and the other OpenAI-compatible adapters send the value as it is. Some providers change it:
248​
249- **Claude** (Anthropic and Amazon Bedrock): some calls cannot force a tool. Then `'required'` and a named tool become `'auto'`.
250 - `claude-fable-5-1`, `claude-mythos-5-1`, `claude-opus-5-5`, and `claude-sonnet-5-5` never take a forced tool.
251 - No Claude model takes a forced tool while thinking is on. See [Reasoning](../chat/reasoning).
252- **Amazon Bedrock (Converse API)**: Converse has no `none` value, so `'none'` sends no tools. The tool calls in the history go out as text.
253- **Gemini**: the value becomes `functionCallingConfig` (`AUTO`, `NONE`, or `ANY`). A named tool is `ANY` with `allowedFunctionNames`. With only provider tools, such as Google Search, Gemini gets no tool config.
254- **Ollama**: Ollama has no tool choice. See [Ollama](../adapters/ollama#tool-choice).
255- **CLI-style adapters**: each page says which values work. See [Claude Code](../adapters/claude-code#tool-choice), [Codex](../adapters/codex#tool-choice), [OpenCode](../adapters/opencode#tool-choice), [Grok Build](../adapters/grok-build#tool-choice), and [ACP-compatible](../adapters/acp-compatible#tool-choice).