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

live-test.ts

416 lines12.7 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 config: {
94 driver,
95 tools: [addNumbersTool],
96 timeout: 60000,
97 memoryLimit: 128,
98 },
99 adapter,
100 snippets: {
101 storage,
102 maxSnippetsInContext: 5,
103 },
104 messages: messages1,
105 })
106​
107 logInfo(
108 `Phase 1 tools available: ${tools1.map((t: any) => t.name).join(', ')}`,
109 )
110 if (verbose) {
111 logInfo(`System prompt:\n${systemPrompt1.substring(0, 500)}...`)
112 }
113​
114 // Run the chat
115 logStep(2, 'Executing chat with LLM')
116​
117 const stream1 = chat({
118 adapter,
119 messages: messages1,
120 tools: tools1 as any,
121 systemPrompts: [systemPrompt1],
122 agentLoopStrategy: maxIterations(15),
123 })
124​
125 let toolCallCount1 = 0
126 let executeTypescriptCalled = false
127 let registerSnippetCalled = false
128 let fullContent = ''
129​
130 for await (const chunk of stream1 as AsyncIterable<StreamChunk>) {
131 if (chunk.type === 'tool_call') {
132 toolCallCount1++
133 const toolName = chunk.toolCall.function.name
134 logInfo(`Tool called: ${toolName}`)
135 if (verbose) {
136 logInfo(
137 ` Arguments: ${chunk.toolCall.function.arguments.substring(0, 200)}...`,
138 )
139 }
140 if (toolName === 'execute_typescript') {
141 executeTypescriptCalled = true
142 }
143 if (toolName === 'register_snippet') {
144 registerSnippetCalled = true
145 }
146 } else if (chunk.type === 'tool_result') {
147 if (verbose) {
148 logInfo(`Tool result: ${chunk.content.substring(0, 200)}...`)
149 }
150 } else if (chunk.type === 'content') {
151 fullContent += chunk.delta
152 } else if (chunk.type === EventType.RUN_FINISHED) {
153 logInfo(`Phase 1 done: ${chunk.metadata?.tanstack?.finishReason}`)
154 }
155 }
156​
157 if (verbose && fullContent) {
158 logInfo(`LLM response: ${fullContent.substring(0, 500)}...`)
159 }
160​
161 // Verify snippet was created
162 const snippetIndex = await storage.loadIndex()
163 const snippetCreated = snippetIndex.some(
164 (s) => s.name === 'add_two_numbers',
165 )
166​
167 if (snippetCreated) {
168 result.snippetCreated = true
169 logSuccess('Snippet "add_two_numbers" was created successfully')
170​
171 // Log the created snippet
172 const snippet = await storage.get('add_two_numbers')
173 if (snippet && verbose) {
174 logInfo(`Snippet details:`)
175 logInfo(` Description: ${snippet.description}`)
176 logInfo(` Code: ${snippet.code.substring(0, 100)}...`)
177 }
178 } else {
179 logWarning(
180 'Snippet was not created - LLM may not have followed instructions',
181 )
182 }
183​
184 result.phases.phase1 = {
185 success: executeTypescriptCalled,
186 details: {
187 toolCallCount: toolCallCount1,
188 executeTypescriptCalled,
189 registerSnippetCalled,
190 snippetCreated,
191 snippetsInStorage: snippetIndex.length,
192 },
193 }
194​
195 if (result.phases.phase1.success) {
196 logSuccess('Phase 1 completed successfully')
197 } else {
198 logError('Phase 1 failed - execute_typescript was not called')
199 }
200 } catch (error) {
201 result.phases.phase1 = {
202 success: false,
203 error: error instanceof Error ? error.message : String(error),
204 }
205 logError(`Phase 1 error: ${result.phases.phase1.error}`)
206 }
207​
208 // =========================================================================
209 // Phase 2: Second run - Use the saved snippet (if created)
210 // =========================================================================
211​
212 logSection('Phase 2: Snippet Reuse')
213​
214 // Only run phase 2 if a snippet was created
215 if (!result.snippetCreated) {
216 logWarning('Skipping Phase 2 - no snippet was created in Phase 1')
217 result.phases.phase2 = {
218 success: false,
219 error: 'No snippet was created in Phase 1',
220 }
221 } else {
222 logStep(1, 'Running code mode with real LLM (snippet should be available)')
223​
224 try {
225 const messages2: Array<ModelMessage> = [
226 {
227 role: 'user',
228 content: `What is 10 + 20?
229​
230If you have a snippet called "add_two_numbers" available, please use it directly instead of execute_typescript.`,
231 },
232 ]
233​
234 // Get tools and system prompt with snippets integration
235 const {
236 tools: tools2,
237 systemPrompt: systemPrompt2,
238 selectedSnippets,
239 } = await codeModeWithSnippets({
240 config: {
241 driver,
242 tools: [addNumbersTool],
243 timeout: 60000,
244 memoryLimit: 128,
245 },
246 adapter,
247 snippets: {
248 storage,
249 maxSnippetsInContext: 5,
250 },
251 messages: messages2,
252 })
253​
254 logInfo(
255 `Phase 2 tools available: ${tools2.map((t: any) => t.name).join(', ')}`,
256 )
257 logInfo(
258 `Selected snippets: ${selectedSnippets.map((s) => s.name).join(', ') || 'none'}`,
259 )
260​
261 // Check if snippet is now available as a tool
262 const snippetToolAvailable = tools2.some(
263 (t: any) => t.name === 'add_two_numbers',
264 )
265 if (snippetToolAvailable) {
266 logSuccess('Snippet "add_two_numbers" is available as a tool')
267 } else {
268 logWarning(
269 'Snippet is not available as a tool (may not have been selected by LLM)',
270 )
271 }
272​
273 // Run the chat
274 logStep(2, 'Executing chat with LLM')
275​
276 const stream2 = chat({
277 adapter,
278 messages: messages2,
279 tools: tools2 as any,
280 systemPrompts: [systemPrompt2],
281 agentLoopStrategy: maxIterations(15),
282 })
283​
284 let toolCallCount2 = 0
285 let snippetCalled = false
286 let snippetExecutedSuccessfully = false
287 let snippetExecutionError: string | undefined
288 let executeTypescriptCalledPhase2 = false
289 let fullContent2 = ''
290​
291 for await (const chunk of stream2 as AsyncIterable<StreamChunk>) {
292 if (chunk.type === 'tool_call') {
293 toolCallCount2++
294 const toolName = chunk.toolCall.function.name
295 logInfo(`Tool called: ${toolName}`)
296 if (toolName === 'add_two_numbers') {
297 snippetCalled = true
298 }
299 if (toolName === 'execute_typescript') {
300 executeTypescriptCalledPhase2 = true
301 }
302 } else if (chunk.type === 'tool_result') {
303 // Check if this is the snippet result and if it succeeded
304 if (snippetCalled && chunk.toolCallId) {
305 // Check if the result contains an error
306 const resultContent = chunk.content
307 if (
308 resultContent.includes('error') ||
309 resultContent.includes('Error')
310 ) {
311 snippetExecutionError = resultContent.substring(0, 200)
312 logError(`Snippet execution failed: ${snippetExecutionError}`)
313 } else {
314 snippetExecutedSuccessfully = true
315 if (verbose) {
316 logInfo(`Snippet result: ${resultContent.substring(0, 200)}`)
317 }
318 }
319 }
320 } else if (chunk.type === 'content') {
321 fullContent2 += chunk.delta
322 } else if (chunk.type === EventType.RUN_FINISHED) {
323 logInfo(`Phase 2 done: ${chunk.metadata?.tanstack?.finishReason}`)
324 }
325 }
326​
327 if (verbose && fullContent2) {
328 logInfo(`LLM response: ${fullContent2.substring(0, 500)}...`)
329 }
330​
331 result.snippetUsed = snippetCalled && snippetExecutedSuccessfully
332​
333 // Consider phase 2 successful if either:
334 // 1. The snippet was called directly AND executed successfully, OR
335 // 2. The snippet wasn't available (selection issue) but execute_typescript worked
336 const phase2Success =
337 (snippetCalled && snippetExecutedSuccessfully) ||
338 executeTypescriptCalledPhase2
339​
340 result.phases.phase2 = {
341 success: phase2Success,
342 details: {
343 toolCallCount: toolCallCount2,
344 snippetCalled,
345 snippetExecutedSuccessfully,
346 snippetExecutionError,
347 executeTypescriptCalled: executeTypescriptCalledPhase2,
348 snippetToolAvailable,
349 selectedSnippetCount: selectedSnippets.length,
350 },
351 }
352​
353 if (snippetCalled && snippetExecutedSuccessfully) {
354 logSuccess(
355 'Phase 2 completed successfully - snippet was called and executed correctly!',
356 )
357 } else if (snippetCalled && !snippetExecutedSuccessfully) {
358 logError(
359 `Phase 2 failed - snippet was called but execution failed: ${snippetExecutionError}`,
360 )
361 } else if (executeTypescriptCalledPhase2) {
362 logWarning(
363 'Phase 2 completed but LLM used execute_typescript instead of the snippet',
364 )
365 } else {
366 logError('Phase 2 failed - no tool was called')
367 }
368 } catch (error) {
369 result.phases.phase2 = {
370 success: false,
371 error: error instanceof Error ? error.message : String(error),
372 }
373 logError(`Phase 2 error: ${result.phases.phase2.error}`)
374 }
375 }
376​
377 // =========================================================================
378 // Final Result
379 // =========================================================================
380​
381 logSection('Test Results')
382​
383 // For live tests, we're more lenient - consider it passed if Phase 1 succeeded
384 // since LLM behavior can vary
385 result.passed = result.phases.phase1.success
386​
387 if (result.passed) {
388 logSuccess('Test passed!')
389 logInfo(
390 `✓ execute_typescript used in Phase 1: ${result.phases.phase1.details?.executeTypescriptCalled}`,
391 )
392 logInfo(`✓ Snippet created: ${result.snippetCreated}`)
393 logInfo(`✓ Snippet used successfully in Phase 2: ${result.snippetUsed}`)
394 } else {
395 logError('Test failed')
396 if (!result.phases.phase1.success) {
397 logError(`Phase 1 (Code Mode): ${result.phases.phase1.error || 'Failed'}`)
398 }
399 if (!result.phases.phase2.success) {
400 const phase2Details = result.phases.phase2.details as
401 | Record<string, unknown>
402 | undefined
403 if (phase2Details?.snippetExecutionError) {
404 logError(
405 `Phase 2 (Snippet Reuse): Snippet execution failed - ${phase2Details.snippetExecutionError}`,
406 )
407 } else {
408 logError(
409 `Phase 2 (Snippet Reuse): ${result.phases.phase2.error || 'Failed'}`,
410 )
411 }
412 }
413 }
414​
415 return result