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

structured-output-test.ts

294 lines8.8 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 threadId: 'test-cli',
124 adapter,
125 messages,
126 tools: [executeTypescript] as any,
127 systemPrompts: [systemPrompt],
128 agentLoopStrategy: maxIterations(10),
129 maxTokens: 4096,
130 })
131​
132 let executeTypescriptCalled = false
133 let fullContent = ''
134 const collectedMessages: Array<ModelMessage> = [...messages]
135​
136 for await (const chunk of analysisStream as AsyncIterable<StreamChunk>) {
137 if (chunk.type === 'tool_call') {
138 const toolName = chunk.toolCall.function.name
139 logInfo(`Tool called: ${toolName}`)
140 if (verbose) {
141 logInfo(
142 ` Arguments: ${chunk.toolCall.function.arguments.substring(0, 200)}...`,
143 )
144 }
145 if (toolName === 'execute_typescript') {
146 executeTypescriptCalled = 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(`Code mode done: ${chunk.metadata?.tanstack?.finishReason}`)
156 }
157 }
158​
159 result.codeModeExecuted = executeTypescriptCalled
160​
161 if (executeTypescriptCalled) {
162 logSuccess('execute_typescript was called')
163 } else {
164 logWarning(
165 'execute_typescript was not called - LLM may have skipped code execution',
166 )
167 }
168​
169 if (verbose && fullContent) {
170 logInfo(`LLM analysis: ${fullContent.substring(0, 300)}...`)
171 }
172​
173 // Save the assistant's response for phase 2
174 if (fullContent) {
175 collectedMessages.push({
176 role: 'assistant',
177 content: fullContent,
178 })
179 }
180​
181 // =========================================================================
182 // Phase 2: Get Structured Output
183 // =========================================================================
184​
185 logSection('Phase 2: Structured Output Generation')
186 logStep(1, 'Requesting structured math report')
187​
188 // Add a follow-up message asking for the structured format
189 const structuredRequestMessages = [
190 ...collectedMessages,
191 {
192 role: 'user' as const,
193 content:
194 'Now provide a structured math report about the calculation you just performed.',
195 },
196 ]
197​
198 // Use chat with outputSchema for structured output
199 const structuredResult = await chat({
200 threadId: 'test-cli',
201 adapter,
202 messages: structuredRequestMessages,
203 systemPrompts: [systemPrompt],
204 outputSchema: MathReportSchema,
205 maxTokens: 2048,
206 })
207​
208 logSuccess('Structured output received!')
209 result.structuredOutputReceived = true
210 result.structuredOutput = structuredResult as MathReport
211​
212 if (verbose) {
213 logInfo(
214 `Structured output: ${JSON.stringify(result.structuredOutput, null, 2)}`,
215 )
216 }
217​
218 // Validate the structured output
219 logStep(2, 'Validating structured output')
220​
221 const output = result.structuredOutput
222 if (!output) {
223 logError('Structured output is empty')
224 } else {
225 // Check required fields exist
226 const hasTitle =
227 typeof output.title === 'string' && output.title.length > 0
228 const hasOperation =
229 typeof output.operation === 'string' && output.operation.length > 0
230 const hasOperands =
231 Array.isArray(output.operands) && output.operands.length > 0
232 const hasResult = typeof output.result === 'number'
233 const hasFunFact =
234 typeof output.funFact === 'string' && output.funFact.length > 0
235​
236 logInfo(` title: ${hasTitle ? '✓' : '✗'} "${output.title}"`)
237 logInfo(` operation: ${hasOperation ? '✓' : '✗'} "${output.operation}"`)
238 logInfo(
239 ` operands: ${hasOperands ? '✓' : '✗'} [${output.operands?.join(', ')}]`,
240 )
241 logInfo(` result: ${hasResult ? '✓' : '✗'} ${output.result}`)
242 logInfo(
243 ` funFact: ${hasFunFact ? '✓' : '✗'} "${output.funFact?.substring(0, 50)}..."`,
244 )
245​
246 // Check if the result is correct (42 + 17 = 59)
247 const expectedResult = 59
248 const resultCorrect = output.result === expectedResult
249​
250 if (resultCorrect) {
251 logSuccess(`Result is correct: ${output.result} = 42 + 17`)
252 } else {
253 logWarning(
254 `Result may be incorrect: got ${output.result}, expected ${expectedResult}`,
255 )
256 }
257​
258 // Test passes if we got structured output with all required fields
259 result.passed =
260 hasTitle && hasOperation && hasOperands && hasResult && hasFunFact
261 }
262 } catch (error) {
263 result.error = error instanceof Error ? error.message : String(error)
264 logError(`Test error: ${result.error}`)
265 if (error instanceof Error && error.stack && verbose) {
266 console.error(error.stack)
267 }
268 }
269​
270 // =========================================================================
271 // Final Result
272 // =========================================================================
273​
274 logSection('Test Results')
275​
276 if (result.passed) {
277 logSuccess('Structured Output Test PASSED!')
278 logInfo('✓ Code mode executed successfully')
279 logInfo('✓ Structured output received and validated')
280 } else {
281 logError('Structured Output Test FAILED')
282 if (!result.codeModeExecuted) {
283 logError(' - Code mode was not executed')
284 }
285 if (!result.structuredOutputReceived) {
286 logError(' - Structured output was not received')
287 }
288 if (result.error) {
289 logError(` - Error: ${result.error}`)
290 }
291 }
292​
293 return result