Open History to see the last commit
1import { resolve } from 'node:path'
2import { fileURLToPath } from 'node:url'
3import { createFileRoute } from '@tanstack/react-router'
4import { chat, maxIterations, toServerSentEventsStream } from '@tanstack/ai'
5import { createCodeMode } from '@tanstack/ai-code-mode'
6import {
7 createAlwaysTrustedStrategy,
8 createSnippetManagementTools,
9 createSnippetsSystemPrompt,
10 snippetsToTools,
11} from '@tanstack/ai-code-mode-snippets'
12import { createFileSnippetStorage } from '@tanstack/ai-code-mode-snippets/storage'
13import { anthropicText } from '@tanstack/ai-anthropic'
14import { openaiText } from '@tanstack/ai-openai'
15import { geminiText } from '@tanstack/ai-gemini'
16import type { AnyServerTool, AnyTextAdapter, StreamChunk } from '@tanstack/ai'
17import type { IsolateDriver } from '@tanstack/ai-code-mode'
18
19import { databaseTools, getSchemaInfoTool } from '@/lib/tools/database-tools'
20import { maxTokensModelOptions } from '@/lib/max-tokens-model-options'
21
22type Provider = 'anthropic' | 'openai' | 'gemini'
23
24function getAdapter(provider: Provider, model?: string): AnyTextAdapter {
25 switch (provider) {
26 case 'openai':
27 return openaiText((model || 'gpt-4o') as 'gpt-4o')
28 case 'gemini':
29 return geminiText((model || 'gemini-2.5-flash') as 'gemini-2.5-flash')
30 case 'anthropic':
31 default:
32 return anthropicText((model || 'claude-haiku-4-5') as 'claude-haiku-4-5')
33 }
34}
35
36const DATABASE_DEMO_SYSTEM_PROMPT = `You are a helpful data analyst assistant with access to an in-memory database containing three tables: customers, products, and purchases.
37
38## Available Tools
39
40You have two tools to work with:
41
421. **getSchemaInfo** — Get the schema (column names and types) and row counts for one or all tables. Call this first if you're unsure what columns are available.
43
442. **queryTable** — Query any table with optional filtering, column selection, sorting, and limiting. Supports exact-match \`where\` conditions.
45
46## Tables Overview
47
48- **customers** — Customer records (id, name, email, city, joined)
49- **products** — Product catalog (id, name, category, price, stock)
50- **purchases** — Purchase records linking customers to products (id, customer_id, product_id, quantity, total, purchased_at)
51
52## Strategy
53
54- For questions that need data from multiple tables, make multiple queryTable calls and join the data yourself.
55- For aggregation (sums, averages, counts), query the raw data and compute the result.
56- Always present results clearly, using tables or lists when appropriate.
57- If a question is ambiguous, make reasonable assumptions and state them.`
58
59// Lazy initialization
60let codeModeCache: {
61 tool: ReturnType<typeof createCodeMode>['tool']
62 systemPrompt: string
63 driver: IsolateDriver
64} | null = null
65
66async function getCodeModeTools() {
67 if (!codeModeCache) {
68 const { createIsolateDriver } = await import('@/lib/create-isolate-driver')
69 const driver = await createIsolateDriver()
70 const { tool, systemPrompt } = createCodeMode({
71 driver,
72 tools: databaseTools,
73 timeout: 60000,
74 memoryLimit: 128,
75 })
76 codeModeCache = { tool, systemPrompt, driver }
77 }
78 return codeModeCache
79}
80
81// --- Snippets storage ---
82
83const __dirname = fileURLToPath(new URL('.', import.meta.url))
84const snippetsDir = resolve(__dirname, '../../../.db-snippets')
85const trustStrategy = createAlwaysTrustedStrategy()
86const snippetStorage = createFileSnippetStorage({
87 directory: snippetsDir,
88 trustStrategy,
89})
90
91let snippetManagementToolsCache: ReturnType<
92 typeof createSnippetManagementTools
93> | null = null
94
95function getSnippetManagementTools() {
96 if (!snippetManagementToolsCache) {
97 snippetManagementToolsCache = createSnippetManagementTools({
98 storage: snippetStorage,
99 trustStrategy,
100 })
101 }
102 return snippetManagementToolsCache
103}
104
105const SNIPPET_REGISTRATION_PROMPT = `## Snippet Registration — MANDATORY
106
107After every successful \`execute_typescript\` call you MUST register the code as a reusable snippet using \`register_snippet\` — unless an identical snippet already exists.
108
109Rules:
110- \`name\`: descriptive snake_case (e.g. \`revenue_by_city_and_category\`)
111- \`code\`: the TypeScript code, parameterised with an \`input\` variable where useful
112- \`inputSchema\` / \`outputSchema\`: valid JSON Schema **strings**
113- If a snippet with the same name exists, skip registration
114
115This is not optional — snippet registration is a core part of your workflow.`
116
117async function getSnippetToolsAndPrompt(driver: IsolateDriver): Promise<{
118 snippetTools: Array<AnyServerTool>
119 snippetsPrompt: string
120}> {
121 const allSnippets = await snippetStorage.loadAll()
122 const snippetIndex = await snippetStorage.loadIndex()
123
124 const snippetTools =
125 allSnippets.length > 0
126 ? snippetsToTools({
127 snippets: allSnippets,
128 driver,
129 tools: databaseTools,
130 storage: snippetStorage,
131 timeout: 60000,
132 memoryLimit: 128,
133 })
134 : []
135
136 const libraryPrompt = createSnippetsSystemPrompt({
137 selectedSnippets: allSnippets,
138 totalSnippetCount: snippetIndex.length,
139 snippetsAsTools: true,
140 })
141
142 const snippetsPrompt = libraryPrompt + '\n\n' + SNIPPET_REGISTRATION_PROMPT
143
144 return { snippetTools, snippetsPrompt }
145}
146
147// --- Instrumentation helpers ---
148
149function instrumentAdapter(adapter: AnyTextAdapter): {
150 adapter: AnyTextAdapter
151} {
152 const baseChatStream = adapter.chatStream.bind(adapter)
153 let llmCallCount = 0
154 let totalContextBytes = 0
155 const textEncoder = new TextEncoder()
156
157 const instrumented: AnyTextAdapter = {
158 ...adapter,
159 chatStream: (options) => {
160 llmCallCount += 1
161 let contextBytes = 0
162 try {
163 contextBytes = textEncoder.encode(
164 JSON.stringify(options.messages ?? []),
165 ).length
166 } catch {
167 contextBytes = 0
168 }
169 totalContextBytes += contextBytes
170 const averageContextBytes =
171 llmCallCount > 0 ? Math.round(totalContextBytes / llmCallCount) : 0
172 const stream = baseChatStream(options)
173 async function* instrumentedStream(): AsyncGenerator<StreamChunk> {
174 yield {
175 type: 'CUSTOM',
176 model: adapter.model,
177 timestamp: Date.now(),
178 name: 'db_demo:llm_call',
179 value: {
180 count: llmCallCount,
181 contextBytes,
182 totalContextBytes,
183 averageContextBytes,
184 },
185 } as StreamChunk
186 for await (const chunk of stream) {
187 yield chunk
188 }
189 }
190 return instrumentedStream()
191 },
192 }
193
194 return { adapter: instrumented }
195}
196
197function wrapWithTimingEvents(
198 stream: AsyncIterable<StreamChunk>,
199 adapter: AnyTextAdapter,
200): AsyncGenerator<StreamChunk> {
201 const requestStartTimeMs = Date.now()
202 return (async function* (): AsyncGenerator<StreamChunk> {
203 yield {
204 type: 'CUSTOM',
205 model: adapter.model,
206 timestamp: requestStartTimeMs,
207 name: 'db_demo:chat_start',
208 value: { startTimeMs: requestStartTimeMs },
209 } as StreamChunk
210 for await (const chunk of stream) {
211 if (chunk.type === 'RUN_FINISHED') {
212 const endTimeMs = Date.now()
213 yield {
214 type: 'CUSTOM',
215 model: adapter.model,
216 timestamp: endTimeMs,
217 name: 'db_demo:chat_end',
218 value: {
219 endTimeMs,
220 durationMs: endTimeMs - requestStartTimeMs,
221 },
222 } as StreamChunk
223 }
224 yield chunk
225 }
226 })()
227}
228
229export const Route = createFileRoute('/_database-demo/api/database-demo')({
230 server: {
231 handlers: {
232 POST: async ({ request }) => {
233 const requestSignal = request.signal
234 if (requestSignal.aborted) {
235 return new Response(null, { status: 499 })
236 }
237
238 const abortController = new AbortController()
239 const body = await request.json()
240 const { messages, forwardedProps: data } = body
241
242 const provider: Provider = data?.provider || 'anthropic'
243 const model: string | undefined = data?.model
244 const useCodeMode: boolean = data?.useCodeMode !== false
245 const withSnippets: boolean = data?.withSnippets === true
246
247 const rawAdapter = getAdapter(provider, model)
248 const { adapter: instrumentedAdapter } = instrumentAdapter(rawAdapter)
249
250 try {
251 let tools: Array<AnyServerTool>
252 let systemPrompts: Array<string>
253
254 if (useCodeMode) {
255 const { tool, systemPrompt, driver } = await getCodeModeTools()
256 tools = [tool, getSchemaInfoTool]
257 systemPrompts = [DATABASE_DEMO_SYSTEM_PROMPT, systemPrompt]
258
259 if (withSnippets) {
260 const { snippetTools, snippetsPrompt } =
261 await getSnippetToolsAndPrompt(driver)
262 tools = [
263 tool,
264 getSchemaInfoTool,
265 ...getSnippetManagementTools(),
266 ...snippetTools,
267 ]
268 systemPrompts = [
269 DATABASE_DEMO_SYSTEM_PROMPT,
270 systemPrompt,
271 snippetsPrompt,
272 ]
273 }
274 } else {
275 tools = [...databaseTools]
276 systemPrompts = [DATABASE_DEMO_SYSTEM_PROMPT]
277 }
278
279 const stream = chat({
280 threadId: body.threadId,
281 adapter: instrumentedAdapter,
282 messages,
283 tools,
284 systemPrompts,
285 agentLoopStrategy: maxIterations(15),
286 abortController,
287 modelOptions: maxTokensModelOptions(rawAdapter, 8192),
288 })
289
290 const instrumentedStream = wrapWithTimingEvents(stream, rawAdapter)
291 const sseStream = toServerSentEventsStream(
292 instrumentedStream,
293 abortController,
294 )
295
296 return new Response(sseStream, {
297 headers: {
298 'Content-Type': 'text/event-stream',
299 'Cache-Control': 'no-cache',
300 Connection: 'keep-alive',
301 },
302 })
303 } catch (error: unknown) {
304 console.error('[API Database Demo Route] Error:', error)
305
306 if (
307 (error instanceof Error && error.name === 'AbortError') ||
308 abortController.signal.aborted
309 ) {
310 return new Response(null, { status: 499 })
311 }
312
313 return new Response(
314 JSON.stringify({
315 error:
316 error instanceof Error ? error.message : 'An error occurred',
317 }),
318 {
319 status: 500,
320 headers: { 'Content-Type': 'application/json' },
321 },
322 )
323 }
324 },
325 },
326 },
327})