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

code-mode.md

287 lines13.1 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- **Run in a harness session:** [Code mode in a harness](../harness/code-mode) adds code mode as a plugin.
135​
136## Advanced
137​
138### Stop tool calls when the run stops
139​
140When 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:
141​
142```typescript
143import { toolDefinition } from "@tanstack/ai";
144import { z } from "zod";
145​
146const searchDocs = toolDefinition({
147 name: "searchDocs",
148 description: "Search the docs",
149 inputSchema: z.object({ query: z.string() }),
150}).server(async ({ query }, ctx) => {
151 const res = await fetch(
152 `https://search.example/v1?q=${encodeURIComponent(query)}`,
153 { signal: ctx?.abortSignal },
154 );
155 return res.json();
156});
157```
158​
159MCP tools from `@tanstack/ai-mcp` already stop their request when the run aborts.
160​
161A tool that runs inside Code Mode gets these fields:
162​
163- `abortSignal`: the signal of the chat run. If the run is already aborted, the call does not start.
164- `context`: the runtime `context` that you gave to `chat()`.
165- `emitCustomEvent`: sends a custom event to the stream. A tool that a `snippet_*` function calls does not send events.
166​
167The tool does not get `toolCallId` or `inputResponse`. These fields belong to the `execute_typescript` call.
168​
169### `createCodeMode` options
170​
171| Option | Type | Description |
172|--------|------|-------------|
173| `driver` | `IsolateDriver` | Required. The sandbox that runs the code. See [Isolate Drivers](./code-mode-isolates). |
174| `tools` | `Array<ServerTool>` | Required, at least one. Each tool needs a `.server()` implementation. Each one becomes an `external_*` function. |
175| `timeout` | `number` | Time limit for one execution, in ms. Default: `30000`. |
176| `memoryLimit` | `number` | Memory limit in MB. Default: `128`. The Node, QuickJS, QuickJS Bun, and E2B drivers use it. |
177| `getSnippetBindings` | `() => Promise<Record<string, ToolBinding>>` | Extra bindings that load at each execution. [Snippets](./code-mode-with-snippets) use it. |
178| `lazyToolsConfig` | `LazyToolsConfig` | How much of each lazy tool the catalog shows. See [Lazy Tools](./lazy-tools). |
179| `onSecretParameter` | `'warn' \| 'throw' \| 'ignore' \| (info) => void` | What to do when a tool parameter name looks like a secret. Default: `'warn'`. |
180| `transpile` | `(code: string) => string \| Promise<string>` | Replaces the step that strips TypeScript. The default uses sucrase and is safe for browsers and the edge. |
181| `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). |
182​
183`createCodeMode` returns:
184​
185- `tool`: the `execute_typescript` tool.
186- `discoveryTool`: the `discover_tools` tool, or `null` when no tool is lazy.
187- `tools`: `[tool]`, or `[tool, discoveryTool]`. Give this array to `chat()`.
188- `systemPrompt`: the matching system prompt.
189​
190A custom `transpile` function must accept top-level `return` and `await`. The [snippet](./code-mode-with-snippets) helpers ignore `transpile` and always use the default.
191​
192### The result of `execute_typescript`
193​
194```typescript
195interface CodeModeToolResult {
196 success: boolean;
197 result?: unknown; // Return value of the code
198 logs?: Array<string>; // Captured console output
199 error?: {
200 message: string;
201 name?: string;
202 line?: number;
203 stack?: string;
204 };
206```
207​
208### Lower-level functions
209​
210`createCodeMode` calls two functions. When you need only the tool or only the prompt, use them:
211​
212```typescript ignore
213import {
214 createCodeModeTool,
215 createCodeModeSystemPrompt,
216} from "@tanstack/ai-code-mode";
217​
218const tool = createCodeModeTool(config);
219const prompt = createCodeModeSystemPrompt(config);
220```
221​
222`@tanstack/ai-code-mode` also exports these helpers for custom pipelines:
223​
224- `stripTypeScript(code)`: strips TypeScript syntax with sucrase. It needs no native binary, so it runs on the edge.
225- `toolsToBindings(tools, prefix?)`: turns tools into `Record<string, ToolBinding>` for a sandbox.
226- `generateTypeStubs(bindings, options?)`: writes TypeScript declarations for bindings, for a system prompt.
227​
228### Custom events
229​
230Code 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.
231​
232| Event | When | Payload |
233|-------|------|---------|
234| `code_mode:execution_started` | The execution starts | `{ timestamp, codeLength }` |
235| `code_mode:console` | For each `console.log`, `error`, `warn`, or `info` call | `{ level, message, timestamp }` |
236| `code_mode:external_call` | Before an `external_*` function runs | `{ function, args, timestamp }` |
237| `code_mode:external_result` | After an `external_*` call succeeds | `{ function, result, duration }` |
238| `code_mode:external_error` | When an `external_*` call fails | `{ function, error, duration }` |
239| `code_mode:execution_finished` | The execution ends, with success or failure | `{ timestamp, durationMs, phase, success, logCount, error }` |
240​
241### Model compatibility
242​
243Code 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.
244​
245We 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/`.
246​
247| Rank | Model | Stars | Acc | Comp | TS | CME | Latency | Tokens |
248|------|-------|:-----:|:---:|:----:|:--:|:---:|--------:|-------:|
249| 1 | `grok:grok-4-1-fast-non-reasoning` | ★★★ | 10 | 9 | 6 | 10 | 7.0s | n/a |
250| 2 | `ollama:gpt-oss:20b` | ★★★ | 10 | 8 | 6 | 5 | 45.1s | 23.6k |
251| 3 | `anthropic:claude-haiku-4-5` | ★★★ | 10 | 10 | 7 | 10 | 9.4s | 8.5k |
252| 4 | `gemini:gemini-2.5-flash` | ★★★ | 10 | 7 | 5 | 9 | 7.3s | 6.9k |
253| 5 | `ollama:nemotron-cascade-2` | ★★★ | 10 | 9 | 5 | 5 | 60.4s | 11.7k |
254| 6 | `openai:gpt-4o-mini` | ★★☆ | 10 | 8 | 8 | 10 | 19.2s | 8.7k |
255| 7 | `ollama:gemma4:31b` | ★★☆ | 10 | 8 | 4 | 5 | 264.2s | 6.4k |
256​
257The columns:
258​
259- **Stars:** the overall rating (1 to 3). It combines accuracy, completeness, code quality, Code Mode efficiency, speed, token use, and stability.
260- **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).
261- **Latency:** the wall-clock time for the full agent loop.
262- **Tokens:** the total prompt and completion tokens. The Grok adapter does not report usage.
263​
264What the results show:
265​
266- **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).
267- **Best local model:** `ollama:gpt-oss:20b` takes 45s and has zero compile failures. `ollama:nemotron-cascade-2` is a close second.
268- **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`.
269- **Limit:** this benchmark uses one prompt. Local model results change between runs. Use them as a rough filter, not a final ranking.
270​
271To run the benchmark yourself:
272​
273```bash
274cd packages/ai-code-mode/models-eval
275pnpm install
276pnpm eval # full suite (needs cloud API keys + Anthropic for judging)
277pnpm eval -- --ollama-only # local models only
278pnpm eval -- --no-judge # skip Anthropic-based judging
279```
280​
281### Tips
282​
283- **Start small.** Give the model 2 or 3 tools and a clear task.
284- **Use it for parallel work.** Code Mode helps most when the model can `Promise.all` calls that otherwise need separate tool turns.
285- **Read the logs.** The result returns the `console.log` output of the code.
286- **Keep each tool focused.** One tool does one thing. The model combines them in code.
287- **Read the prompt.** Call `createCodeModeSystemPrompt(config)` and print it to see the type stubs that the model sees.