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

code-mode.md

420 lines17.7 KB

1---
2title: Code Mode
3id: code-mode
4order: 1
5description: "Let LLMs write and execute TypeScript programs that orchestrate tools in a secure sandbox with TanStack AI Code Mode — fewer loops, richer logic."
6keywords:
7 - tanstack ai
8 - code mode
9 - sandbox
10 - typescript execution
11 - tool orchestration
12 - execute_typescript
13 - ai agents
14---
15​
16Code Mode lets an LLM write and execute TypeScript programs inside a secure sandbox. Instead of making one tool call at a time, the model writes a short script that orchestrates multiple tools with loops, conditionals, `Promise.all`, and data transformations — then returns a single result.
17​
18You already have a chat app that uses [tools](../tools/tools). By the end of this guide, you'll have Code Mode set up so the LLM can compose those tools in TypeScript and execute them in a single sandbox call.
19​
20## Why Code Mode?
21​
22### Reduced context window usage
23​
24In a traditional agentic loop, every tool call adds a round-trip of messages: the model's tool-call request, the tool result, then the model's next reasoning step. A task that touches five tools can easily consume thousands of tokens in back-and-forth.
25​
26With Code Mode the model emits one `execute_typescript` call containing a complete program. The five tool invocations happen inside the sandbox, and only the final result comes back — one request, one response.
27​
28### The LLM decides how to interpret tool output
29​
30When tools are called individually, the model must decide what to do with each result in a new turn. With Code Mode, the model writes the logic up front: filter, aggregate, compare, branch. It can `Promise.all` ten API calls, pick the best result, and return a summary — all in a single execution.
31​
32### Type-safe tool execution
33​
34Tools you pass to Code Mode are converted to typed function stubs that appear in the system prompt. The model sees exact input/output types, so it generates correct calls without guessing parameter names or shapes. TypeScript annotations in the generated code are stripped automatically before execution.
35​
36### Secure sandboxing
37​
38Generated code runs in an isolated environment. V8, QuickJS WASM, native QuickJS on Bun, and a Cloudflare Worker have no access to the host file system, network, or process. A Daytona sandbox and an E2B sandbox are full Linux environments. Each sandbox has its own file system, network, and processes. The code in that sandbox cannot reach the host. Timeouts and memory limits are configurable.
39​
40## Getting Started
41​
42### 1. Install packages
43​
44<!-- ::start:tabs variant="package-manager" mode="install" -->
45​
46react: @tanstack/ai @tanstack/ai-code-mode zod
47vue: @tanstack/ai @tanstack/ai-code-mode zod
48solid: @tanstack/ai @tanstack/ai-code-mode zod
49svelte: @tanstack/ai @tanstack/ai-code-mode zod
50preact: @tanstack/ai @tanstack/ai-code-mode zod
51angular: @tanstack/ai @tanstack/ai-code-mode zod
52vanilla: @tanstack/ai @tanstack/ai-code-mode zod
53octane: @tanstack/ai @tanstack/ai-code-mode zod
54​
55<!-- ::end:tabs -->
56​
57Pick an isolate driver:
58​
59Node.js (V8 isolates, native compile):
60​
61<!-- ::start:tabs variant="package-manager" mode="install" -->
62​
63react: @tanstack/ai-isolate-node
64vue: @tanstack/ai-isolate-node
65solid: @tanstack/ai-isolate-node
66svelte: @tanstack/ai-isolate-node
67preact: @tanstack/ai-isolate-node
68angular: @tanstack/ai-isolate-node
69vanilla: @tanstack/ai-isolate-node
70octane: @tanstack/ai-isolate-node
71​
72<!-- ::end:tabs -->
73​
74QuickJS WASM (browsers and edge, no native deps):
75​
76<!-- ::start:tabs variant="package-manager" mode="install" -->
77​
78react: @tanstack/ai-isolate-quickjs
79vue: @tanstack/ai-isolate-quickjs
80solid: @tanstack/ai-isolate-quickjs
81svelte: @tanstack/ai-isolate-quickjs
82preact: @tanstack/ai-isolate-quickjs
83angular: @tanstack/ai-isolate-quickjs
84vanilla: @tanstack/ai-isolate-quickjs
85octane: @tanstack/ai-isolate-quickjs
86​
87<!-- ::end:tabs -->
88​
89QuickJS Bun (native QuickJS via bun:ffi):
90​
91<!-- ::start:tabs variant="package-manager" mode="install" -->
92​
93react: @tanstack/ai-isolate-quickjs-bun
94vue: @tanstack/ai-isolate-quickjs-bun
95solid: @tanstack/ai-isolate-quickjs-bun
96svelte: @tanstack/ai-isolate-quickjs-bun
97preact: @tanstack/ai-isolate-quickjs-bun
98angular: @tanstack/ai-isolate-quickjs-bun
99vanilla: @tanstack/ai-isolate-quickjs-bun
100octane: @tanstack/ai-isolate-quickjs-bun
101​
102<!-- ::end:tabs -->
103​
104Cloudflare Workers:
105​
106<!-- ::start:tabs variant="package-manager" mode="install" -->
107​
108react: @tanstack/ai-isolate-cloudflare
109vue: @tanstack/ai-isolate-cloudflare
110solid: @tanstack/ai-isolate-cloudflare
111svelte: @tanstack/ai-isolate-cloudflare
112preact: @tanstack/ai-isolate-cloudflare
113angular: @tanstack/ai-isolate-cloudflare
114vanilla: @tanstack/ai-isolate-cloudflare
115octane: @tanstack/ai-isolate-cloudflare
116​
117<!-- ::end:tabs -->
118​
119Daytona sandboxes:
120​
121<!-- ::start:tabs variant="package-manager" mode="install" -->
122​
123react: @tanstack/ai-isolate-daytona @daytona/sdk
124vue: @tanstack/ai-isolate-daytona @daytona/sdk
125solid: @tanstack/ai-isolate-daytona @daytona/sdk
126svelte: @tanstack/ai-isolate-daytona @daytona/sdk
127preact: @tanstack/ai-isolate-daytona @daytona/sdk
128angular: @tanstack/ai-isolate-daytona @daytona/sdk
129vanilla: @tanstack/ai-isolate-daytona @daytona/sdk
130octane: @tanstack/ai-isolate-daytona @daytona/sdk
131​
132<!-- ::end:tabs -->
133​
134E2B sandboxes:
135​
136<!-- ::start:tabs variant="package-manager" mode="install" -->
137​
138react: @tanstack/ai-isolate-e2b e2b
139vue: @tanstack/ai-isolate-e2b e2b
140solid: @tanstack/ai-isolate-e2b e2b
141svelte: @tanstack/ai-isolate-e2b e2b
142preact: @tanstack/ai-isolate-e2b e2b
143angular: @tanstack/ai-isolate-e2b e2b
144vanilla: @tanstack/ai-isolate-e2b e2b
145octane: @tanstack/ai-isolate-e2b e2b
146​
147<!-- ::end:tabs -->
148​
149### 2. Define tools
150​
151Define your tools with `toolDefinition()` and provide a server-side implementation with `.server()`. These become the `external_*` functions available inside the sandbox.
152​
153```typescript group=code-mode
154import { toolDefinition } from "@tanstack/ai";
155import { z } from "zod";
156​
157const fetchWeather = toolDefinition({
158 name: "fetchWeather",
159 description: "Get current weather for a city",
160 inputSchema: z.object({ location: z.string() }),
161 outputSchema: z.object({
162 temperature: z.number(),
163 condition: z.string(),
164 }),
165}).server(async ({ location }) => {
166 const res = await fetch(`https://api.weather.example/v1?city=${location}`);
167 return res.json();
168});
169```
170​
171### 3. Create the Code Mode tool and system prompt
172​
173```typescript group=code-mode
174import { createCodeMode } from "@tanstack/ai-code-mode";
175import { createNodeIsolateDriver } from "@tanstack/ai-isolate-node";
176​
177const { tool, systemPrompt } = createCodeMode({
178 driver: createNodeIsolateDriver(),
179 tools: [fetchWeather],
180 timeout: 30_000,
181});
182```
183​
184### 4. Use with `chat()`
185​
186```typescript group=code-mode
187import { chat } from "@tanstack/ai";
188import { openaiText } from "@tanstack/ai-openai";
189​
190const result = await chat({
191 adapter: openaiText("gpt-5.5"),
192 systemPrompts: [
193 "You are a helpful weather assistant.",
194 systemPrompt,
195 ],
196 tools: [tool],
197 messages: [
198 {
199 role: "user",
200 content: "Compare the weather in Tokyo, Paris, and New York City",
201 },
202 ],
203});
204```
205​
206The model will generate something like:
207​
208```typescript ignore
209const cities = ["Tokyo", "Paris", "New York City"];
210const results = await Promise.all(
211 cities.map((city) => external_fetchWeather({ location: city }))
212);
213​
214const warmest = results.reduce((prev, curr) =>
215 curr.temperature > prev.temperature ? curr : prev
216);
217​
218return {
219 comparison: results.map((r, i) => ({
220 city: cities[i],
221 temperature: r.temperature,
222 condition: r.condition,
223 })),
224 warmest: cities[results.indexOf(warmest)],
225};
226```
227​
228All three API calls happen in parallel inside the sandbox. The model receives one structured result instead of three separate tool-call round-trips.
229​
230## API Reference
231​
232### `createCodeMode(config)`
233​
234Creates both the `execute_typescript` tool and its matching system prompt from a single config object. This is the recommended entry point.
235​
236```typescript ignore
237const { tool, systemPrompt } = createCodeMode({
238 driver, // IsolateDriver — required
239 tools, // Array<ServerTool | ToolDefinition> — required, at least one
240 timeout, // number — execution timeout in ms (default: 30000)
241 memoryLimit, // number. Memory limit in MB (default: 128). Node, QuickJS, and E2B drivers.
242 getSnippetBindings, // () => Promise<Record<string, ToolBinding>> — optional dynamic bindings
243});
244```
245​
246**Config properties:**
247​
248| Property | Type | Description |
249|----------|------|-------------|
250| `driver` | `IsolateDriver` | The sandbox runtime to execute code in |
251| `tools` | `Array<ServerTool \| ToolDefinition>` | Tools exposed as `external_*` functions. Must have `.server()` implementations |
252| `timeout` | `number` | Execution timeout in milliseconds (default: 30000) |
253| `memoryLimit` | `number` | Memory limit in MB (default: 128). Supported by Node, QuickJS, and E2B drivers |
254| `getSnippetBindings` | `() => Promise<Record<string, ToolBinding>>` | Optional function returning additional bindings at execution time |
255| `debug` | `DebugOption` | Debug logging, same shape as `chat({ debug })`. Failed executions log under `errors` (on by default), successful ones under `tools`. Pass `{ logger }` to use your own `Logger`, or `false` to silence. See [Debug Logging](../advanced/debug-logging.md) |
256​
257The tool returns a `CodeModeToolResult`:
258​
259```typescript
260interface CodeModeToolResult {
261 success: boolean;
262 result?: unknown; // Return value from the executed code
263 logs?: Array<string>; // Captured console output
264 error?: {
265 message: string;
266 name?: string;
267 line?: number;
268 };
270```
271​
272### `createCodeModeTool(config)` / `createCodeModeSystemPrompt(config)`
273​
274Lower-level functions if you need only the tool or only the prompt. `createCodeMode` calls both internally.
275​
276```typescript
277import { createCodeModeTool, createCodeModeSystemPrompt } from "@tanstack/ai-code-mode";
278import { config } from "./config";
279​
280const tool = createCodeModeTool(config);
281const prompt = createCodeModeSystemPrompt(config);
282```
283​
284### `IsolateDriver`
285​
286The interface that sandbox runtimes implement. You do not implement this yourself — pick one of the provided drivers:
287​
288```typescript
289import type { IsolateConfig, IsolateContext } from "@tanstack/ai-code-mode";
290​
291interface IsolateDriver {
292 createContext(config: IsolateConfig): Promise<IsolateContext>;
294```
295​
296**Available drivers:**
297​
298| Package | Factory function | Environment |
299|---------|-----------------|-------------|
300| `@tanstack/ai-isolate-node` | `createNodeIsolateDriver()` | Node.js |
301| `@tanstack/ai-isolate-quickjs` | `createQuickJSIsolateDriver()` | Node.js, browser, edge |
302| `@tanstack/ai-isolate-quickjs-bun` | `createQuickJSBunIsolateDriver()` | Bun |
303| `@tanstack/ai-isolate-cloudflare` | `createCloudflareIsolateDriver()` | Cloudflare Workers |
304| `@tanstack/ai-isolate-daytona` | `createDaytonaIsolateDriver()` | Daytona sandboxes |
305| `@tanstack/ai-isolate-e2b` | `createE2BIsolateDriver()` | E2B sandboxes |
306​
307For full configuration options for each driver, see [Isolate Drivers](./code-mode-isolates.md).
308​
309### Advanced
310​
311These utilities are used internally and are exported for custom pipelines:
312​
313- **`stripTypeScript(code)`** — Strips TypeScript syntax using sucrase (edge-safe, no native binary), converting to plain JavaScript.
314- **`toolsToBindings(tools, prefix?)`** — Converts TanStack AI tools into `Record<string, ToolBinding>` for sandbox injection.
315- **`generateTypeStubs(bindings, options?)`** — Generates TypeScript type declarations from tool bindings for system prompts.
316​
317## Choosing a Driver
318​
319For a full comparison of drivers with all configuration options, see [Isolate Drivers](./code-mode-isolates.md).
320​
321In brief: use the **Node driver** for server-side Node.js (fastest, V8 JIT), **QuickJS** for browsers or portable edge deployments (no native deps), **QuickJS Bun** for Bun servers (native QuickJS via `bun:ffi`), the **Cloudflare driver** when you deploy to Cloudflare Workers, and the **Daytona driver** when you want execution inside a full remote Linux sandbox.
322​
323Use the **E2B driver** for an E2B sandbox.
324​
325## Custom Events
326​
327Code Mode emits custom events during execution that you can observe through the TanStack AI event system. These are useful for building UIs that show execution progress, debugging, or logging.
328​
329| Event | When | Payload |
330|-------|------|---------|
331| `code_mode:execution_started` | Code execution begins | `{ timestamp, codeLength }` |
332| `code_mode:console` | Each `console.log/error/warn/info` call | `{ level, message, timestamp }` |
333| `code_mode:external_call` | Before an `external_*` function runs | `{ function, args, timestamp }` |
334| `code_mode:external_result` | After a successful `external_*` call | `{ function, result, duration }` |
335| `code_mode:external_error` | When an `external_*` call fails | `{ function, error, duration }` |
336​
337To display these events in your React app, see [Showing Code Mode in the UI](./client-integration).
338​
339## Stop tool calls when the run stops
340​
341When a user stops a chat run, a tool call that the sandbox started keeps going unless the tool listens for the abort. Each `external_*` call gets the `abortSignal` of the chat run in its second argument. Pass it to the slow work:
342​
343```typescript
344import { toolDefinition } from "@tanstack/ai";
345import { z } from "zod";
346​
347const searchDocs = toolDefinition({
348 name: "searchDocs",
349 description: "Search the docs",
350 inputSchema: z.object({ query: z.string() }),
351}).server(async ({ query }, ctx) => {
352 const res = await fetch(
353 `https://search.example/v1?q=${encodeURIComponent(query)}`,
354 { signal: ctx?.abortSignal },
355 );
356 return res.json();
357});
358```
359​
360MCP tools from `@tanstack/ai-mcp` already stop their request when the run aborts.
361​
362A tool that runs inside Code Mode gets these fields:
363​
364- `abortSignal`: the signal of the chat run. If the run is already aborted, the call does not start.
365- `context`: the runtime `context` that you gave to `chat()`.
366- `emitCustomEvent`: sends a custom event to the stream. A tool that a `snippet_*` function calls does not send events.
367​
368The tool does not get `toolCallId` or `inputResponse`. These fields belong to the `execute_typescript` call.
369​
370## Model Compatibility
371​
372Code Mode asks the model to write valid TypeScript that calls your tools through the sandbox bridge. Not every model handles this equally — many small or older models mishandle the `external_*` calling conventions even when the system prompt is explicit. We track a single multi-step benchmark (joining three tables, filtering customers who bought from every product category, aggregating spend per category) against a gold reference. The full harness lives at `packages/ai-code-mode/models-eval/`.
373​
374| Rank | Model | Stars | Acc | Comp | TS | CME | Latency | Tokens |
375|------|-------|:-----:|:---:|:----:|:--:|:---:|--------:|-------:|
376| 1 | `grok:grok-4-1-fast-non-reasoning` | ★★★ | 10 | 9 | 6 | 10 | 7.0s | — |
377| 2 | `ollama:gpt-oss:20b` | ★★★ | 10 | 8 | 6 | 5 | 45.1s | 23.6k |
378| 3 | `anthropic:claude-haiku-4-5` | ★★★ | 10 | 10 | 7 | 10 | 9.4s | 8.5k |
379| 4 | `gemini:gemini-2.5-flash` | ★★★ | 10 | 7 | 5 | 9 | 7.3s | 6.9k |
380| 5 | `ollama:nemotron-cascade-2` | ★★★ | 10 | 9 | 5 | 5 | 60.4s | 11.7k |
381| 6 | `openai:gpt-4o-mini` | ★★☆ | 10 | 8 | 8 | 10 | 19.2s | 8.7k |
382| 7 | `ollama:gemma4:31b` | ★★☆ | 10 | 8 | 4 | 5 | 264.2s | 6.4k |
383​
384**Columns**
385​
386- **Stars** — overall weighted rating (1-3) combining accuracy, comprehensiveness, code quality, code-mode efficiency, speed, token efficiency, and stability.
387- **Acc / Comp / TS / CME** — Anthropic-judged subscores out of 10: accuracy vs gold, comprehensiveness, TypeScript quality, code-mode efficiency (fewer wasted attempts is better).
388- **Latency** — wall-clock time for the full agentic loop.
389- **Tokens** — total prompt + completion tokens. Grok's adapter does not report usage.
390​
391**Takeaways**
392​
393- **Strongest cloud picks:** Grok 4.1 Fast, Claude Haiku 4.5, and Gemini 2.5 Flash all finish under 10s and handle the multi-step task cleanly. Claude Haiku 4.5 has the highest comprehensiveness score (10/10).
394- **Strongest local pick:** `ollama:gpt-oss:20b` is the best local performer at 45s with zero compilation failures. `ollama:nemotron-cascade-2` is a close second.
395- **Avoid:** the smaller `gemma4` (9.6 GB) and the other local models commented out at the top of `eval-config.ts` (`granite4:3b`, `ministral-3`, `mistral:7b`, `qwen3:8b`, etc.) — they either ignore the `external_queryTable` shape, hallucinate results, or refuse to invoke `execute_typescript`.
396- **Caveat:** this is a single‑prompt benchmark. Local model results can vary noticeably between runs; use these as a rough capability filter rather than a definitive ranking.
397​
398Reproduce locally:
399​
400```bash
401cd packages/ai-code-mode/models-eval
402pnpm install
403pnpm eval # full suite (needs cloud API keys + Anthropic for judging)
404pnpm eval -- --ollama-only # local models only
405pnpm eval -- --no-judge # skip Anthropic-based judging
406```
407​
408## Tips
409​
410- **Start simple.** Give the model 2-3 tools and a clear task. Code Mode works best when the model has a focused set of capabilities.
411- **Prefer `Promise.all` tasks.** Code Mode shines when the model can parallelize work that would otherwise be sequential tool calls.
412- **Use `console.log` for debugging.** Logs are captured and returned in the result, making it easy to see what happened inside the sandbox.
413- **Keep tools focused.** Each tool should do one thing well. The model will compose them in code.
414- **Check the system prompt.** Call `createCodeModeSystemPrompt(config)` and inspect the output to see exactly what the model will see, including generated type stubs.
415​
416## Next Steps
417​
418- [Showing Code Mode in the UI](./client-integration) — Display execution progress in your React app
419- [Code Mode with Snippets](./code-mode-with-snippets) — Add persistent, reusable snippet libraries
420- [Isolate Drivers](./code-mode-isolates): compare Node, QuickJS, QuickJS Bun, Cloudflare, Daytona, and E2B.