Open History to see the last commit
1---
2title: Code Mode with Snippets
3id: code-mode-with-snippets
4order: 3
5description: "Teach Code Mode to save and reuse working code as named snippets backed by persistent storage — faster follow-up requests and composable agent memory."
6keywords:
7 - tanstack ai
8 - code mode
9 - snippets
10 - snippet library
11 - register_snippet
12 - reusable snippets
13 - agent memory
14 - snippet storage
15---
16
17Snippets extend [Code Mode](./code-mode.md) with a persistent library of reusable TypeScript snippets. When the LLM writes a useful piece of code — say, a function that fetches and ranks NPM packages — it can save that code as a _snippet_. On future requests, relevant snippets are loaded from storage and made available as first-class tools the LLM can call without re-writing the logic.
18
19> **Different from agent-authoring skills.** The snippets on this page are _runtime_ snippets the chat LLM saves and reuses. If you're looking to teach your coding assistant (Claude Code, Cursor, etc.) how TanStack AI itself works, see [Agent Skills (TanStack Intent)](../getting-started/agent-skills).
20
21## Overview
22
23The snippets system has two integration paths:
24
25| Approach | Entry point | Snippet selection | Best for |
26|----------|-------------|----------------|----------|
27| **High-level** | `codeModeWithSnippets()` | Automatic (LLM-based) | New projects, turnkey setup |
28| **Manual** | Individual functions (`snippetsToTools`, `createSnippetManagementTools`, etc.) | You decide which snippets to load | Full control, existing setups |
29
30Both paths share the same storage, trust, and execution primitives — they differ only in how snippets are selected and assembled.
31
32## How It Works
33
34A request with snippets enabled goes through these stages:
35
36```text
37┌─────────────────────────────────────────────────────┐
38│ 1. Load snippet index (metadata only, no code) │
39├─────────────────────────────────────────────────────┤
40│ 2. Select relevant snippets (LLM call — fast model) │
41├─────────────────────────────────────────────────────┤
42│ 3. Build tool registry │
43│ ├── execute_typescript (Code Mode sandbox) │
44│ ├── search_snippets / get_snippet / register_snippet │
45│ └── snippet tools (one per selected snippet) │
46├─────────────────────────────────────────────────────┤
47│ 4. Generate system prompt │
48│ ├── Code Mode type stubs │
49│ └── Snippet library documentation │
50├─────────────────────────────────────────────────────┤
51│ 5. Main chat() call (strong model) │
52│ ├── Can call snippet tools directly │
53│ ├── Can write code via execute_typescript │
54│ └── Can register new snippets for future use │
55└─────────────────────────────────────────────────────┘
56```
57
58### LLM calls
59
60There are **two** LLM interactions per request when using the high-level API:
61
621. **Snippet selection** (`selectRelevantSnippets`) — A single chat call using the adapter you provide. It sends the last 5 conversation messages plus a catalog of snippet names/descriptions, and asks the model to return a JSON array of relevant snippet names. This should be a cheap/fast model (e.g., `gpt-4o-mini`, `claude-haiku-4-5`).
63
642. **Main chat** — The primary `chat()` call with your full model. This is where the LLM reasons, calls tools, writes code, and registers snippets.
65
66The selection call is lightweight — it only sees snippet metadata (names, descriptions, usage hints), not full code. If there are no snippets in storage or no messages, it short-circuits and skips the LLM call entirely.
67
68## High-Level API: `codeModeWithSnippets()`
69
70### Installation
71
72<!-- ::start:tabs variant="package-manager" mode="install" -->
73
74react: @tanstack/ai-code-mode-snippets
75vue: @tanstack/ai-code-mode-snippets
76solid: @tanstack/ai-code-mode-snippets
77svelte: @tanstack/ai-code-mode-snippets
78preact: @tanstack/ai-code-mode-snippets
79angular: @tanstack/ai-code-mode-snippets
80vanilla: @tanstack/ai-code-mode-snippets
81octane: @tanstack/ai-code-mode-snippets
82
83<!-- ::end:tabs -->
84
85### Usage
86
87```typescript
88import { chat, maxIterations, toServerSentEventsStream } from '@tanstack/ai'
89import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
90import { codeModeWithSnippets } from '@tanstack/ai-code-mode-snippets'
91import { createFileSnippetStorage } from '@tanstack/ai-code-mode-snippets/storage'
92import { openaiText } from '@tanstack/ai-openai'
93import { myTool1, myTool2 } from './tools'
94
95const messages = [{ role: 'user' as const, content: 'Hello' }]
96const storage = createFileSnippetStorage({ directory: './.snippets' })
97const driver = createNodeIsolateDriver()
98
99const { toolsRegistry, systemPrompt, selectedSnippets } = await codeModeWithSnippets({
100 config: {
101 driver,
102 tools: [myTool1, myTool2],
103 timeout: 60_000,
104 memoryLimit: 128,
105 },
106 adapter: openaiText('gpt-5-mini'), // cheap model for snippet selection
107 snippets: {
108 storage,
109 maxSnippetsInContext: 5,
110 },
111 messages, // current conversation
112})
113
114const stream = chat({
115 adapter: openaiText('gpt-5.5'), // strong model for reasoning
116 tools: toolsRegistry.getTools(),
117 messages,
118 systemPrompts: ['You are a helpful assistant.', systemPrompt],
119 agentLoopStrategy: maxIterations(15),
120})
121```
122
123`codeModeWithSnippets` returns:
124
125| Property | Type | Description |
126|----------|------|-------------|
127| `toolsRegistry` | `ToolRegistry` | Mutable registry containing all tools. Pass to `chat()` via `tools: toolsRegistry.getTools()`. |
128| `systemPrompt` | `string` | Combined Code Mode + snippet library documentation. |
129| `selectedSnippets` | `Array<Snippet>` | Snippets the selection model chose for this conversation. |
130
131### What goes into the registry
132
133The registry is populated with:
134
135- **`execute_typescript`** — The Code Mode sandbox tool. Inside the sandbox, snippets are also available as `snippet_*` functions (loaded dynamically at execution time).
136- **`search_snippets`** — Search the snippet library by query. Returns matching snippet metadata.
137- **`get_snippet`** — Retrieve full details (including code) for a specific snippet.
138- **`register_snippet`** — Save working code as a new snippet. Newly registered snippets are immediately added to the registry as callable tools.
139- **One tool per selected snippet** — Each selected snippet becomes a direct tool (prefixed with `[SNIPPET]` in its description) that the LLM can call without going through `execute_typescript`.
140
141## Manual API
142
143If you want full control — for example, loading all snippets instead of using LLM-based selection — use the lower-level functions directly. This is the approach used in the `ts-code-mode-web` example.
144
145```typescript
146import { chat, maxIterations } from '@tanstack/ai'
147import { createCodeMode } from '@tanstack/ai-code-mode'
148import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
149import {
150 createAlwaysTrustedStrategy,
151 createSnippetManagementTools,
152 createSnippetsSystemPrompt,
153 snippetsToTools,
154} from '@tanstack/ai-code-mode-snippets'
155import { createFileSnippetStorage } from '@tanstack/ai-code-mode-snippets/storage'
156import { openaiText } from '@tanstack/ai-openai'
157import { myTool1, myTool2, BASE_PROMPT } from './tools'
158
159const messages = [{ role: 'user' as const, content: 'Hello' }]
160const trustStrategy = createAlwaysTrustedStrategy()
161const storage = createFileSnippetStorage({
162 directory: './.snippets',
163 trustStrategy,
164})
165const driver = createNodeIsolateDriver()
166
167// 1. Create Code Mode tool + prompt
168const { tool: codeModeTool, systemPrompt: codeModePrompt } =
169 createCodeMode({
170 driver,
171 tools: [myTool1, myTool2],
172 timeout: 60_000,
173 memoryLimit: 128,
174 })
175
176// 2. Load all snippets and convert to tools
177const allSnippets = await storage.loadAll()
178const snippetIndex = await storage.loadIndex()
179
180const snippetTools = allSnippets.length > 0
181 ? snippetsToTools({
182 snippets: allSnippets,
183 driver,
184 tools: [myTool1, myTool2],
185 storage,
186 timeout: 60_000,
187 memoryLimit: 128,
188 })
189 : []
190
191// 3. Create management tools
192const managementTools = createSnippetManagementTools({
193 storage,
194 trustStrategy,
195})
196
197// 4. Generate snippet library prompt
198const snippetsPrompt = createSnippetsSystemPrompt({
199 selectedSnippets: allSnippets,
200 totalSnippetCount: snippetIndex.length,
201 snippetsAsTools: true,
202})
203
204// 5. Assemble and call chat()
205const stream = chat({
206 adapter: openaiText('gpt-5.5'),
207 tools: [codeModeTool, ...managementTools, ...snippetTools],
208 messages,
209 systemPrompts: [BASE_PROMPT, codeModePrompt, snippetsPrompt],
210 agentLoopStrategy: maxIterations(15),
211})
212```
213
214This approach skips the selection LLM call entirely — you load whichever snippets you want and pass them in directly.
215
216## Snippet Storage
217
218Snippets are persisted through the `SnippetStorage` interface. Two implementations are provided:
219
220### File storage (production)
221
222`createFileSnippetStorage` is Node-only — it imports `node:fs` / `node:path` — so
223it lives behind the `/storage` subpath rather than the package root. This keeps
224the root export safe to bundle for Cloudflare Workers and browser builds; only
225reach for the subpath in a Node runtime.
226
227```typescript
228import { createFileSnippetStorage } from '@tanstack/ai-code-mode-snippets/storage'
229import { createDefaultTrustStrategy } from '@tanstack/ai-code-mode-snippets'
230
231const trustStrategy = createDefaultTrustStrategy()
232const storage = createFileSnippetStorage({
233 directory: './.snippets',
234 trustStrategy, // optional, defaults to createDefaultTrustStrategy()
235})
236```
237
238Creates a directory structure:
239
240```text
241.snippets/
242 _index.json # Lightweight catalog for fast loading
243 fetch_github_stats/
244 meta.json # Description, schemas, hints, stats
245 code.ts # TypeScript source
246 compare_npm_packages/
247 meta.json
248 code.ts
249```
250
251### Memory storage (testing & edge runtimes)
252
253```typescript
254import { createMemorySnippetStorage } from '@tanstack/ai-code-mode-snippets'
255
256const storage = createMemorySnippetStorage()
257```
258
259Keeps everything in memory — no `node:fs` dependency, so it is re-exported from
260the package root and is safe to use in Workers and browsers. Useful for tests,
261demos, and edge deployments. (It is also available from the `/storage` subpath.)
262
263### Storage interface
264
265Both implementations satisfy this interface:
266
267| Method | Description |
268|--------|-------------|
269| `loadIndex()` | Load lightweight metadata for all snippets (no code) |
270| `loadAll()` | Load all snippets with full details including code |
271| `get(name)` | Get a single snippet by name |
272| `save(snippet)` | Create or update a snippet |
273| `delete(name)` | Remove a snippet |
274| `search(query, options?)` | Search snippets by text query |
275| `updateStats(name, success)` | Record an execution result for trust tracking |
276
277## Trust Strategies
278
279Snippets start untrusted and earn trust through successful executions. The trust level is metadata only — it does not currently gate execution. Four built-in strategies are available:
280
281```typescript group=code-mode-with-snippets
282import {
283 createDefaultTrustStrategy,
284 createAlwaysTrustedStrategy,
285 createRelaxedTrustStrategy,
286 createCustomTrustStrategy,
287} from '@tanstack/ai-code-mode-snippets'
288```
289
290| Strategy | Initial level | Provisional | Trusted |
291|----------|--------------|-------------|---------|
292| **Default** | `untrusted` | 10+ runs, ≥90% success | 100+ runs, ≥95% success |
293| **Relaxed** | `untrusted` | 3+ runs, ≥80% success | 10+ runs, ≥90% success |
294| **Always trusted** | `trusted` | — | — |
295| **Custom** | Configurable | Configurable | Configurable |
296
297```typescript group=code-mode-with-snippets
298const strategy = createCustomTrustStrategy({
299 initialLevel: 'untrusted',
300 provisionalThreshold: { executions: 5, successRate: 0.85 },
301 trustedThreshold: { executions: 50, successRate: 0.95 },
302})
303```
304
305## Snippet Lifecycle
306
307### Registration
308
309When the LLM produces useful code via `execute_typescript`, the system prompt instructs it to call `register_snippet` with:
310
311- `name` — snake_case identifier (becomes the tool name)
312- `description` — what the snippet does
313- `code` — TypeScript source that receives an `input` variable
314- `inputSchema` / `outputSchema` — JSON Schema strings
315- `usageHints` — when to use this snippet
316- `dependsOn` — other snippets this one calls
317
318The snippet is saved to storage and (if a `ToolRegistry` was provided) immediately added as a callable tool in the current session.
319
320### Execution
321
322When a snippet tool is called, the system:
323
3241. Wraps the snippet code with `const input = <serialized input>;`
3252. Strips TypeScript syntax to plain JavaScript
3263. Creates a fresh sandbox context with `external_*` bindings
3274. Executes the code and returns the result
3285. Updates execution stats (success/failure count) asynchronously
329
330### Selection (high-level API only)
331
332On each new request, `selectRelevantSnippets`:
333
3341. Takes the last 5 conversation messages as context
3352. Builds a catalog from the snippet index (name + description + first usage hint)
3363. Asks the adapter to return a JSON array of relevant snippet names (max `maxSnippetsInContext`)
3374. Loads full snippet data for the selected names
338
339If parsing fails or the model returns invalid JSON, it falls back to an empty selection — the request proceeds without pre-loaded snippets, but the LLM can still search and use snippets via the management tools.
340
341## Snippets as Tools vs. Sandbox Bindings
342
343The `snippetsAsTools` option (default: `true`) controls how snippets are exposed:
344
345| Mode | How the LLM calls a snippet | Pros | Cons |
346|------|--------------------------|------|------|
347| **As tools** (`true`) | Direct tool call: `snippet_name({ ... })` | Simpler for the LLM, shows in tool-call UI, proper input validation | One tool per snippet in the tool list |
348| **As bindings** (`false`) | Inside `execute_typescript`: `await snippet_fetch_data({ ... })` | Snippets composable in code, fewer top-level tools | LLM must write code to use them |
349
350When `snippetsAsTools` is enabled, the system prompt documents each snippet with its schema, usage hints, and example calls. When disabled, snippets appear as typed `snippet_*` functions in the sandbox type stubs.
351
352## Custom Events
353
354Snippet execution emits events through the TanStack AI event system:
355
356| Event | When | Payload |
357|-------|------|---------|
358| `code_mode:snippet_call` | Snippet tool invoked | `{ snippet, input, timestamp }` |
359| `code_mode:snippet_result` | Snippet completed successfully | `{ snippet, result, duration, timestamp }` |
360| `code_mode:snippet_error` | Snippet execution failed | `{ snippet, error, duration, timestamp }` |
361| `snippet:registered` | New snippet saved via `register_snippet` | `{ id, name, description, timestamp }` |
362
363To render these events in your React app alongside Code Mode execution events, see [Showing Code Mode in the UI](./client-integration).
364
365## Tips
366
367- **Use a cheap model for selection.** The selection call only needs to match snippet names to conversation context — `gpt-4o-mini` or `claude-haiku-4-5` work well.
368- **Start without snippets.** Get Code Mode working first, then add `@tanstack/ai-code-mode-snippets` once you have tools that produce reusable patterns.
369- **Monitor the snippet count.** As the library grows, consider increasing `maxSnippetsInContext` or switching to the manual API where you control which snippets load.
370- **Newly registered snippets are available on the next message,** not in the current turn's tool list (unless using `ToolRegistry` with the high-level API, which adds them immediately).
371- **Snippets can call other snippets.** Inside the sandbox, both `external_*` and `snippet_*` functions are available. Set `dependsOn` when registering to document these relationships.
372
373## Next Steps
374
375- [Code Mode](./code-mode) — Core Code Mode setup and API reference
376- [Showing Code Mode in the UI](./client-integration) — Display execution progress in your React app
377- [Isolate Drivers](./code-mode-isolates) — Compare sandbox runtimes