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

code-mode.md

370 lines15.6 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 isolate, QuickJS WASM, native QuickJS on Bun, Cloudflare Worker, or Daytona sandbox) with no access to the host file system, network, or process. The sandbox has configurable timeouts and memory limits.
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​
134### 2. Define tools
135​
136Define your tools with `toolDefinition()` and provide a server-side implementation with `.server()`. These become the `external_*` functions available inside the sandbox.
137​
138```typescript group=code-mode
139import { toolDefinition } from "@tanstack/ai";
140import { z } from "zod";
141​
142const fetchWeather = toolDefinition({
143 name: "fetchWeather",
144 description: "Get current weather for a city",
145 inputSchema: z.object({ location: z.string() }),
146 outputSchema: z.object({
147 temperature: z.number(),
148 condition: z.string(),
149 }),
150}).server(async ({ location }) => {
151 const res = await fetch(`https://api.weather.example/v1?city=${location}`);
152 return res.json();
153});
154```
155​
156### 3. Create the Code Mode tool and system prompt
157​
158```typescript group=code-mode
159import { createCodeMode } from "@tanstack/ai-code-mode";
160import { createNodeIsolateDriver } from "@tanstack/ai-isolate-node";
161​
162const { tool, systemPrompt } = createCodeMode({
163 driver: createNodeIsolateDriver(),
164 tools: [fetchWeather],
165 timeout: 30_000,
166});
167```
168​
169### 4. Use with `chat()`
170​
171```typescript group=code-mode
172import { chat } from "@tanstack/ai";
173import { openaiText } from "@tanstack/ai-openai";
174​
175const result = await chat({
176 adapter: openaiText("gpt-5.5"),
177 systemPrompts: [
178 "You are a helpful weather assistant.",
179 systemPrompt,
180 ],
181 tools: [tool],
182 messages: [
183 {
184 role: "user",
185 content: "Compare the weather in Tokyo, Paris, and New York City",
186 },
187 ],
188});
189```
190​
191The model will generate something like:
192​
193```typescript ignore
194const cities = ["Tokyo", "Paris", "New York City"];
195const results = await Promise.all(
196 cities.map((city) => external_fetchWeather({ location: city }))
197);
198​
199const warmest = results.reduce((prev, curr) =>
200 curr.temperature > prev.temperature ? curr : prev
201);
202​
203return {
204 comparison: results.map((r, i) => ({
205 city: cities[i],
206 temperature: r.temperature,
207 condition: r.condition,
208 })),
209 warmest: cities[results.indexOf(warmest)],
210};
211```
212​
213All three API calls happen in parallel inside the sandbox. The model receives one structured result instead of three separate tool-call round-trips.
214​
215## API Reference
216​
217### `createCodeMode(config)`
218​
219Creates both the `execute_typescript` tool and its matching system prompt from a single config object. This is the recommended entry point.
220​
221```typescript ignore
222const { tool, systemPrompt } = createCodeMode({
223 driver, // IsolateDriver — required
224 tools, // Array<ServerTool | ToolDefinition> — required, at least one
225 timeout, // number — execution timeout in ms (default: 30000)
226 memoryLimit, // number — memory limit in MB (default: 128, Node + QuickJS drivers)
227 getSnippetBindings, // () => Promise<Record<string, ToolBinding>> — optional dynamic bindings
228});
229```
230​
231**Config properties:**
232​
233| Property | Type | Description |
234|----------|------|-------------|
235| `driver` | `IsolateDriver` | The sandbox runtime to execute code in |
236| `tools` | `Array<ServerTool \| ToolDefinition>` | Tools exposed as `external_*` functions. Must have `.server()` implementations |
237| `timeout` | `number` | Execution timeout in milliseconds (default: 30000) |
238| `memoryLimit` | `number` | Memory limit in MB (default: 128). Supported by Node and QuickJS drivers |
239| `getSnippetBindings` | `() => Promise<Record<string, ToolBinding>>` | Optional function returning additional bindings at execution time |
240​
241The tool returns a `CodeModeToolResult`:
242​
243```typescript
244interface CodeModeToolResult {
245 success: boolean;
246 result?: unknown; // Return value from the executed code
247 logs?: Array<string>; // Captured console output
248 error?: {
249 message: string;
250 name?: string;
251 line?: number;
252 };
254```
255​
256### `createCodeModeTool(config)` / `createCodeModeSystemPrompt(config)`
257​
258Lower-level functions if you need only the tool or only the prompt. `createCodeMode` calls both internally.
259​
260```typescript
261import { createCodeModeTool, createCodeModeSystemPrompt } from "@tanstack/ai-code-mode";
262import { config } from "./config";
263​
264const tool = createCodeModeTool(config);
265const prompt = createCodeModeSystemPrompt(config);
266```
267​
268### `IsolateDriver`
269​
270The interface that sandbox runtimes implement. You do not implement this yourself — pick one of the provided drivers:
271​
272```typescript
273import type { IsolateConfig, IsolateContext } from "@tanstack/ai-code-mode";
274​
275interface IsolateDriver {
276 createContext(config: IsolateConfig): Promise<IsolateContext>;
278```
279​
280**Available drivers:**
281​
282| Package | Factory function | Environment |
283|---------|-----------------|-------------|
284| `@tanstack/ai-isolate-node` | `createNodeIsolateDriver()` | Node.js |
285| `@tanstack/ai-isolate-quickjs` | `createQuickJSIsolateDriver()` | Node.js, browser, edge |
286| `@tanstack/ai-isolate-quickjs-bun` | `createQuickJSBunIsolateDriver()` | Bun |
287| `@tanstack/ai-isolate-cloudflare` | `createCloudflareIsolateDriver()` | Cloudflare Workers |
288| `@tanstack/ai-isolate-daytona` | `createDaytonaIsolateDriver()` | Daytona sandboxes |
289​
290For full configuration options for each driver, see [Isolate Drivers](./code-mode-isolates.md).
291​
292### Advanced
293​
294These utilities are used internally and are exported for custom pipelines:
295​
296- **`stripTypeScript(code)`** — Strips TypeScript syntax using sucrase (edge-safe, no native binary), converting to plain JavaScript.
297- **`toolsToBindings(tools, prefix?)`** — Converts TanStack AI tools into `Record<string, ToolBinding>` for sandbox injection.
298- **`generateTypeStubs(bindings, options?)`** — Generates TypeScript type declarations from tool bindings for system prompts.
299​
300## Choosing a Driver
301​
302For a full comparison of drivers with all configuration options, see [Isolate Drivers](./code-mode-isolates.md).
303​
304In 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.
305​
306## Custom Events
307​
308Code 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.
309​
310| Event | When | Payload |
311|-------|------|---------|
312| `code_mode:execution_started` | Code execution begins | `{ timestamp, codeLength }` |
313| `code_mode:console` | Each `console.log/error/warn/info` call | `{ level, message, timestamp }` |
314| `code_mode:external_call` | Before an `external_*` function runs | `{ function, args, timestamp }` |
315| `code_mode:external_result` | After a successful `external_*` call | `{ function, result, duration }` |
316| `code_mode:external_error` | When an `external_*` call fails | `{ function, error, duration }` |
317​
318To display these events in your React app, see [Showing Code Mode in the UI](./client-integration).
319​
320## Model Compatibility
321​
322Code 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/`.
323​
324| Rank | Model | Stars | Acc | Comp | TS | CME | Latency | Tokens |
325|------|-------|:-----:|:---:|:----:|:--:|:---:|--------:|-------:|
326| 1 | `grok:grok-4-1-fast-non-reasoning` | ★★★ | 10 | 9 | 6 | 10 | 7.0s | — |
327| 2 | `ollama:gpt-oss:20b` | ★★★ | 10 | 8 | 6 | 5 | 45.1s | 23.6k |
328| 3 | `anthropic:claude-haiku-4-5` | ★★★ | 10 | 10 | 7 | 10 | 9.4s | 8.5k |
329| 4 | `gemini:gemini-2.5-flash` | ★★★ | 10 | 7 | 5 | 9 | 7.3s | 6.9k |
330| 5 | `ollama:nemotron-cascade-2` | ★★★ | 10 | 9 | 5 | 5 | 60.4s | 11.7k |
331| 6 | `openai:gpt-4o-mini` | ★★☆ | 10 | 8 | 8 | 10 | 19.2s | 8.7k |
332| 7 | `ollama:gemma4:31b` | ★★☆ | 10 | 8 | 4 | 5 | 264.2s | 6.4k |
333​
334**Columns**
335​
336- **Stars** — overall weighted rating (1-3) combining accuracy, comprehensiveness, code quality, code-mode efficiency, speed, token efficiency, and stability.
337- **Acc / Comp / TS / CME** — Anthropic-judged subscores out of 10: accuracy vs gold, comprehensiveness, TypeScript quality, code-mode efficiency (fewer wasted attempts is better).
338- **Latency** — wall-clock time for the full agentic loop.
339- **Tokens** — total prompt + completion tokens. Grok's adapter does not report usage.
340​
341**Takeaways**
342​
343- **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).
344- **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.
345- **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`.
346- **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.
347​
348Reproduce locally:
349​
350```bash
351cd packages/ai-code-mode/models-eval
352pnpm install
353pnpm eval # full suite (needs cloud API keys + Anthropic for judging)
354pnpm eval -- --ollama-only # local models only
355pnpm eval -- --no-judge # skip Anthropic-based judging
356```
357​
358## Tips
359​
360- **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.
361- **Prefer `Promise.all` tasks.** Code Mode shines when the model can parallelize work that would otherwise be sequential tool calls.
362- **Use `console.log` for debugging.** Logs are captured and returned in the result, making it easy to see what happened inside the sandbox.
363- **Keep tools focused.** Each tool should do one thing well. The model will compose them in code.
364- **Check the system prompt.** Call `createCodeModeSystemPrompt(config)` and inspect the output to see exactly what the model will see, including generated type stubs.
365​
366## Next Steps
367​
368- [Showing Code Mode in the UI](./client-integration) — Display execution progress in your React app
369- [Code Mode with Snippets](./code-mode-with-snippets) — Add persistent, reusable snippet libraries
370- [Isolate Drivers](./code-mode-isolates) — Compare Node, QuickJS, QuickJS Bun, Cloudflare, and Daytona sandbox runtimes