Open History to see the last commit
1<div align="center">
2 <picture>
3 <source
4 media="(prefers-color-scheme: dark)"
5 srcset="https://tanstack.com/api/readme/ai.png?theme=dark"
6 />
7 <source
8 media="(prefers-color-scheme: light)"
9 srcset="https://tanstack.com/api/readme/ai.png"
10 />
11 <img
12 src="https://tanstack.com/api/readme/ai.png"
13 alt="TanStack AI"
14 width="900"
15 />
16 </picture>
17</div>
18
19<br />
20
21# @tanstack/ai-code-mode
22
23Code Mode for TanStack AI — let LLMs write and execute TypeScript in secure sandboxes with typed tool access.
24
25## Overview
26
27Code Mode gives your AI agent an `execute_typescript` tool. Instead of one tool call per action, the LLM writes a small TypeScript program that orchestrates multiple tool calls with loops, conditionals, `Promise.all`, and data transformations — all running in an isolated sandbox.
28
29## Installation
30
31```bash
32pnpm add @tanstack/ai-code-mode
33```
34
35You also need an isolate driver:
36
37```bash
38# Node.js (fastest, uses V8 isolates via isolated-vm)
39pnpm add @tanstack/ai-isolate-node
40
41# QuickJS WASM (browser-compatible, no native deps)
42pnpm add @tanstack/ai-isolate-quickjs
43
44# Bun servers (native QuickJS via bun:ffi)
45bun add @tanstack/ai-isolate-quickjs-bun
46
47# Cloudflare Workers (edge execution)
48pnpm add @tanstack/ai-isolate-cloudflare
49```
50
51## Quick Start
52
53```typescript
54import { chat, toolDefinition } from '@tanstack/ai'
55import { createCodeMode } from '@tanstack/ai-code-mode'
56import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
57import { z } from 'zod'
58
59// Define tools that the LLM can call from inside the sandbox
60const weatherTool = toolDefinition({
61 name: 'fetchWeather',
62 description: 'Get weather for a city',
63 inputSchema: z.object({ location: z.string() }),
64 outputSchema: z.object({ temperature: z.number(), condition: z.string() }),
65}).server(async ({ location }) => {
66 // Your implementation
67 return { temperature: 72, condition: 'sunny' }
68})
69
70// Create the execute_typescript tool and system prompt
71const { tool, systemPrompt } = createCodeMode({
72 driver: createNodeIsolateDriver(),
73 tools: [weatherTool],
74})
75
76const result = await chat({
77 adapter: yourAdapter,
78 model: 'gpt-4o',
79 systemPrompts: ['You are a helpful assistant.', systemPrompt],
80 tools: [tool],
81 messages: [
82 { role: 'user', content: 'Compare weather in Tokyo, Paris, and NYC' },
83 ],
84})
85```
86
87The LLM will generate code like:
88
89```typescript
90const cities = ['Tokyo', 'Paris', 'NYC']
91const results = await Promise.all(
92 cities.map((city) => external_fetchWeather({ location: city })),
93)
94const warmest = results.reduce((prev, curr) =>
95 curr.temperature > prev.temperature ? curr : prev,
96)
97return { warmestCity: warmest.location, temperature: warmest.temperature }
98```
99
100## API Reference
101
102### `createCodeMode(config)`
103
104Creates both the `execute_typescript` tool and its matching system prompt. This is the recommended entry point.
105
106**Config:**
107
108- `driver` — An `IsolateDriver` (Node, QuickJS, QuickJS Bun, or Cloudflare)
109- `tools` — Array of `ServerTool` or `ToolDefinition` instances. Exposed as `external_*` functions in the sandbox
110- `timeout` — Execution timeout in ms (default: 30000)
111- `memoryLimit` — Memory limit in MB (default: 128, supported by the Node, QuickJS, and QuickJS Bun drivers)
112- `getSnippetBindings` — Optional async function returning dynamic bindings
113
114### `createCodeModeTool(config)` / `createCodeModeSystemPrompt(config)`
115
116Lower-level functions if you need only the tool or only the prompt. `createCodeMode` calls both internally.
117
118### Advanced
119
120These utilities are used internally and exported for custom pipelines:
121
122- **`stripTypeScript(code)`** — Strips TypeScript syntax using sucrase (edge-safe, no native binary).
123- **`toolsToBindings(tools, prefix?)`** — Converts tools to `ToolBinding` records for sandbox injection.
124- **`generateTypeStubs(bindings, options?)`** — Generates TypeScript type declarations from tool bindings.
125
126## Driver Selection Guide
127
128| Driver | Best For | Native Deps | Browser | Memory Limit |
129| ---------------------------------- | -------------------------------------------- | ------------------- | ------- | ------------ |
130| `@tanstack/ai-isolate-node` | Server-side Node.js apps | Yes (`isolated-vm`) | No | Yes |
131| `@tanstack/ai-isolate-quickjs` | Browser, edge, or no-native-dep environments | No (WASM) | Yes | Yes |
132| `@tanstack/ai-isolate-quickjs-bun` | Bun servers (native QuickJS via `bun:ffi`) | No | No | Yes |
133| `@tanstack/ai-isolate-cloudflare` | Cloudflare Workers deployments | No | N/A | N/A |
134
135## Custom Events
136
137Code Mode emits custom events during execution that you can observe via the TanStack AI event system:
138
139| Event | Description |
140| ----------------------------- | --------------------------------------------------- |
141| `code_mode:execution_started` | Emitted when code execution begins |
142| `code_mode:console` | Emitted for each `console.log/error/warn/info` call |
143| `code_mode:external_call` | Emitted before each `external_*` function call |
144| `code_mode:external_result` | Emitted after a successful `external_*` call |
145| `code_mode:external_error` | Emitted when an `external_*` call fails |
146
147## Models eval (development)
148
149The benchmark lives in a **separate workspace package** so `@tanstack/ai-code-mode` does not depend on `@tanstack/ai-isolate-node` (avoids an Nx build cycle). See `models-eval/package.json` (`@tanstack/ai-code-mode-models-eval`).
150
1511. `packages/ai-code-mode/models-eval/pull-models.sh` — pull recommended Ollama models
1522. `pnpm --filter @tanstack/ai-code-mode-models-eval eval:capture` — run models and capture raw outputs/telemetry only (no judge LLM call)
1533. `pnpm --filter @tanstack/ai-code-mode-models-eval eval:judge` — judge latest captured session from logs (no model rerun)
1544. `pnpm --filter @tanstack/ai-code-mode-models-eval eval` — single-pass run+judge (legacy convenience mode)
1555. `pnpm --filter @tanstack/ai-code-mode-models-eval eval -- --ollama-only` — only Ollama models from `eval-config.ts`
1566. `pnpm --filter @tanstack/ai-code-mode-models-eval eval -- --ollama-only --models qwen3-coder` — one or more model ids (comma-separated)
157
158Judge-phase flags:
159
160- `--judge-latest` judge latest captured session
161- `--rejudge` re-run judging even if logs already contain judge fields
162
163The default list omits some small Ollama models that rarely complete code-mode successfully (see comments in `eval-config.ts`). You can still benchmark them with `--models granite4:3b` etc. if pulled locally.
164
165### Model comparison metrics
166
167The models eval now tracks seven decision-oriented metrics plus an overall rating:
168
169- `accuracy` (1-10): numerical/factual correctness vs gold report
170- `comprehensiveness` (1-10): whether the response covers everything requested by the user query
171- `typescriptQuality` (1-10): quality/readability/type-safety of generated TypeScript
172- `codeModeEfficiency` (1-10): how efficiently the model uses code-mode/tooling to reach the answer
173- `speedTier` (1-5): relative wall-clock speed against peers in the same category (`local` or `cloud`)
174- `tokenEfficiencyTier` (1-5): relative token efficiency against peers in the same category
175- `stabilityTier` (1-5): success consistency over the latest 5 logged runs for that model
176- `stars` (1-3): weighted rollup score across all metrics
177
178Raw run telemetry also includes compile/runtime failures, redundant schema checks, total tool calls, TTFT, token totals, stability sample size/rate, and per-model logs.
179
180### Methodology
181
182Canonical output is written to `packages/ai-code-mode/models-eval/results.json` after each capture or judge run.
183
184- Benchmark: single code-mode benchmark prompt over the in-memory `customers` / `products` / `purchases` dataset
185- Primary quality scores (judge): `accuracy`, `comprehensiveness`, `typescriptQuality`, `codeModeEfficiency`
186- Computed comparative scores: `speedTier`, `tokenEfficiencyTier`, `stabilityTier`
187- Stability definition: a run is "stable" if it has no top-level run error, produces a non-empty candidate report, and has at least one successful `execute_typescript` call
188- Star rollup weights:
189 - accuracy: 25%
190 - comprehensiveness: 15%
191 - typescriptQuality: 15%
192 - codeModeEfficiency (with compile/runtime failure penalty): 10%
193 - speedTier: 10%
194 - tokenEfficiencyTier: 10%
195 - stabilityTier: 15%
196
197### Model comparison table
198
199The table below is transcribed from canonical `models-eval/results.json` (session `2026-03-26T15:38:44.006Z`).
200
201| Provider | Model | Category | Stars | Accuracy | Comprehensiveness | TypeScript | Code-Mode | Speed Tier | Token Tier | Stability Tier |
202| --------- | ----------------------------- | -------- | ----- | -------- | ----------------- | ---------- | --------- | ---------- | ---------- | -------------- |
203| Ollama | `gpt-oss:20b` | local | ★★★ | 10 | 8 | 5 | 5 | 5 | 5 | 5 |
204| Ollama | `nemotron-cascade-2` | local | ★★☆ | 3 | 5 | 6 | 5 | 1 | 5 | 5 |
205| Anthropic | `claude-haiku-4-5` | cloud | ★★★ | 10 | 10 | 6 | 7 | 3 | 2 | 5 |
206| OpenAI | `gpt-4o-mini` | cloud | ★★★ | 10 | 8 | 7 | 9 | 3 | 1 | 5 |
207| Gemini | `gemini-2.5-flash` | cloud | ★★★ | 10 | 8 | 7 | 10 | 4 | 2 | 5 |
208| xAI | `grok-4-1-fast-non-reasoning` | cloud | ★★★ | 10 | 8 | 6 | 10 | 4 | 5 | 5 |
209| Groq | `llama-3.3-70b-versatile` | cloud | ★★★ | 10 | 7 | 6 | 9 | 5 | 3 | 4 |
210| Groq | `qwen/qwen3-32b` | cloud | ★★☆ | 10 | 8 | 5 | 4 | 1 | 2 | 5 |
211
212Suggested interpretation:
213
214- **Local-first**: favor `stars >= 2` with high speed tier.
215- **Cloud-first quality**: favor high `accuracy` + `typescriptQuality`, then compare stars.
216- **Cost-sensitive**: prioritize `tokenEfficiencyTier` and `speedTier` together.
217
218## License
219
220MIT