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

api.database-demo.ts

328 lines10.4 KB

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 }
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
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
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 }
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 }
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 })()
228​
229export const Route = createFileRoute(
230 '/_database-demo/api/database-demo' as any,
231)({
232 server: {
233 handlers: {
234 POST: async ({ request }) => {
235 const requestSignal = request.signal
236 if (requestSignal.aborted) {
237 return new Response(null, { status: 499 })
238 }
239​
240 const abortController = new AbortController()
241 const body = await request.json()
242 const { messages, data } = body
243​
244 const provider: Provider = data?.provider || 'anthropic'
245 const model: string | undefined = data?.model
246 const useCodeMode: boolean = data?.useCodeMode !== false
247 const withSnippets: boolean = data?.withSnippets === true
248​
249 const rawAdapter = getAdapter(provider, model)
250 const { adapter: instrumentedAdapter } = instrumentAdapter(rawAdapter)
251​
252 try {
253 let tools: Array<AnyServerTool>
254 let systemPrompts: Array<string>
255​
256 if (useCodeMode) {
257 const { tool, systemPrompt, driver } = await getCodeModeTools()
258 tools = [tool, getSchemaInfoTool]
259 systemPrompts = [DATABASE_DEMO_SYSTEM_PROMPT, systemPrompt]
260​
261 if (withSnippets) {
262 const { snippetTools, snippetsPrompt } =
263 await getSnippetToolsAndPrompt(driver)
264 tools = [
265 tool,
266 getSchemaInfoTool,
267 ...getSnippetManagementTools(),
268 ...snippetTools,
269 ]
270 systemPrompts = [
271 DATABASE_DEMO_SYSTEM_PROMPT,
272 systemPrompt,
273 snippetsPrompt,
274 ]
275 }
276 } else {
277 tools = [...databaseTools]
278 systemPrompts = [DATABASE_DEMO_SYSTEM_PROMPT]
279 }
280​
281 const stream = chat({
282 adapter: instrumentedAdapter,
283 messages,
284 tools,
285 systemPrompts,
286 agentLoopStrategy: maxIterations(15),
287 abortController,
288 modelOptions: maxTokensModelOptions(rawAdapter, 8192),
289 })
290​
291 const instrumentedStream = wrapWithTimingEvents(stream, rawAdapter)
292 const sseStream = toServerSentEventsStream(
293 instrumentedStream,
294 abortController,
295 )
296​
297 return new Response(sseStream, {
298 headers: {
299 'Content-Type': 'text/event-stream',
300 'Cache-Control': 'no-cache',
301 Connection: 'keep-alive',
302 },
303 })
304 } catch (error: unknown) {
305 console.error('[API Database Demo Route] Error:', error)
306​
307 if (
308 (error instanceof Error && error.name === 'AbortError') ||
309 abortController.signal.aborted
310 ) {
311 return new Response(null, { status: 499 })
312 }
313​
314 return new Response(
315 JSON.stringify({
316 error:
317 error instanceof Error ? error.message : 'An error occurred',
318 }),
319 {
320 status: 500,
321 headers: { 'Content-Type': 'application/json' },
322 },
323 )
324 }
325 },
326 },
327 },
328})