|
| 1 | +--- |
| 2 | +title: Lazy Tools |
| 3 | +id: lazy-tools |
| 4 | +order: 5 |
| 5 | +description: "Keep large tool catalogs out of the Code Mode system prompt with lazy tools — the model fetches TypeScript signatures on demand via a discover_tools call." |
| 6 | +keywords: |
| 7 | + - tanstack ai |
| 8 | + - code mode |
| 9 | + - lazy tools |
| 10 | + - discover_tools |
| 11 | + - progressive disclosure |
| 12 | + - prompt size |
| 13 | + - tool catalog |
| 14 | +--- |
| 15 | + |
| 16 | +Large tool catalogs bloat the `execute_typescript` system prompt. Every tool you pass to `createCodeMode` becomes a full TypeScript type stub in that prompt — and at 50+ tools, those stubs can push the effective prompt into the tens of thousands of tokens before the model has even seen your user message. |
| 17 | + |
| 18 | +Lazy tools fix this with **progressive disclosure**: mark rarely-used tools `lazy: true` and they are withheld from the initial system prompt. The model sees only their names in a short "Discoverable APIs" catalog. When it needs one, it calls the `discover_tools` sibling tool to fetch the TypeScript signature on demand, then uses it inside `execute_typescript`. All sandbox bindings are always injected — lazy only defers _documentation_, not callability. |
| 19 | + |
| 20 | +## Marking a Tool Lazy |
| 21 | + |
| 22 | +Add `lazy: true` to the `toolDefinition` config for any tool you want to defer: |
| 23 | + |
| 24 | +```typescript group=lazy-tools |
| 25 | +import { toolDefinition } from "@tanstack/ai"; |
| 26 | +import { z } from "zod"; |
| 27 | + |
| 28 | +// Always eager — documented upfront |
| 29 | +const fetchWeather = toolDefinition({ |
| 30 | + name: "fetchWeather", |
| 31 | + description: "Get current weather for a city", |
| 32 | + inputSchema: z.object({ location: z.string() }), |
| 33 | + outputSchema: z.object({ temperature: z.number(), condition: z.string() }), |
| 34 | +}).server(async ({ location }) => { |
| 35 | + const res = await fetch(`https://api.weather.example/v1?city=${location}`); |
| 36 | + return res.json(); |
| 37 | +}); |
| 38 | + |
| 39 | +// Lazy — kept out of the system prompt until discovered |
| 40 | +const fetchArchive = toolDefinition({ |
| 41 | + name: "fetchArchive", |
| 42 | + description: "Retrieve historical weather archive data for a date range", |
| 43 | + inputSchema: z.object({ |
| 44 | + location: z.string(), |
| 45 | + from: z.string(), |
| 46 | + to: z.string(), |
| 47 | + }), |
| 48 | + outputSchema: z.array(z.object({ date: z.string(), temperature: z.number() })), |
| 49 | + lazy: true, |
| 50 | +}).server(async ({ location, from, to }) => { |
| 51 | + const res = await fetch( |
| 52 | + `https://api.weather.example/v1/archive?city=${location}&from=${from}&to=${to}` |
| 53 | + ); |
| 54 | + return res.json(); |
| 55 | +}); |
| 56 | +``` |
| 57 | + |
| 58 | +Eager tools continue to receive full type stubs in the system prompt. Lazy tools appear only by name. |
| 59 | + |
| 60 | +## Server Setup |
| 61 | + |
| 62 | +Pass both eager and lazy tools to `createCodeMode`. When at least one tool is lazy, `createCodeMode` also returns a `discover_tools` sibling tool — include it in the `tools` array you pass to `chat()`: |
| 63 | + |
| 64 | +```typescript group=lazy-tools |
| 65 | +// server/route.ts |
| 66 | +import { chat, maxIterations, toServerSentEventsStream } from "@tanstack/ai"; |
| 67 | +import { createCodeMode } from "@tanstack/ai-code-mode"; |
| 68 | +import { createNodeIsolateDriver } from "@tanstack/ai-isolate-node"; |
| 69 | +import { openaiText } from "@tanstack/ai-openai"; |
| 70 | + |
| 71 | +const { tools, systemPrompt } = createCodeMode({ |
| 72 | + driver: createNodeIsolateDriver(), |
| 73 | + tools: [fetchWeather, fetchArchive], // fetchArchive is lazy |
| 74 | +}); |
| 75 | + |
| 76 | +// tools is [execute_typescript, discover_tools] |
| 77 | +// — discover_tools is included automatically because fetchArchive is lazy |
| 78 | + |
| 79 | +export async function POST(req: Request) { |
| 80 | + const { messages } = await req.json(); |
| 81 | + |
| 82 | + const stream = chat({ |
| 83 | + adapter: openaiText("gpt-5.5"), |
| 84 | + systemPrompts: ["You are a helpful weather assistant.", systemPrompt], |
| 85 | + tools: [...tools], |
| 86 | + messages, |
| 87 | + agentLoopStrategy: maxIterations(10), |
| 88 | + }); |
| 89 | + |
| 90 | + return toServerSentEventsStream(stream); |
| 91 | +} |
| 92 | +``` |
| 93 | + |
| 94 | +`createCodeMode` returns `{ tool, discoveryTool, tools, systemPrompt }`: |
| 95 | + |
| 96 | +| Field | Type | Description | |
| 97 | +|-------|------|-------------| |
| 98 | +| `tool` | `ServerTool` | The `execute_typescript` tool (backward compatible) | |
| 99 | +| `discoveryTool` | `ServerTool \| null` | The `discover_tools` tool, or `null` when there are no lazy tools | |
| 100 | +| `tools` | `Array<ServerTool>` | `[tool]` or `[tool, discoveryTool]` — spread into `chat({ tools })` | |
| 101 | +| `systemPrompt` | `string` | The matching system prompt | |
| 102 | + |
| 103 | +If no tools are lazy, `discoveryTool` is `null` and `tools` contains only `execute_typescript`. |
| 104 | + |
| 105 | +## The `discover_tools` Flow |
| 106 | + |
| 107 | +When the model encounters a task that requires a lazy tool, it: |
| 108 | + |
| 109 | +1. Calls `discover_tools` with the tool name (bare name, no `external_` prefix). |
| 110 | +2. Receives the TypeScript type stub and description for that tool. |
| 111 | +3. Writes `execute_typescript` code using the now-documented `external_fetchArchive(...)` call. |
| 112 | + |
| 113 | +The bindings are always injected into the sandbox — discovering a tool only retrieves documentation, it does not enable the binding. The model could call `external_fetchArchive` without discovering it first, but it would be writing blind without the type signature. |
| 114 | + |
| 115 | +## Tuning the Discoverable APIs Catalog |
| 116 | + |
| 117 | +By default, lazy tools appear in the system prompt as bare names with no description: |
| 118 | + |
| 119 | +```text |
| 120 | +### Discoverable APIs |
| 121 | +
|
| 122 | +- external_fetchArchive |
| 123 | +- external_runReport |
| 124 | +- external_exportData |
| 125 | +``` |
| 126 | + |
| 127 | +If you want the model to have a hint about what each tool does before deciding whether to discover it, use `lazyToolsConfig.includeDescription`: |
| 128 | + |
| 129 | +```typescript |
| 130 | +import { createCodeMode } from "@tanstack/ai-code-mode"; |
| 131 | +import { createNodeIsolateDriver } from "@tanstack/ai-isolate-node"; |
| 132 | +import { |
| 133 | + fetchWeather, |
| 134 | + fetchArchive, |
| 135 | + runReport, |
| 136 | + exportData, |
| 137 | +} from "./tools"; |
| 138 | + |
| 139 | +const { tools, systemPrompt } = createCodeMode({ |
| 140 | + driver: createNodeIsolateDriver(), |
| 141 | + tools: [fetchWeather, fetchArchive, runReport, exportData], |
| 142 | + lazyToolsConfig: { |
| 143 | + includeDescription: "first-sentence", // 'none' | 'first-sentence' | 'full' |
| 144 | + }, |
| 145 | +}); |
| 146 | +``` |
| 147 | + |
| 148 | +With `'first-sentence'` the catalog becomes: |
| 149 | + |
| 150 | +```text |
| 151 | +### Discoverable APIs |
| 152 | +
|
| 153 | +- external_fetchArchive — Retrieve historical weather archive data for a date range. |
| 154 | +- external_runReport — Generate a summary report for a given time period. |
| 155 | +- external_exportData — Export query results to CSV or JSON format. |
| 156 | +``` |
| 157 | + |
| 158 | +| Value | Effect | |
| 159 | +|-------|--------| |
| 160 | +| `'none'` (default) | Bare names only — smallest possible prompt addition | |
| 161 | +| `'first-sentence'` | Name plus the first sentence of the tool's description | |
| 162 | +| `'full'` | Name plus the complete description | |
| 163 | + |
| 164 | +The full type stub and input/output schema are always returned on discovery — `includeDescription` only affects the pre-discovery catalog. |
| 165 | + |
| 166 | +## Lazy Tools with Plain `chat()` |
| 167 | + |
| 168 | +The same `lazyToolsConfig` option works for lazy tools used directly with `chat()`, outside of Code Mode. Tools marked `lazy: true` are withheld from the `__lazy__tool__discovery__` catalog description until the model calls for them. Pass `lazyToolsConfig` directly to `chat()`: |
| 169 | + |
| 170 | +```typescript |
| 171 | +import { chat, maxIterations, toServerSentEventsStream } from "@tanstack/ai"; |
| 172 | +import { openaiText } from "@tanstack/ai-openai"; |
| 173 | +import { fetchWeather, fetchArchive, runReport } from "./tools"; |
| 174 | + |
| 175 | +// Non-code-mode: lazy tools in a regular chat agent |
| 176 | +export async function POST(req: Request) { |
| 177 | + const { messages } = await req.json(); |
| 178 | + |
| 179 | + const stream = chat({ |
| 180 | + adapter: openaiText("gpt-5.5"), |
| 181 | + messages, |
| 182 | + tools: [fetchWeather, fetchArchive, runReport], |
| 183 | + lazyToolsConfig: { |
| 184 | + includeDescription: "first-sentence", |
| 185 | + }, |
| 186 | + agentLoopStrategy: maxIterations(10), |
| 187 | + }); |
| 188 | + |
| 189 | + return toServerSentEventsStream(stream); |
| 190 | +} |
| 191 | +``` |
| 192 | + |
| 193 | +The `includeDescription` behavior is identical — `'none'` lists bare tool names, `'first-sentence'` appends the first sentence, `'full'` appends the complete description. |
| 194 | + |
| 195 | +## Tips |
| 196 | + |
| 197 | +- **Start with `'none'`.** The bare-names catalog is enough for models that reason well about tool names. Add `'first-sentence'` only if the model frequently discovers irrelevant tools. |
| 198 | +- **Lazy tools are always callable.** Their `external_*` bindings are injected into the sandbox regardless of whether the model has called `discover_tools`. Discovery only reveals documentation. |
| 199 | +- **Use `discoveryTool` for observability.** You can inspect `discoveryTool.name` (`"discover_tools"`) to confirm the tool is wired up, or log its calls for analytics. |
| 200 | +- **Partition by frequency, not capability.** Mark tools lazy when they are rarely needed for a typical request. Core tools that most requests use should stay eager. |
| 201 | + |
| 202 | +## Next Steps |
| 203 | + |
| 204 | +- [Code Mode](./code-mode) — Core Code Mode setup and API reference |
| 205 | +- [Code Mode with Skills](./code-mode-with-skills) — Persistent reusable skill libraries |
| 206 | +- [Isolate Drivers](./code-mode-isolates) — Compare Node, QuickJS, and Cloudflare sandbox runtimes |
0 commit comments