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

code-mode.md

286 lines13.0 KB

1---
2title: Code Mode
3id: code-mode
4order: 1
5description: "Let the model write one short TypeScript program that calls your tools in a sandbox, instead of one tool call per turn."
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 the model write one program that calls several tools. One sandbox run replaces one round trip per tool.
17​
18The model gets one tool, `execute_typescript`, and you get one result back.
19​
20## Quick setup
21​
22You need a working chat first. If you do not have one, start with the [Quick Start](../getting-started/quick-start). This setup takes about 5 minutes.
23​
241. Install Code Mode and the Node sandbox driver:
25​
26<!-- ::start:tabs variant="package-manager" mode="install" -->
27​
28react: @tanstack/ai @tanstack/ai-code-mode @tanstack/ai-isolate-node @tanstack/ai-openai zod
29vue: @tanstack/ai @tanstack/ai-code-mode @tanstack/ai-isolate-node @tanstack/ai-openai zod
30solid: @tanstack/ai @tanstack/ai-code-mode @tanstack/ai-isolate-node @tanstack/ai-openai zod
31svelte: @tanstack/ai @tanstack/ai-code-mode @tanstack/ai-isolate-node @tanstack/ai-openai zod
32preact: @tanstack/ai @tanstack/ai-code-mode @tanstack/ai-isolate-node @tanstack/ai-openai zod
33angular: @tanstack/ai @tanstack/ai-code-mode @tanstack/ai-isolate-node @tanstack/ai-openai zod
34vanilla: @tanstack/ai @tanstack/ai-code-mode @tanstack/ai-isolate-node @tanstack/ai-openai zod
35octane: @tanstack/ai @tanstack/ai-code-mode @tanstack/ai-isolate-node @tanstack/ai-openai zod
36​
37<!-- ::end:tabs -->
38​
39The Node driver needs Node.js 22 or later. On Bun, the edge, or Cloudflare, pick a different driver from [Isolate Drivers](./code-mode-isolates).
40​
412. Replace your chat route with this one. It defines a tool, wraps it with `createCodeMode`, and gives the result to `chat()`:
42​
43```typescript
44// app/api/chat/route.ts (Next.js). Any route that takes a Request works.
45import {
46 chat,
47 chatParamsFromRequest,
48 toServerSentEventsResponse,
49 toolDefinition,
50} from "@tanstack/ai";
51import { createCodeMode } from "@tanstack/ai-code-mode";
52import { createNodeIsolateDriver } from "@tanstack/ai-isolate-node";
53import { openaiText } from "@tanstack/ai-openai";
54import { z } from "zod";
55​
56const temperatures: Record<string, number> = {
57 Tokyo: 18,
58 Paris: 12,
59 "New York City": 9,
60};
61​
62const fetchWeather = toolDefinition({
63 name: "fetchWeather",
64 description: "Get current weather for a city",
65 inputSchema: z.object({ location: z.string() }),
66 outputSchema: z.object({
67 temperature: z.number(),
68 condition: z.string(),
69 }),
70}).server(async ({ location }) => ({
71 temperature: temperatures[location] ?? 20,
72 condition: "sunny",
73}));
74​
75const { tools, systemPrompt } = createCodeMode({
76 driver: createNodeIsolateDriver(),
77 tools: [fetchWeather],
78});
79​
80export async function POST(request: Request) {
81 const { messages, threadId, runId } = await chatParamsFromRequest(request);
82​
83 const stream = chat({
84 adapter: openaiText("gpt-6.1-sol"),
85 systemPrompts: ["You are a helpful weather assistant.", systemPrompt],
86 tools,
87 messages,
88 threadId,
89 runId,
90 });
91​
92 return toServerSentEventsResponse(stream);
94```
95​
963. Open your chat and send: "Compare the weather in Tokyo, Paris, and New York City."
97​
98The model calls `execute_typescript` one time, with a program like this:
99​
100```typescript ignore
101const cities = ["Tokyo", "Paris", "New York City"];
102const results = await Promise.all(
103 cities.map((city) => external_fetchWeather({ location: city }))
104);
105​
106const warmest = results.reduce((prev, curr) =>
107 curr.temperature > prev.temperature ? curr : prev
108);
109​
110return {
111 comparison: results.map((r, i) => ({ city: cities[i], ...r })),
112 warmest: cities[results.indexOf(warmest)],
113};
114```
115​
116The three weather calls run in parallel inside the sandbox. The model gets one result and writes its answer from it.
117​
118## How it works
119​
120- `createCodeMode` turns each tool into a typed `external_<name>` function, for example `external_fetchWeather`.
121- `systemPrompt` shows the model the TypeScript types of these functions. The model sees the exact input and output shapes.
122- `tools` holds the `execute_typescript` tool. Give it to `chat()`.
123- When the model calls `execute_typescript`, Code Mode strips the TypeScript types and runs the code in a fresh sandbox.
124- Each `external_*` call leaves the sandbox and runs your real tool on your server. The sandbox code cannot reach the host.
125​
126The Node, QuickJS, QuickJS Bun, and Cloudflare drivers have no access to the host file system, network, or process. The Daytona and E2B drivers run the code in a full remote Linux sandbox, with its own file system, network, and processes.
127​
128## Add more
129​
130- **Show the run to your users:** [Showing Code Mode in the UI](./client-integration).
131- **Run somewhere other than Node:** [Isolate Drivers](./code-mode-isolates).
132- **Let the model save and reuse code:** [Code Mode with Snippets](./code-mode-with-snippets).
133- **Have many tools:** [Lazy Tools](./lazy-tools) keeps rarely used tools out of the prompt.
134​
135## Advanced
136​
137### Stop tool calls when the run stops
138​
139When 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:
140​
141```typescript
142import { toolDefinition } from "@tanstack/ai";
143import { z } from "zod";
144​
145const searchDocs = toolDefinition({
146 name: "searchDocs",
147 description: "Search the docs",
148 inputSchema: z.object({ query: z.string() }),
149}).server(async ({ query }, ctx) => {
150 const res = await fetch(
151 `https://search.example/v1?q=${encodeURIComponent(query)}`,
152 { signal: ctx?.abortSignal },
153 );
154 return res.json();
155});
156```
157​
158MCP tools from `@tanstack/ai-mcp` already stop their request when the run aborts.
159​
160A tool that runs inside Code Mode gets these fields:
161​
162- `abortSignal`: the signal of the chat run. If the run is already aborted, the call does not start.
163- `context`: the runtime `context` that you gave to `chat()`.
164- `emitCustomEvent`: sends a custom event to the stream. A tool that a `snippet_*` function calls does not send events.
165​
166The tool does not get `toolCallId` or `inputResponse`. These fields belong to the `execute_typescript` call.
167​
168### `createCodeMode` options
169​
170| Option | Type | Description |
171|--------|------|-------------|
172| `driver` | `IsolateDriver` | Required. The sandbox that runs the code. See [Isolate Drivers](./code-mode-isolates). |
173| `tools` | `Array<ServerTool>` | Required, at least one. Each tool needs a `.server()` implementation. Each one becomes an `external_*` function. |
174| `timeout` | `number` | Time limit for one execution, in ms. Default: `30000`. |
175| `memoryLimit` | `number` | Memory limit in MB. Default: `128`. The Node, QuickJS, QuickJS Bun, and E2B drivers use it. |
176| `getSnippetBindings` | `() => Promise<Record<string, ToolBinding>>` | Extra bindings that load at each execution. [Snippets](./code-mode-with-snippets) use it. |
177| `lazyToolsConfig` | `LazyToolsConfig` | How much of each lazy tool the catalog shows. See [Lazy Tools](./lazy-tools). |
178| `onSecretParameter` | `'warn' \| 'throw' \| 'ignore' \| (info) => void` | What to do when a tool parameter name looks like a secret. Default: `'warn'`. |
179| `transpile` | `(code: string) => string \| Promise<string>` | Replaces the step that strips TypeScript. The default uses sucrase and is safe for browsers and the edge. |
180| `debug` | `DebugOption` | Debug logging, same shape as `chat({ debug })`. Failed executions log under `errors` (on by default). Successful ones log under `tools`. Pass `false` to silence it. See [Debug Logging](../advanced/debug-logging.md). |
181​
182`createCodeMode` returns:
183​
184- `tool`: the `execute_typescript` tool.
185- `discoveryTool`: the `discover_tools` tool, or `null` when no tool is lazy.
186- `tools`: `[tool]`, or `[tool, discoveryTool]`. Give this array to `chat()`.
187- `systemPrompt`: the matching system prompt.
188​
189A custom `transpile` function must accept top-level `return` and `await`. The [snippet](./code-mode-with-snippets) helpers ignore `transpile` and always use the default.
190​
191### The result of `execute_typescript`
192​
193```typescript
194interface CodeModeToolResult {
195 success: boolean;
196 result?: unknown; // Return value of the code
197 logs?: Array<string>; // Captured console output
198 error?: {
199 message: string;
200 name?: string;
201 line?: number;
202 stack?: string;
203 };
205```
206​
207### Lower-level functions
208​
209`createCodeMode` calls two functions. When you need only the tool or only the prompt, use them:
210​
211```typescript ignore
212import {
213 createCodeModeTool,
214 createCodeModeSystemPrompt,
215} from "@tanstack/ai-code-mode";
216​
217const tool = createCodeModeTool(config);
218const prompt = createCodeModeSystemPrompt(config);
219```
220​
221`@tanstack/ai-code-mode` also exports these helpers for custom pipelines:
222​
223- `stripTypeScript(code)`: strips TypeScript syntax with sucrase. It needs no native binary, so it runs on the edge.
224- `toolsToBindings(tools, prefix?)`: turns tools into `Record<string, ToolBinding>` for a sandbox.
225- `generateTypeStubs(bindings, options?)`: writes TypeScript declarations for bindings, for a system prompt.
226​
227### Custom events
228​
229Code Mode sends these custom events while it runs. Each event carries the `toolCallId` of its `execute_typescript` call. [Showing Code Mode in the UI](./client-integration) renders them.
230​
231| Event | When | Payload |
232|-------|------|---------|
233| `code_mode:execution_started` | The execution starts | `{ timestamp, codeLength }` |
234| `code_mode:console` | For each `console.log`, `error`, `warn`, or `info` call | `{ level, message, timestamp }` |
235| `code_mode:external_call` | Before an `external_*` function runs | `{ function, args, timestamp }` |
236| `code_mode:external_result` | After an `external_*` call succeeds | `{ function, result, duration }` |
237| `code_mode:external_error` | When an `external_*` call fails | `{ function, error, duration }` |
238| `code_mode:execution_finished` | The execution ends, with success or failure | `{ timestamp, durationMs, phase, success, logCount, error }` |
239​
240### Model compatibility
241​
242Code Mode needs a model that writes valid TypeScript and calls the `external_*` functions correctly. Many small or older models get the calling convention wrong, even with a clear system prompt.
243​
244We run one multi-step benchmark against a gold reference. The task joins three tables, finds customers who bought from every product category, and sums the spend per category. The harness is in `packages/ai-code-mode/models-eval/`.
245​
246| Rank | Model | Stars | Acc | Comp | TS | CME | Latency | Tokens |
247|------|-------|:-----:|:---:|:----:|:--:|:---:|--------:|-------:|
248| 1 | `grok:grok-4-1-fast-non-reasoning` | ★★★ | 10 | 9 | 6 | 10 | 7.0s | n/a |
249| 2 | `ollama:gpt-oss:20b` | ★★★ | 10 | 8 | 6 | 5 | 45.1s | 23.6k |
250| 3 | `anthropic:claude-haiku-4-5` | ★★★ | 10 | 10 | 7 | 10 | 9.4s | 8.5k |
251| 4 | `gemini:gemini-2.5-flash` | ★★★ | 10 | 7 | 5 | 9 | 7.3s | 6.9k |
252| 5 | `ollama:nemotron-cascade-2` | ★★★ | 10 | 9 | 5 | 5 | 60.4s | 11.7k |
253| 6 | `openai:gpt-4o-mini` | ★★☆ | 10 | 8 | 8 | 10 | 19.2s | 8.7k |
254| 7 | `ollama:gemma4:31b` | ★★☆ | 10 | 8 | 4 | 5 | 264.2s | 6.4k |
255​
256The columns:
257​
258- **Stars:** the overall rating (1 to 3). It combines accuracy, completeness, code quality, Code Mode efficiency, speed, token use, and stability.
259- **Acc, Comp, TS, CME:** scores out of 10 from an Anthropic judge. They are accuracy against the gold result, completeness, TypeScript quality, and Code Mode efficiency (fewer wasted attempts is better).
260- **Latency:** the wall-clock time for the full agent loop.
261- **Tokens:** the total prompt and completion tokens. The Grok adapter does not report usage.
262​
263What the results show:
264​
265- **Best cloud models:** Grok 4.1 Fast, Claude Haiku 4.5, and Gemini 2.5 Flash finish in less than 10s and do the task correctly. Claude Haiku 4.5 has the highest completeness score (10/10).
266- **Best local model:** `ollama:gpt-oss:20b` takes 45s and has zero compile failures. `ollama:nemotron-cascade-2` is a close second.
267- **Avoid:** the smaller `gemma4` (9.6 GB) and the local models that are commented out at the top of `eval-config.ts` (for example `granite4:3b`, `ministral-3`, `mistral:7b`, `qwen3:8b`). They ignore the `external_queryTable` shape, invent results, or do not call `execute_typescript`.
268- **Limit:** this benchmark uses one prompt. Local model results change between runs. Use them as a rough filter, not a final ranking.
269​
270To run the benchmark yourself:
271​
272```bash
273cd packages/ai-code-mode/models-eval
274pnpm install
275pnpm eval # full suite (needs cloud API keys + Anthropic for judging)
276pnpm eval -- --ollama-only # local models only
277pnpm eval -- --no-judge # skip Anthropic-based judging
278```
279​
280### Tips
281​
282- **Start small.** Give the model 2 or 3 tools and a clear task.
283- **Use it for parallel work.** Code Mode helps most when the model can `Promise.all` calls that otherwise need separate tool turns.
284- **Read the logs.** The result returns the `console.log` output of the code.
285- **Keep each tool focused.** One tool does one thing. The model combines them in code.
286- **Read the prompt.** Call `createCodeModeSystemPrompt(config)` and print it to see the type stubs that the model sees.