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

live-test.ts

420 lines12.8 KB

1/**
2 * Live test for the snippets system
3 *
4 * Uses a real LLM adapter (OpenAI or Anthropic) to test:
5 * 1. First run: Create a snippet using code mode
6 * 2. Second run: Use the saved snippet
7 */
8​
9import { EventType, chat, maxIterations } from '@tanstack/ai'
10import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
11import { codeModeWithSnippets } from '../src/code-mode-with-snippets'
12import {
13 addNumbersTool,
14 createTestStorage,
15 logError,
16 logInfo,
17 logSection,
18 logStep,
19 logSuccess,
20 logWarning,
21} from './test-utils'
22import type { AnyTextAdapter, ModelMessage, StreamChunk } from '@tanstack/ai'
23import type { TestResult } from './test-utils'
24​
25/**
26 * Options for the live test
27 */
28export interface LiveTestOptions {
29 /**
30 * The adapter to use for the LLM
31 */
32 adapter: AnyTextAdapter
33​
34 /**
35 * Whether to log verbose output
36 */
37 verbose?: boolean
39​
40/**
41 * Run the live test with a real LLM
42 */
43export async function runLiveTest(
44 options: LiveTestOptions,
45): Promise<TestResult> {
46 const { adapter, verbose = false } = options
47​
48 logSection('Live Snippets Test')
49 logInfo(`Using adapter: ${adapter.name} with model: ${adapter.model}`)
50​
51 // Create shared storage that persists between phases
52 const storage = createTestStorage()
53 const driver = createNodeIsolateDriver({
54 memoryLimit: 128,
55 timeout: 60000, // Longer timeout for real LLM
56 })
57​
58 const result: TestResult = {
59 passed: false,
60 phases: {
61 phase1: { success: false },
62 phase2: { success: false },
63 },
64 snippetCreated: false,
65 snippetUsed: false,
66 }
67​
68 // =========================================================================
69 // Phase 1: First run - Create snippet using code mode
70 // =========================================================================
71​
72 logSection('Phase 1: Snippet Creation')
73 logStep(1, 'Running code mode with real LLM (no existing snippets)')
74​
75 try {
76 const messages1: Array<ModelMessage> = [
77 {
78 role: 'user',
79 content: `What is 5 + 3?
80​
81IMPORTANT INSTRUCTIONS:
821. Use the execute_typescript tool to call external_add_numbers({ a: 5, b: 3 }) to get the answer
832. After getting the result, use register_snippet to save a reusable snippet called "add_two_numbers" that wraps this pattern
843. The snippet should accept { a: number, b: number } as input and return the result from external_add_numbers
85​
86Please complete all three steps: execute the code, register the snippet, and tell me the answer.`,
87 },
88 ]
89​
90 // Get tools and system prompt with snippets integration
91 const { tools: tools1, systemPrompt: systemPrompt1 } =
92 await codeModeWithSnippets({
93 threadId: 'test-cli',
94 config: {
95 driver,
96 tools: [addNumbersTool],
97 timeout: 60000,
98 memoryLimit: 128,
99 },
100 adapter,
101 snippets: {
102 storage,
103 maxSnippetsInContext: 5,
104 },
105 messages: messages1,
106 })
107​
108 logInfo(
109 `Phase 1 tools available: ${tools1.map((t: any) => t.name).join(', ')}`,
110 )
111 if (verbose) {
112 logInfo(`System prompt:\n${systemPrompt1.substring(0, 500)}...`)
113 }
114​
115 // Run the chat
116 logStep(2, 'Executing chat with LLM')
117​
118 const stream1 = chat({
119 threadId: 'test-cli',
120 adapter,
121 messages: messages1,
122 tools: tools1 as any,
123 systemPrompts: [systemPrompt1],
124 agentLoopStrategy: maxIterations(15),
125 })
126​
127 let toolCallCount1 = 0
128 let executeTypescriptCalled = false
129 let registerSnippetCalled = false
130 let fullContent = ''
131​
132 for await (const chunk of stream1 as AsyncIterable<StreamChunk>) {
133 if (chunk.type === 'tool_call') {
134 toolCallCount1++
135 const toolName = chunk.toolCall.function.name
136 logInfo(`Tool called: ${toolName}`)
137 if (verbose) {
138 logInfo(
139 ` Arguments: ${chunk.toolCall.function.arguments.substring(0, 200)}...`,
140 )
141 }
142 if (toolName === 'execute_typescript') {
143 executeTypescriptCalled = true
144 }
145 if (toolName === 'register_snippet') {
146 registerSnippetCalled = true
147 }
148 } else if (chunk.type === 'tool_result') {
149 if (verbose) {
150 logInfo(`Tool result: ${chunk.content.substring(0, 200)}...`)
151 }
152 } else if (chunk.type === 'content') {
153 fullContent += chunk.delta
154 } else if (chunk.type === EventType.RUN_FINISHED) {
155 logInfo(`Phase 1 done: ${chunk.metadata?.tanstack?.finishReason}`)
156 }
157 }
158​
159 if (verbose && fullContent) {
160 logInfo(`LLM response: ${fullContent.substring(0, 500)}...`)
161 }
162​
163 // Verify snippet was created
164 const snippetIndex = await storage.loadIndex()
165 const snippetCreated = snippetIndex.some(
166 (s) => s.name === 'add_two_numbers',
167 )
168​
169 if (snippetCreated) {
170 result.snippetCreated = true
171 logSuccess('Snippet "add_two_numbers" was created successfully')
172​
173 // Log the created snippet
174 const snippet = await storage.get('add_two_numbers')
175 if (snippet && verbose) {
176 logInfo(`Snippet details:`)
177 logInfo(` Description: ${snippet.description}`)
178 logInfo(` Code: ${snippet.code.substring(0, 100)}...`)
179 }
180 } else {
181 logWarning(
182 'Snippet was not created - LLM may not have followed instructions',
183 )
184 }
185​
186 result.phases.phase1 = {
187 success: executeTypescriptCalled,
188 details: {
189 toolCallCount: toolCallCount1,
190 executeTypescriptCalled,
191 registerSnippetCalled,
192 snippetCreated,
193 snippetsInStorage: snippetIndex.length,
194 },
195 }
196​
197 if (result.phases.phase1.success) {
198 logSuccess('Phase 1 completed successfully')
199 } else {
200 logError('Phase 1 failed - execute_typescript was not called')
201 }
202 } catch (error) {
203 result.phases.phase1 = {
204 success: false,
205 error: error instanceof Error ? error.message : String(error),
206 }
207 logError(`Phase 1 error: ${result.phases.phase1.error}`)
208 }
209​
210 // =========================================================================
211 // Phase 2: Second run - Use the saved snippet (if created)
212 // =========================================================================
213​
214 logSection('Phase 2: Snippet Reuse')
215​
216 // Only run phase 2 if a snippet was created
217 if (!result.snippetCreated) {
218 logWarning('Skipping Phase 2 - no snippet was created in Phase 1')
219 result.phases.phase2 = {
220 success: false,
221 error: 'No snippet was created in Phase 1',
222 }
223 } else {
224 logStep(1, 'Running code mode with real LLM (snippet should be available)')
225​
226 try {
227 const messages2: Array<ModelMessage> = [
228 {
229 role: 'user',
230 content: `What is 10 + 20?
231​
232If you have a snippet called "add_two_numbers" available, please use it directly instead of execute_typescript.`,
233 },
234 ]
235​
236 // Get tools and system prompt with snippets integration
237 const {
238 tools: tools2,
239 systemPrompt: systemPrompt2,
240 selectedSnippets,
241 } = await codeModeWithSnippets({
242 threadId: 'test-cli',
243 config: {
244 driver,
245 tools: [addNumbersTool],
246 timeout: 60000,
247 memoryLimit: 128,
248 },
249 adapter,
250 snippets: {
251 storage,
252 maxSnippetsInContext: 5,
253 },
254 messages: messages2,
255 })
256​
257 logInfo(
258 `Phase 2 tools available: ${tools2.map((t: any) => t.name).join(', ')}`,
259 )
260 logInfo(
261 `Selected snippets: ${selectedSnippets.map((s) => s.name).join(', ') || 'none'}`,
262 )
263​
264 // Check if snippet is now available as a tool
265 const snippetToolAvailable = tools2.some(
266 (t: any) => t.name === 'add_two_numbers',
267 )
268 if (snippetToolAvailable) {
269 logSuccess('Snippet "add_two_numbers" is available as a tool')
270 } else {
271 logWarning(
272 'Snippet is not available as a tool (may not have been selected by LLM)',
273 )
274 }
275​
276 // Run the chat
277 logStep(2, 'Executing chat with LLM')
278​
279 const stream2 = chat({
280 threadId: 'test-cli',
281 adapter,
282 messages: messages2,
283 tools: tools2 as any,
284 systemPrompts: [systemPrompt2],
285 agentLoopStrategy: maxIterations(15),
286 })
287​
288 let toolCallCount2 = 0
289 let snippetCalled = false
290 let snippetExecutedSuccessfully = false
291 let snippetExecutionError: string | undefined
292 let executeTypescriptCalledPhase2 = false
293 let fullContent2 = ''
294​
295 for await (const chunk of stream2 as AsyncIterable<StreamChunk>) {
296 if (chunk.type === 'tool_call') {
297 toolCallCount2++
298 const toolName = chunk.toolCall.function.name
299 logInfo(`Tool called: ${toolName}`)
300 if (toolName === 'add_two_numbers') {
301 snippetCalled = true
302 }
303 if (toolName === 'execute_typescript') {
304 executeTypescriptCalledPhase2 = true
305 }
306 } else if (chunk.type === 'tool_result') {
307 // Check if this is the snippet result and if it succeeded
308 if (snippetCalled && chunk.toolCallId) {
309 // Check if the result contains an error
310 const resultContent = chunk.content
311 if (
312 resultContent.includes('error') ||
313 resultContent.includes('Error')
314 ) {
315 snippetExecutionError = resultContent.substring(0, 200)
316 logError(`Snippet execution failed: ${snippetExecutionError}`)
317 } else {
318 snippetExecutedSuccessfully = true
319 if (verbose) {
320 logInfo(`Snippet result: ${resultContent.substring(0, 200)}`)
321 }
322 }
323 }
324 } else if (chunk.type === 'content') {
325 fullContent2 += chunk.delta
326 } else if (chunk.type === EventType.RUN_FINISHED) {
327 logInfo(`Phase 2 done: ${chunk.metadata?.tanstack?.finishReason}`)
328 }
329 }
330​
331 if (verbose && fullContent2) {
332 logInfo(`LLM response: ${fullContent2.substring(0, 500)}...`)
333 }
334​
335 result.snippetUsed = snippetCalled && snippetExecutedSuccessfully
336​
337 // Consider phase 2 successful if either:
338 // 1. The snippet was called directly AND executed successfully, OR
339 // 2. The snippet wasn't available (selection issue) but execute_typescript worked
340 const phase2Success =
341 (snippetCalled && snippetExecutedSuccessfully) ||
342 executeTypescriptCalledPhase2
343​
344 result.phases.phase2 = {
345 success: phase2Success,
346 details: {
347 toolCallCount: toolCallCount2,
348 snippetCalled,
349 snippetExecutedSuccessfully,
350 snippetExecutionError,
351 executeTypescriptCalled: executeTypescriptCalledPhase2,
352 snippetToolAvailable,
353 selectedSnippetCount: selectedSnippets.length,
354 },
355 }
356​
357 if (snippetCalled && snippetExecutedSuccessfully) {
358 logSuccess(
359 'Phase 2 completed successfully - snippet was called and executed correctly!',
360 )
361 } else if (snippetCalled && !snippetExecutedSuccessfully) {
362 logError(
363 `Phase 2 failed - snippet was called but execution failed: ${snippetExecutionError}`,
364 )
365 } else if (executeTypescriptCalledPhase2) {
366 logWarning(
367 'Phase 2 completed but LLM used execute_typescript instead of the snippet',
368 )
369 } else {
370 logError('Phase 2 failed - no tool was called')
371 }
372 } catch (error) {
373 result.phases.phase2 = {
374 success: false,
375 error: error instanceof Error ? error.message : String(error),
376 }
377 logError(`Phase 2 error: ${result.phases.phase2.error}`)
378 }
379 }
380​
381 // =========================================================================
382 // Final Result
383 // =========================================================================
384​
385 logSection('Test Results')
386​
387 // For live tests, we're more lenient - consider it passed if Phase 1 succeeded
388 // since LLM behavior can vary
389 result.passed = result.phases.phase1.success
390​
391 if (result.passed) {
392 logSuccess('Test passed!')
393 logInfo(
394 `✓ execute_typescript used in Phase 1: ${result.phases.phase1.details?.executeTypescriptCalled}`,
395 )
396 logInfo(`✓ Snippet created: ${result.snippetCreated}`)
397 logInfo(`✓ Snippet used successfully in Phase 2: ${result.snippetUsed}`)
398 } else {
399 logError('Test failed')
400 if (!result.phases.phase1.success) {
401 logError(`Phase 1 (Code Mode): ${result.phases.phase1.error || 'Failed'}`)
402 }
403 if (!result.phases.phase2.success) {
404 const phase2Details = result.phases.phase2.details as
405 | Record<string, unknown>
406 | undefined
407 if (phase2Details?.snippetExecutionError) {
408 logError(
409 `Phase 2 (Snippet Reuse): Snippet execution failed - ${phase2Details.snippetExecutionError}`,
410 )
411 } else {
412 logError(
413 `Phase 2 (Snippet Reuse): ${result.phases.phase2.error || 'Failed'}`,
414 )
415 }
416 }
417 }
418​
419 return result