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 { openaiText } from '@tanstack/ai-openai'
58import { z } from 'zod'
59
60// Define tools that the LLM can call from inside the sandbox
61const weatherTool = toolDefinition({
62 name: 'fetchWeather',
63 description: 'Get weather for a city',
64 inputSchema: z.object({ location: z.string() }),
65 outputSchema: z.object({ temperature: z.number(), condition: z.string() }),
66}).server(async ({ location }) => {
67 // Your implementation
68 return { temperature: 72, condition: 'sunny' }
69})
70
71// Create the execute_typescript tool and system prompt
72const { tool, systemPrompt } = createCodeMode({
73 driver: createNodeIsolateDriver(),
74 tools: [weatherTool],
75})
76
77const result = await chat({
78 adapter: openaiText('gpt-6.1-sol'),
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 threadId: 'thread-1',
85})
86```
87
88The LLM will generate code like:
89
90```typescript
91const cities = ['Tokyo', 'Paris', 'NYC']
92const results = await Promise.all(
93 cities.map((city) => external_fetchWeather({ location: city })),
94)
95const warmest = results.reduce((prev, curr) =>
96 curr.temperature > prev.temperature ? curr : prev,
97)
98return { warmestCity: warmest.location, temperature: warmest.temperature }
99```
100
101## API Reference
102
103### `createCodeMode(config)`
104
105Creates both the `execute_typescript` tool and its matching system prompt. This is the recommended entry point.
106
107**Config:**
108
109- `driver` — An `IsolateDriver` (Node, QuickJS, QuickJS Bun, or Cloudflare)
110- `tools` — Array of `ServerTool` or `ToolDefinition` instances. Exposed as `external_*` functions in the sandbox
111- `timeout` — Execution timeout in ms (default: 30000)
112- `memoryLimit` — Memory limit in MB (default: 128, supported by the Node, QuickJS, and QuickJS Bun drivers)
113- `getSnippetBindings` — Optional async function returning dynamic bindings
114
115### `createCodeModeTool(config)` / `createCodeModeSystemPrompt(config)`
116
117Lower-level functions if you need only the tool or only the prompt. `createCodeMode` calls both internally.
118
119### Advanced
120
121These utilities are used internally and exported for custom pipelines:
122
123- **`stripTypeScript(code)`** — Strips TypeScript syntax using sucrase (edge-safe, no native binary).
124- **`toolsToBindings(tools, prefix?)`** — Converts tools to `ToolBinding` records for sandbox injection.
125- **`generateTypeStubs(bindings, options?)`** — Generates TypeScript type declarations from tool bindings.
126
127## Driver Selection Guide
128
129| Driver | Best For | Native Deps | Browser | Memory Limit |
130| ---------------------------------- | -------------------------------------------- | ------------------- | ------- | ------------ |
131| `@tanstack/ai-isolate-node` | Server-side Node.js apps | Yes (`isolated-vm`) | No | Yes |
132| `@tanstack/ai-isolate-quickjs` | Browser, edge, or no-native-dep environments | No (WASM) | Yes | Yes |
133| `@tanstack/ai-isolate-quickjs-bun` | Bun servers (native QuickJS via `bun:ffi`) | No | No | Yes |
134| `@tanstack/ai-isolate-cloudflare` | Cloudflare Workers deployments | No | N/A | N/A |
135
136## Custom Events
137
138Code Mode emits custom events during execution that you can observe via the TanStack AI event system:
139
140| Event | Description |
141| ----------------------------- | --------------------------------------------------- |
142| `code_mode:execution_started` | Emitted when code execution begins |
143| `code_mode:console` | Emitted for each `console.log/error/warn/info` call |
144| `code_mode:external_call` | Emitted before each `external_*` function call |
145| `code_mode:external_result` | Emitted after a successful `external_*` call |
146| `code_mode:external_error` | Emitted when an `external_*` call fails |
147
148## Models eval (development)
149
150The 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`).
151
1521. `packages/ai-code-mode/models-eval/pull-models.sh` — pull recommended Ollama models
1532. `pnpm --filter @tanstack/ai-code-mode-models-eval eval:capture` — run models and capture raw outputs/telemetry only (no judge LLM call)
1543. `pnpm --filter @tanstack/ai-code-mode-models-eval eval:judge` — judge latest captured session from logs (no model rerun)
1554. `pnpm --filter @tanstack/ai-code-mode-models-eval eval` — single-pass run+judge (legacy convenience mode)
1565. `pnpm --filter @tanstack/ai-code-mode-models-eval eval -- --ollama-only` — only Ollama models from `eval-config.ts`
1576. `pnpm --filter @tanstack/ai-code-mode-models-eval eval -- --ollama-only --models qwen3-coder` — one or more model ids (comma-separated)
158
159Judge-phase flags:
160
161- `--judge-latest` judge latest captured session
162- `--rejudge` re-run judging even if logs already contain judge fields
163
164The 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.
165
166### Model comparison metrics
167
168The models eval now tracks seven decision-oriented metrics plus an overall rating:
169
170- `accuracy` (1-10): numerical/factual correctness vs gold report
171- `comprehensiveness` (1-10): whether the response covers everything requested by the user query
172- `typescriptQuality` (1-10): quality/readability/type-safety of generated TypeScript
173- `codeModeEfficiency` (1-10): how efficiently the model uses code-mode/tooling to reach the answer
174- `speedTier` (1-5): relative wall-clock speed against peers in the same category (`local` or `cloud`)
175- `tokenEfficiencyTier` (1-5): relative token efficiency against peers in the same category
176- `stabilityTier` (1-5): success consistency over the latest 5 logged runs for that model
177- `stars` (1-3): weighted rollup score across all metrics
178
179Raw run telemetry also includes compile/runtime failures, redundant schema checks, total tool calls, TTFT, token totals, stability sample size/rate, and per-model logs.
180
181### Methodology
182
183Canonical output is written to `packages/ai-code-mode/models-eval/results.json` after each capture or judge run.
184
185- Benchmark: single code-mode benchmark prompt over the in-memory `customers` / `products` / `purchases` dataset
186- Primary quality scores (judge): `accuracy`, `comprehensiveness`, `typescriptQuality`, `codeModeEfficiency`
187- Computed comparative scores: `speedTier`, `tokenEfficiencyTier`, `stabilityTier`
188- 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
189- Star rollup weights:
190 - accuracy: 25%
191 - comprehensiveness: 15%
192 - typescriptQuality: 15%
193 - codeModeEfficiency (with compile/runtime failure penalty): 10%
194 - speedTier: 10%
195 - tokenEfficiencyTier: 10%
196 - stabilityTier: 15%
197
198### Model comparison table
199
200The table below is transcribed from canonical `models-eval/results.json` (session `2026-03-26T15:38:44.006Z`).
201
202| Provider | Model | Category | Stars | Accuracy | Comprehensiveness | TypeScript | Code-Mode | Speed Tier | Token Tier | Stability Tier |
203| --------- | ----------------------------- | -------- | ----- | -------- | ----------------- | ---------- | --------- | ---------- | ---------- | -------------- |
204| Ollama | `gpt-oss:20b` | local | ★★★ | 10 | 8 | 5 | 5 | 5 | 5 | 5 |
205| Ollama | `nemotron-cascade-2` | local | ★★☆ | 3 | 5 | 6 | 5 | 1 | 5 | 5 |
206| Anthropic | `claude-haiku-4-5` | cloud | ★★★ | 10 | 10 | 6 | 7 | 3 | 2 | 5 |
207| OpenAI | `gpt-4o-mini` | cloud | ★★★ | 10 | 8 | 7 | 9 | 3 | 1 | 5 |
208| Gemini | `gemini-2.5-flash` | cloud | ★★★ | 10 | 8 | 7 | 10 | 4 | 2 | 5 |
209| xAI | `grok-4-1-fast-non-reasoning` | cloud | ★★★ | 10 | 8 | 6 | 10 | 4 | 5 | 5 |
210| Groq | `llama-3.3-70b-versatile` | cloud | ★★★ | 10 | 7 | 6 | 9 | 5 | 3 | 4 |
211| Groq | `qwen/qwen3-32b` | cloud | ★★☆ | 10 | 8 | 5 | 4 | 1 | 2 | 5 |
212
213Suggested interpretation:
214
215- **Local-first**: favor `stars >= 2` with high speed tier.
216- **Cloud-first quality**: favor high `accuracy` + `typescriptQuality`, then compare stars.
217- **Cost-sensitive**: prioritize `tokenEfficiencyTier` and `speedTier` together.
218
219## License
220
221MIT