Open History to see the last commit
1---
2title: Lazy Tools
3id: lazy-tools
4order: 5
5description: "Keep rarely used tools out of the Code Mode system prompt. The model gets their TypeScript signatures on demand with a discover_tools call."
6keywords:
7 - tanstack ai
8 - code mode
9 - lazy tools
10 - discover_tools
11 - progressive disclosure
12 - prompt size
13 - tool catalog
14---
15
16Lazy Code Mode tools load a type stub only when the program imports that tool. The system prompt stays small when you register many tools.
17
18Mark the rarely used tools `lazy: true`. The prompt then lists only their names. When the model needs one, it calls `discover_tools` to get the signature, then uses the tool in `execute_typescript`.
19
20## Quick setup
21
22You need the route from the [Code Mode quick setup](./code-mode#quick-setup) first.
23
241. Add `lazy: true` to each tool that most requests do not need:
25
26```typescript group=lazy-tools
27import { toolDefinition } from "@tanstack/ai";
28import { z } from "zod";
29
30// Eager: the full type stub is in the system prompt
31const fetchWeather = toolDefinition({
32 name: "fetchWeather",
33 description: "Get current weather for a city",
34 inputSchema: z.object({ location: z.string() }),
35 outputSchema: z.object({ temperature: z.number(), condition: z.string() }),
36}).server(async ({ location }) => ({
37 temperature: location.length + 10,
38 condition: "sunny",
39}));
40
41// Lazy: only the name is in the system prompt, until the model discovers it
42const fetchArchive = toolDefinition({
43 name: "fetchArchive",
44 description: "Retrieve historical weather archive data for a date range",
45 inputSchema: z.object({
46 location: z.string(),
47 from: z.string(),
48 to: z.string(),
49 }),
50 outputSchema: z.array(z.object({ date: z.string(), temperature: z.number() })),
51 lazy: true,
52}).server(async ({ from, to }) => [
53 { date: from, temperature: 14 },
54 { date: to, temperature: 16 },
55]);
56```
57
582. Give both tools to `createCodeMode`, and give the returned `tools` array to `chat()`. Because one tool is lazy, `tools` also holds `discover_tools`:
59
60```typescript group=lazy-tools
61import {
62 chat,
63 chatParamsFromRequest,
64 maxIterations,
65 toServerSentEventsResponse,
66} from "@tanstack/ai";
67import { createCodeMode } from "@tanstack/ai-code-mode";
68import { createNodeIsolateDriver } from "@tanstack/ai-isolate-node";
69import { openaiText } from "@tanstack/ai-openai";
70
71const { tools, systemPrompt } = createCodeMode({
72 driver: createNodeIsolateDriver(),
73 tools: [fetchWeather, fetchArchive],
74});
75// tools is [execute_typescript, discover_tools]
76
77export async function POST(request: Request) {
78 const { messages, threadId, runId } = await chatParamsFromRequest(request);
79
80 const stream = chat({
81 adapter: openaiText("gpt-6.1-sol"),
82 systemPrompts: ["You are a helpful weather assistant.", systemPrompt],
83 tools,
84 messages,
85 threadId,
86 runId,
87 agentLoopStrategy: maxIterations(10),
88 });
89
90 return toServerSentEventsResponse(stream);
91}
92```
93
943. Ask "What was the weather in Paris from 2026-01-01 to 2026-01-07?" The model calls `discover_tools` first, then calls `external_fetchArchive` in `execute_typescript`.
95
96## How it works
97
98The system prompt lists the lazy tools in a "Discoverable APIs" catalog, with names only:
99
100```text
101### Discoverable APIs
102
103- external_fetchArchive
104- external_runReport
105- external_exportData
106```
107
108Then the model:
109
1101. Calls `discover_tools` with a list of tool names. The `external_` prefix is optional.
1112. Gets the TypeScript type stub and the description of each tool.
1123. Writes `execute_typescript` code that calls `external_fetchArchive(...)`.
113
114Lazy hides only the documentation. Every tool is always a function in the sandbox. The model can call `external_fetchArchive` with no discovery, but then it writes the call without the type signature.
115
116## Show descriptions in the catalog
117
118To give the model a hint about each lazy tool before it discovers one, set `lazyToolsConfig.includeDescription`:
119
120```typescript ignore
121const { tools, systemPrompt } = createCodeMode({
122 driver: createNodeIsolateDriver(),
123 tools: [fetchWeather, fetchArchive],
124 lazyToolsConfig: {
125 includeDescription: "first-sentence",
126 },
127});
128```
129
130| Value | What the catalog shows |
131|-------|------------------------|
132| `'none'` (default) | Names only. This is the smallest prompt. |
133| `'first-sentence'` | The name and the first sentence of the description. |
134| `'full'` | The name and the full description. |
135
136`includeDescription` changes only the catalog. A `discover_tools` call always returns the full type stub.
137
138## Lazy tools with no Code Mode
139
140`chat()` also takes `lazyToolsConfig`, for lazy tools that you give to `chat()` directly. The `includeDescription` values work the same way:
141
142```typescript ignore
143const stream = chat({
144 adapter: openaiText("gpt-6.1-sol"),
145 messages,
146 threadId: "thread-1",
147 tools: [fetchWeather, fetchArchive],
148 lazyToolsConfig: { includeDescription: "first-sentence" },
149});
150```
151
152For the full setup without Code Mode, see [Lazy Tool Discovery](../tools/lazy-tool-discovery).
153
154## Advanced
155
156### What `createCodeMode` returns
157
158| Field | Type | Description |
159|-------|------|-------------|
160| `tool` | `ServerTool` | The `execute_typescript` tool. |
161| `discoveryTool` | `ServerTool \| null` | The `discover_tools` tool, or `null` when no tool is lazy. |
162| `tools` | `Array<ServerTool>` | `[tool]`, or `[tool, discoveryTool]`. Give this array to `chat({ tools })`. |
163| `systemPrompt` | `string` | The matching system prompt. |
164
165If no tool is lazy, `tools` holds only `execute_typescript`. So you can always pass `tools`, with or without lazy tools.
166
167### `discover_tools` input and output
168
169- **Input:** `{ toolNames: Array<string> }`. Each name can be `fetchArchive` or `external_fetchArchive`.
170- **Output:** `{ tools: Array<{ name, description, typeStub }>, errors? }`. An unknown name adds an entry to `errors` that lists the tools that the model can discover.
171
172`discover_tools` is a separate tool call. It is not a function inside `execute_typescript`.
173
174### Tips
175
176- **Start with `'none'`.** Names are enough for models that reason well about tool names. Switch to `'first-sentence'` if the model often discovers the wrong tools.
177- **Split by how often a tool is used.** When most requests do not need a tool, make it lazy. Keep the core tools eager.
178- **Watch `discover_tools` calls.** `discoveryTool.name` is `"discover_tools"`. Log its calls to see which lazy tools the model needs.