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

code-mode-with-snippets.md

357 lines13.9 KB

1---
2title: Code Mode with Snippets
3id: code-mode-with-snippets
4order: 3
5description: "Let Code Mode save working code as named snippets in storage, then call them again on later requests."
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​
17A snippet is a TypeScript function you put in the Code Mode prompt. The model calls that function instead of writing the same program again.
18​
19Snippets let the model save working code under a name. On later requests, the saved snippets load from storage, and the model calls them as tools.
20​
21> [!NOTE]
22> These snippets are runtime code that the chat model saves. To teach your coding assistant (Claude Code, Cursor) how TanStack AI works, see [Agent Skills (TanStack Intent)](../getting-started/agent-skills).
23​
24## Quick setup
25​
26You need the route from the [Code Mode quick setup](./code-mode#quick-setup) first.
27​
281. Install the snippets package:
29​
30<!-- ::start:tabs variant="package-manager" mode="install" -->
31​
32react: @tanstack/ai-code-mode-snippets
33vue: @tanstack/ai-code-mode-snippets
34solid: @tanstack/ai-code-mode-snippets
35svelte: @tanstack/ai-code-mode-snippets
36preact: @tanstack/ai-code-mode-snippets
37angular: @tanstack/ai-code-mode-snippets
38vanilla: @tanstack/ai-code-mode-snippets
39octane: @tanstack/ai-code-mode-snippets
40​
41<!-- ::end:tabs -->
42​
432. Replace `createCodeMode` in your route with `codeModeWithSnippets`. It needs a storage and a cheap model that picks the snippets for each request:
44​
45```typescript
46// app/api/chat/route.ts (Next.js). Any route that takes a Request works.
47import {
48 chat,
49 chatParamsFromRequest,
50 convertMessagesToModelMessages,
51 maxIterations,
52 toServerSentEventsResponse,
53 toolDefinition,
54} from '@tanstack/ai'
55import { codeModeWithSnippets } from '@tanstack/ai-code-mode-snippets'
56import { createFileSnippetStorage } from '@tanstack/ai-code-mode-snippets/storage'
57import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
58import { openaiText } from '@tanstack/ai-openai'
59import { z } from 'zod'
60​
61const fetchWeather = toolDefinition({
62 name: 'fetchWeather',
63 description: 'Get current 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 temperature: location.length + 10,
68 condition: 'sunny',
69}))
70​
71const storage = createFileSnippetStorage({ directory: './.snippets' })
72const driver = createNodeIsolateDriver()
73​
74export async function POST(request: Request) {
75 const { messages, threadId, runId } = await chatParamsFromRequest(request)
76​
77 const { toolsRegistry, systemPrompt } = await codeModeWithSnippets({
78 config: { driver, tools: [fetchWeather] },
79 adapter: openaiText('gpt-5.4-mini'), // cheap model that picks snippets
80 snippets: { storage, maxSnippetsInContext: 5 },
81 messages: convertMessagesToModelMessages(messages),
82 threadId,
83 })
84​
85 const stream = chat({
86 adapter: openaiText('gpt-6.1-sol'), // strong model for the real work
87 systemPrompts: ['You are a helpful weather assistant.', systemPrompt],
88 tools: toolsRegistry.getTools(),
89 messages,
90 threadId,
91 runId,
92 agentLoopStrategy: maxIterations(15),
93 })
94​
95 return toServerSentEventsResponse(stream)
97```
98​
993. Send "Compare the weather in Tokyo and Paris. Save the code as a snippet."
100​
1014. Look in `./.snippets/`. It holds a new folder with `code.ts` and `meta.json`.
102​
1035. Start a new chat and ask the same kind of question. The cheap model picks the saved snippet, and the main model calls it as a tool instead of writing the code again.
104​
105## How it works
106​
107Each request goes through these steps:
108​
1091. `codeModeWithSnippets` loads the snippet index. The index holds names and descriptions, with no code.
1102. The cheap model reads the last 5 messages and the index, then picks the snippets that match.
1113. The registry gets the Code Mode tool, the snippet management tools, and one tool for each picked snippet.
1124. The strong model in `chat()` can call a snippet tool, write new code with `execute_typescript`, or save new code with `register_snippet`.
113​
114If storage is empty or there are no messages, step 2 makes no model call.
115​
116The registry holds these tools:
117​
118- `execute_typescript`: the Code Mode sandbox. Inside it, every saved snippet is also a `snippet_<name>` function.
119- `search_snippets`: searches the library by query and returns the snippet metadata.
120- `get_snippet`: returns one snippet in full, code included.
121- `register_snippet`: saves working code as a new snippet.
122- One tool for each picked snippet. Its description starts with `[SNIPPET]`.
123​
124A new snippet is callable inside `execute_typescript` right away, as `snippet_<name>`. It shows up as a direct tool on the next request.
125​
126## Pick a storage
127​
128- **`createFileSnippetStorage`:** saves snippets to disk. It imports `node:fs` and `node:path`, so it is only on the `@tanstack/ai-code-mode-snippets/storage` subpath. Use it on Node.
129- **`createMemorySnippetStorage`:** keeps snippets in memory. It has no `node:fs` dependency, so the package root exports it, and it runs in Workers and browsers. Use it for tests, demos, and the edge.
130​
131```typescript
132import { createMemorySnippetStorage } from '@tanstack/ai-code-mode-snippets'
133​
134const storage = createMemorySnippetStorage()
135```
136​
137The memory storage is also on the `/storage` subpath.
138​
139## Advanced
140​
141### Pick the snippets yourself
142​
143`codeModeWithSnippets` asks a model to pick snippets. To skip that model call, load the snippets yourself and build the tools with the lower-level functions. The `ts-code-mode-web` example uses this approach.
144​
145This example loads every snippet. It uses the `fetchWeather` tool from the quick setup, moved to `./tools`:
146​
147```typescript
148import {
149 chat,
150 chatParamsFromRequest,
151 maxIterations,
152 toServerSentEventsResponse,
153} from '@tanstack/ai'
154import { createCodeMode } from '@tanstack/ai-code-mode'
155import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
156import {
157 createAlwaysTrustedStrategy,
158 createSnippetManagementTools,
159 createSnippetsSystemPrompt,
160 snippetsToTools,
161} from '@tanstack/ai-code-mode-snippets'
162import { createFileSnippetStorage } from '@tanstack/ai-code-mode-snippets/storage'
163import { openaiText } from '@tanstack/ai-openai'
164import { fetchWeather } from './tools'
165​
166const trustStrategy = createAlwaysTrustedStrategy()
167const storage = createFileSnippetStorage({
168 directory: './.snippets',
169 trustStrategy,
170})
171const driver = createNodeIsolateDriver()
172​
173export async function POST(request: Request) {
174 const { messages, threadId, runId } = await chatParamsFromRequest(request)
175​
176 // 1. The Code Mode tool and prompt
177 const { tool: codeModeTool, systemPrompt: codeModePrompt } = createCodeMode({
178 driver,
179 tools: [fetchWeather],
180 })
181​
182 // 2. Load every snippet and turn each one into a tool
183 const allSnippets = await storage.loadAll()
184 const snippetIndex = await storage.loadIndex()
185 const snippetTools = snippetsToTools({
186 snippets: allSnippets,
187 driver,
188 tools: [fetchWeather],
189 storage,
190 })
191​
192 // 3. The search, get, and register tools
193 const managementTools = createSnippetManagementTools({
194 storage,
195 trustStrategy,
196 })
197​
198 // 4. The prompt that documents the snippet library
199 const snippetsPrompt = createSnippetsSystemPrompt({
200 selectedSnippets: allSnippets,
201 totalSnippetCount: snippetIndex.length,
202 snippetsAsTools: true,
203 })
204​
205 const stream = chat({
206 adapter: openaiText('gpt-6.1-sol'),
207 tools: [codeModeTool, ...managementTools, ...snippetTools],
208 messages,
209 threadId,
210 runId,
211 systemPrompts: ['You are a helpful assistant.', codeModePrompt, snippetsPrompt],
212 agentLoopStrategy: maxIterations(15),
213 })
214​
215 return toServerSentEventsResponse(stream)
217```
218​
219`snippetsToTools` also takes `timeout` (default `30000`) and `memoryLimit` (default `128`).
220​
221### What `codeModeWithSnippets` takes and returns
222​
223Options:
224​
225| Option | Type | Description |
226|--------|------|-------------|
227| `config` | `CodeModeToolConfig` | The same options as [`createCodeMode`](./code-mode#createcodemode-options). |
228| `adapter` | text adapter | The model that picks snippets. A cheap, fast model is enough. |
229| `snippets.storage` | `SnippetStorage` | Where snippets live. |
230| `snippets.maxSnippetsInContext` | `number` | Most snippets to load for one request. Default: `5`. |
231| `messages` | `Array<ModelMessage>` | The conversation, for snippet selection. |
232| `snippetsAsTools` | `boolean` | Exposes picked snippets as direct tools. Default: `true`. |
233​
234Return value:
235​
236| Property | Type | Description |
237|----------|------|-------------|
238| `toolsRegistry` | `ToolRegistry` | All the tools. Give them to `chat()` with `tools: toolsRegistry.getTools()`. |
239| `systemPrompt` | `string` | The Code Mode prompt plus the snippet library docs. |
240| `selectedSnippets` | `Array<Snippet>` | The snippets that the selection model picked. |
241​
242### How selection works
243​
244On each request, `selectRelevantSnippets`:
245​
2461. Takes the last 5 messages.
2472. Builds a catalog from the index: name, description, and the first usage hint of each snippet.
2483. Asks the adapter for a JSON array of matching snippet names, with at most `maxSnippetsInContext` names.
2494. Loads the full snippets for those names.
250​
251If the model returns invalid JSON, the selection is empty. The request continues with no preloaded snippets, and the model can still search and use snippets with the management tools.
252​
253### Snippets as tools or as sandbox functions
254​
255`snippetsAsTools` (default `true`) controls how the model calls a picked snippet:
256​
257| Mode | How the model calls a snippet | Good | Less good |
258|------|-------------------------------|------|-----------|
259| As tools (`true`) | A direct tool call to the snippet | Simpler for the model. Shows in the tool-call UI. Validates the input. | One tool per snippet in the tool list. |
260| As sandbox functions (`false`) | `await snippet_fetch_data({ ... })` inside `execute_typescript` | Snippets combine in code. Fewer top-level tools. | The model must write code to use them. |
261​
262With `true`, the system prompt documents each snippet with its schema, usage hints, and an example call. With `false`, snippets appear as typed `snippet_*` functions in the sandbox type stubs.
263​
264### Snippet lifecycle
265​
266**Saving.** After useful code runs in `execute_typescript`, the system prompt tells the model to call `register_snippet` with these fields:
267​
268- `name`: a snake_case name. It becomes the tool name.
269- `description`: what the snippet does.
270- `code`: TypeScript that reads an `input` variable.
271- `inputSchema` and `outputSchema`: JSON Schema strings.
272- `usageHints`: when to use the snippet.
273- `dependsOn`: other snippets that this one calls.
274​
275**Running.** When the model calls a snippet tool:
276​
2771. The snippet code gets `const input = <serialized input>;` in front of it.
2782. The TypeScript syntax is stripped.
2793. A fresh sandbox context starts with the `external_*` bindings.
2804. The code runs and returns its result.
2815. The success or failure count updates in the background.
282​
283With `codeModeWithSnippets`, code in `execute_typescript` can call both `external_*` and `snippet_*` functions. The code of a snippet tool gets only the `external_*` functions.
284​
285### Storage
286​
287Both storages implement `SnippetStorage`:
288​
289| Method | Description |
290|--------|-------------|
291| `loadIndex()` | Loads the metadata of all snippets, with no code. |
292| `loadAll()` | Loads all snippets, code included. |
293| `get(name)` | Gets one snippet by name. |
294| `save(snippet)` | Creates or updates a snippet. |
295| `delete(name)` | Removes a snippet. |
296| `search(query, options?)` | Searches snippets by text. |
297| `updateStats(name, success)` | Records one execution result, for trust tracking. |
298​
299The file storage writes this layout:
300​
301```text
302.snippets/
303 _index.json # Small catalog for fast loading
304 fetch_github_stats/
305 meta.json # Description, schemas, hints, stats
306 code.ts # TypeScript source
307 compare_npm_packages/
308 meta.json
309 code.ts
310```
311​
312`createFileSnippetStorage` takes `directory` and an optional `trustStrategy` (default: `createDefaultTrustStrategy()`).
313​
314### Trust strategies
315​
316A snippet starts untrusted and earns trust with successful runs. The trust level is metadata only. It does not block a run.
317​
318```typescript group=code-mode-with-snippets
319import {
320 createDefaultTrustStrategy,
321 createAlwaysTrustedStrategy,
322 createRelaxedTrustStrategy,
323 createCustomTrustStrategy,
324} from '@tanstack/ai-code-mode-snippets'
325```
326​
327| Strategy | Starts at | Provisional | Trusted |
328|----------|-----------|-------------|---------|
329| Default | `untrusted` | 10+ runs, 90%+ success | 100+ runs, 95%+ success |
330| Relaxed | `untrusted` | 3+ runs, 80%+ success | 10+ runs, 90%+ success |
331| Always trusted | `trusted` | n/a | n/a |
332| Custom | You choose | You choose | You choose |
333​
334```typescript group=code-mode-with-snippets
335const strategy = createCustomTrustStrategy({
336 initialLevel: 'untrusted',
337 provisionalThreshold: { executions: 5, successRate: 0.85 },
338 trustedThreshold: { executions: 50, successRate: 0.95 },
339})
340```
341​
342### Custom events
343​
344Snippets send these events, next to the [Code Mode events](./code-mode#custom-events). [Showing Code Mode in the UI](./client-integration) shows how to catch them.
345​
346| Event | When | Payload |
347|-------|------|---------|
348| `code_mode:snippet_call` | A snippet tool starts | `{ snippet, input, timestamp }` |
349| `code_mode:snippet_result` | A snippet tool succeeds | `{ snippet, result, duration, timestamp }` |
350| `code_mode:snippet_error` | A snippet tool fails | `{ snippet, error, duration, timestamp }` |
351| `snippet:registered` | `register_snippet` saves a new snippet | `{ id, name, description, timestamp }` |
352​
353### Tips
354​
355- **Use a cheap model for selection.** It only matches snippet names to the conversation. `gpt-5.4-mini` or `claude-haiku-5-5` are enough.
356- **Start with no snippets.** Get Code Mode working first. When your tools produce patterns that repeat, add snippets.
357- **Watch the snippet count.** When the library grows, increase `maxSnippetsInContext`, or pick the snippets yourself.