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

structured-output-test.ts

292 lines8.7 KB

1/**
2 * Structured Output Test for Code Mode
3 *
4 * Tests that code mode analysis can be followed by structured output generation.
5 * This is a simplified test to verify the structured output pipeline works.
6 */
7​
8import { EventType, chat, maxIterations } from '@tanstack/ai'
9import { z } from 'zod'
10import {
11 createCodeModeSystemPrompt,
12 createCodeModeTool,
13} from '@tanstack/ai-code-mode'
14import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
15import {
16 addNumbersTool,
17 logError,
18 logInfo,
19 logSection,
20 logStep,
21 logSuccess,
22 logWarning,
23} from './test-utils'
24import type { AnyTextAdapter, ModelMessage, StreamChunk } from '@tanstack/ai'
25​
26/**
27 * Schema for the structured math report output
28 */
29export const MathReportSchema = z.object({
30 title: z.string().describe('A title for the math report'),
31 operation: z.string().describe('The math operation performed'),
32 operands: z.array(z.number()).describe('The numbers involved'),
33 result: z.number().describe('The result of the calculation'),
34 funFact: z.string().describe('A fun or interesting fact about the result'),
35})
36​
37export type MathReport = z.infer<typeof MathReportSchema>
38​
39/**
40 * Options for the structured output test
41 */
42export interface StructuredOutputTestOptions {
43 /**
44 * The adapter to use for the LLM
45 */
46 adapter: AnyTextAdapter
47​
48 /**
49 * Whether to log verbose output
50 */
51 verbose?: boolean
53​
54/**
55 * Result from the structured output test
56 */
57export interface StructuredOutputTestResult {
58 passed: boolean
59 codeModeExecuted: boolean
60 structuredOutputReceived: boolean
61 structuredOutput?: MathReport
62 error?: string
64​
65/**
66 * Run the structured output test with a real LLM
67 */
68export async function runStructuredOutputTest(
69 options: StructuredOutputTestOptions,
70): Promise<StructuredOutputTestResult> {
71 const { adapter, verbose = false } = options
72​
73 logSection('Structured Output Test')
74 logInfo(`Using adapter: ${adapter.name} with model: ${adapter.model}`)
75​
76 const driver = createNodeIsolateDriver({
77 memoryLimit: 128,
78 timeout: 60000,
79 })
80​
81 const result: StructuredOutputTestResult = {
82 passed: false,
83 codeModeExecuted: false,
84 structuredOutputReceived: false,
85 }
86​
87 // Create code mode tool
88 const codeModeConfig = {
89 driver,
90 tools: [addNumbersTool],
91 timeout: 60000,
92 memoryLimit: 128,
93 }
94​
95 const executeTypescript = createCodeModeTool(codeModeConfig)
96 const codeModeSystemPrompt = createCodeModeSystemPrompt(codeModeConfig)
97​
98 const systemPrompt = `You are a helpful math assistant that can execute code to perform calculations.
99When asked to add numbers, use the execute_typescript tool to call external_add_numbers.
100​
101${codeModeSystemPrompt}
102​
103After performing the calculation, provide a structured report about the result.`
104​
105 // =========================================================================
106 // Phase 1: Run Code Mode Analysis
107 // =========================================================================
108​
109 logSection('Phase 1: Code Mode Execution')
110 logStep(1, 'Running code mode to add numbers')
111​
112 const messages: Array<ModelMessage> = [
113 {
114 role: 'user',
115 content:
116 'Please add 42 and 17 together using code execution, then give me a math report about the result.',
117 },
118 ]
119​
120 try {
121 // First, run the code mode analysis
122 const analysisStream = chat({
123 adapter,
124 messages,
125 tools: [executeTypescript] as any,
126 systemPrompts: [systemPrompt],
127 agentLoopStrategy: maxIterations(10),
128 maxTokens: 4096,
129 })
130​
131 let executeTypescriptCalled = false
132 let fullContent = ''
133 const collectedMessages: Array<ModelMessage> = [...messages]
134​
135 for await (const chunk of analysisStream as AsyncIterable<StreamChunk>) {
136 if (chunk.type === 'tool_call') {
137 const toolName = chunk.toolCall.function.name
138 logInfo(`Tool called: ${toolName}`)
139 if (verbose) {
140 logInfo(
141 ` Arguments: ${chunk.toolCall.function.arguments.substring(0, 200)}...`,
142 )
143 }
144 if (toolName === 'execute_typescript') {
145 executeTypescriptCalled = true
146 }
147 } else if (chunk.type === 'tool_result') {
148 if (verbose) {
149 logInfo(`Tool result: ${chunk.content.substring(0, 200)}...`)
150 }
151 } else if (chunk.type === 'content') {
152 fullContent += chunk.delta
153 } else if (chunk.type === EventType.RUN_FINISHED) {
154 logInfo(`Code mode done: ${chunk.metadata?.tanstack?.finishReason}`)
155 }
156 }
157​
158 result.codeModeExecuted = executeTypescriptCalled
159​
160 if (executeTypescriptCalled) {
161 logSuccess('execute_typescript was called')
162 } else {
163 logWarning(
164 'execute_typescript was not called - LLM may have skipped code execution',
165 )
166 }
167​
168 if (verbose && fullContent) {
169 logInfo(`LLM analysis: ${fullContent.substring(0, 300)}...`)
170 }
171​
172 // Save the assistant's response for phase 2
173 if (fullContent) {
174 collectedMessages.push({
175 role: 'assistant',
176 content: fullContent,
177 })
178 }
179​
180 // =========================================================================
181 // Phase 2: Get Structured Output
182 // =========================================================================
183​
184 logSection('Phase 2: Structured Output Generation')
185 logStep(1, 'Requesting structured math report')
186​
187 // Add a follow-up message asking for the structured format
188 const structuredRequestMessages = [
189 ...collectedMessages,
190 {
191 role: 'user' as const,
192 content:
193 'Now provide a structured math report about the calculation you just performed.',
194 },
195 ]
196​
197 // Use chat with outputSchema for structured output
198 const structuredResult = await chat({
199 adapter,
200 messages: structuredRequestMessages,
201 systemPrompts: [systemPrompt],
202 outputSchema: MathReportSchema,
203 maxTokens: 2048,
204 })
205​
206 logSuccess('Structured output received!')
207 result.structuredOutputReceived = true
208 result.structuredOutput = structuredResult as MathReport
209​
210 if (verbose) {
211 logInfo(
212 `Structured output: ${JSON.stringify(result.structuredOutput, null, 2)}`,
213 )
214 }
215​
216 // Validate the structured output
217 logStep(2, 'Validating structured output')
218​
219 const output = result.structuredOutput
220 if (!output) {
221 logError('Structured output is empty')
222 } else {
223 // Check required fields exist
224 const hasTitle =
225 typeof output.title === 'string' && output.title.length > 0
226 const hasOperation =
227 typeof output.operation === 'string' && output.operation.length > 0
228 const hasOperands =
229 Array.isArray(output.operands) && output.operands.length > 0
230 const hasResult = typeof output.result === 'number'
231 const hasFunFact =
232 typeof output.funFact === 'string' && output.funFact.length > 0
233​
234 logInfo(` title: ${hasTitle ? '✓' : '✗'} "${output.title}"`)
235 logInfo(` operation: ${hasOperation ? '✓' : '✗'} "${output.operation}"`)
236 logInfo(
237 ` operands: ${hasOperands ? '✓' : '✗'} [${output.operands?.join(', ')}]`,
238 )
239 logInfo(` result: ${hasResult ? '✓' : '✗'} ${output.result}`)
240 logInfo(
241 ` funFact: ${hasFunFact ? '✓' : '✗'} "${output.funFact?.substring(0, 50)}..."`,
242 )
243​
244 // Check if the result is correct (42 + 17 = 59)
245 const expectedResult = 59
246 const resultCorrect = output.result === expectedResult
247​
248 if (resultCorrect) {
249 logSuccess(`Result is correct: ${output.result} = 42 + 17`)
250 } else {
251 logWarning(
252 `Result may be incorrect: got ${output.result}, expected ${expectedResult}`,
253 )
254 }
255​
256 // Test passes if we got structured output with all required fields
257 result.passed =
258 hasTitle && hasOperation && hasOperands && hasResult && hasFunFact
259 }
260 } catch (error) {
261 result.error = error instanceof Error ? error.message : String(error)
262 logError(`Test error: ${result.error}`)
263 if (error instanceof Error && error.stack && verbose) {
264 console.error(error.stack)
265 }
266 }
267​
268 // =========================================================================
269 // Final Result
270 // =========================================================================
271​
272 logSection('Test Results')
273​
274 if (result.passed) {
275 logSuccess('Structured Output Test PASSED!')
276 logInfo('✓ Code mode executed successfully')
277 logInfo('✓ Structured output received and validated')
278 } else {
279 logError('Structured Output Test FAILED')
280 if (!result.codeModeExecuted) {
281 logError(' - Code mode was not executed')
282 }
283 if (!result.structuredOutputReceived) {
284 logError(' - Structured output was not received')
285 }
286 if (result.error) {
287 logError(` - Error: ${result.error}`)
288 }
289 }
290​
291 return result