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

code-mode-with-snippets.ts

210 lines6.7 KB

1import {
2 createCodeModeSystemPrompt,
3 createCodeModeTool,
4 toolsToBindings,
5} from '@tanstack/ai-code-mode'
6import { createToolRegistry } from '@tanstack/ai'
7import { selectRelevantSnippets } from './select-relevant-snippets'
8import { createSnippetManagementTools } from './create-snippet-management-tools'
9import { createSnippetsSystemPrompt } from './create-snippets-system-prompt'
10import { snippetsToTools } from './snippets-to-tools'
11import type {
12 CodeModeWithSnippetsOptions,
13 CodeModeWithSnippetsResult,
14 Snippet,
15} from './types'
16import type { ToolBinding } from '@tanstack/ai-code-mode'
17​
18export type { CodeModeWithSnippetsOptions, CodeModeWithSnippetsResult }
19​
20/**
21 * Create Code Mode tools and system prompt with snippets integration.
22 *
23 * This function:
24 * 1. Loads the snippet index from storage
25 * 2. Uses a cheap/fast LLM to select relevant snippets based on conversation context
26 * 3. Creates the execute_typescript tool with dynamic snippet bindings
27 * 4. Creates snippet management tools (search, get, register)
28 * 5. Generates system prompts documenting available snippets
29 * 6. Returns a ToolRegistry that allows dynamic snippet additions mid-stream
30 *
31 * @example
32 * ```typescript
33 * // Node-only file storage lives behind the `/storage` subpath:
34 * import { createFileSnippetStorage } from '@tanstack/ai-code-mode-snippets/storage'
35 *
36 * const { toolsRegistry, systemPrompt, selectedSnippets } = await codeModeWithSnippets({
37 * config: {
38 * driver: createNodeIsolateDriver(),
39 * tools: allTools,
40 * timeout: 60000,
41 * },
42 * adapter: openaiText('gpt-4o-mini'), // Cheap model for selection
43 * snippets: {
44 * storage: createFileSnippetStorage('./.snippets'),
45 * maxSnippetsInContext: 5,
46 * },
47 * messages,
48 * });
49 *
50 * const stream = chat({
51 * adapter: openaiText('gpt-4o'), // Main model
52 * toolRegistry: toolsRegistry, // Dynamic tool registry
53 * messages,
54 * systemPrompts: [BASE_PROMPT, systemPrompt],
55 * });
56 * ```
57 */
58export async function codeModeWithSnippets({
59 config,
60 adapter,
61 snippets,
62 messages,
63 snippetsAsTools = true,
64}: CodeModeWithSnippetsOptions): Promise<CodeModeWithSnippetsResult> {
65 const { storage, maxSnippetsInContext = 5 } = snippets
66​
67 // 1. Load the snippet index (lightweight metadata only)
68 const snippetIndex = await storage.loadIndex()
69​
70 // 2. Use adapter to select relevant snippets based on transcript
71 const selectedSnippets = await selectRelevantSnippets({
72 adapter,
73 messages,
74 snippetIndex,
75 maxSnippets: maxSnippetsInContext,
76 storage,
77 })
78​
79 // Pre-compute bindings from base tools (shared across snippet executions)
80 const baseBindings = toolsToBindings(config.tools, 'external_')
81​
82 // 3. Create the execute_typescript tool with dynamic snippet bindings
83 const codeModeTool = createCodeModeTool({
84 ...config,
85 // Dynamic snippet bindings - fetched at execution time
86 getSnippetBindings: async () => {
87 // Get all snippets from storage (includes newly registered ones)
88 const allSnippets = await storage.loadAll()
89 // Convert to bindings with snippet_ prefix
90 const snippetBindings: Record<string, ToolBinding> = {}
91 for (const snippet of allSnippets) {
92 // Create a simple binding that executes the snippet code
93 snippetBindings[`snippet_${snippet.name}`] = {
94 name: `snippet_${snippet.name}`,
95 description: snippet.description,
96 inputSchema: snippet.inputSchema,
97 outputSchema: snippet.outputSchema,
98 execute: async (input: unknown) => {
99 // This is a simplified execution - the full snippetToTool handles events
100 const wrappedCode = `const input = ${JSON.stringify(input)};\n${snippet.code}`
101 const { stripTypeScript, createEventAwareBindings } =
102 await import('@tanstack/ai-code-mode')
103 const strippedCode = await stripTypeScript(wrappedCode)
104 const context = await config.driver.createContext({
105 bindings: createEventAwareBindings(baseBindings, () => {}),
106 timeout: config.timeout,
107 ...(config.memoryLimit !== undefined && {
108 memoryLimit: config.memoryLimit,
109 }),
110 })
111 try {
112 const result = await context.execute(strippedCode)
113 if (!result.success) {
114 throw new Error(
115 result.error?.message || 'Snippet execution failed',
116 )
117 }
118 return result.value
119 } finally {
120 await context.dispose()
121 }
122 },
123 }
124 }
125 return snippetBindings
126 },
127 })
128​
129 // 4. Create a mutable tool registry
130 const registry = createToolRegistry()
131​
132 // 5. Add the execute_typescript tool to the registry
133 registry.add(codeModeTool)
134​
135 // 6. Create snippet management tools (they need access to the registry)
136 const snippetManagementTools = createSnippetManagementTools({
137 storage,
138 registry,
139 config,
140 baseBindings,
141 })
142​
143 for (const tool of snippetManagementTools) {
144 registry.add(tool)
145 }
146​
147 // 7. Convert selected snippets to direct tools and add to registry (if enabled)
148 if (snippetsAsTools && selectedSnippets.length > 0) {
149 const snippetToolsList = snippetsToTools({
150 snippets: selectedSnippets,
151 driver: config.driver,
152 tools: config.tools,
153 storage,
154 timeout: config.timeout,
155 memoryLimit: config.memoryLimit,
156 })
157​
158 for (const snippetTool of snippetToolsList) {
159 registry.add(snippetTool)
160 }
161 }
162​
163 // 8. Generate combined system prompt
164 const basePrompt = createCodeModeSystemPrompt(config)
165 const snippetsPrompt = createSnippetsSystemPrompt({
166 selectedSnippets,
167 totalSnippetCount: snippetIndex.length,
168 snippetsAsTools,
169 })
170 const systemPrompt = basePrompt + '\n\n' + snippetsPrompt
171​
172 return {
173 toolsRegistry: registry,
174 systemPrompt,
175 selectedSnippets,
176 }
178​
179/**
180 * Create a Code Mode tool configuration extended with snippets.
181 * This is an alternative to codeModeWithSnippets that returns
182 * a config object instead of directly creating tools.
183 *
184 * Useful when you want more control over the tool creation process.
185 */
186export function createCodeModeWithSnippetsConfig({
187 config,
188 selectedSnippets,
189 storage,
190}: {
191 config: CodeModeWithSnippetsOptions['config']
192 selectedSnippets: Array<Snippet>
193 storage: CodeModeWithSnippetsOptions['snippets']['storage']
194}) {
195 // Create snippet tools for direct calling
196 const snippetToolsList = snippetsToTools({
197 snippets: selectedSnippets,
198 driver: config.driver,
199 tools: config.tools,
200 storage,
201 timeout: config.timeout,
202 memoryLimit: config.memoryLimit,
203 })
204​
205 return {
206 ...config,
207 snippetTools: snippetToolsList,
208 selectedSnippets,
209 }