import { generateText, Output } from 'ai'; import { ollama } from 'ai-sdk-ollama'; import { z } from 'zod'; /** * Example demonstrating enhanced JSON repair for object generation with Ollama * * This example shows how the enhanced JSON repair automatically fixes * common JSON issues from LLM outputs (object generation). Tool-call argument * strings also get automatic repair via parseToolArguments (jsonrepair); * see tool-json-repair-example.ts. * * Note: Uses generateText with Output.object() instead of the deprecated generateObject. * See https://ai-sdk.dev/docs/ai-sdk-core/generating-structured-data * * Run: npx tsx src/json-repair-example.ts */ async function main() { console.log('šŸ”§ JSON Repair Example\n'); try { // Example 1: Basic object generation with automatic repair console.log('šŸ“ Example 1: Basic object generation (repair enabled by default)'); const result1 = await generateText({ model: ollama('llama3.2', { structuredOutputs: true, // Enhanced JSON repair is enabled by default reliableObjectGeneration: true, }), output: Output.object({ schema: z.object({ name: z.string(), email: z.string(), // Simple string validation (Zod email() is too strict for LLM output) age: z.number(), city: z.string(), }), }), prompt: 'Generate a person profile for John Doe, 30 years old, from New York. Use a simple email format.', }); console.log('āœ… Generated object:', JSON.stringify(result1.output, null, 2)); console.log(); // Example 2: Complex nested object with automatic repair console.log('šŸ“ Example 2: Complex nested object'); const result2 = await generateText({ model: ollama('llama3.2', { structuredOutputs: true, reliableObjectGeneration: true, }), output: Output.object({ schema: z.object({ recipe: z.object({ name: z.string(), ingredients: z.array( z.object({ name: z.string(), amount: z.string(), }), ), steps: z.array(z.string()), cookingTime: z.number().describe('Cooking time in minutes'), }), }), }), prompt: 'Generate a simple pasta recipe with at least 3 ingredients and 3 steps', }); console.log('āœ… Generated recipe:', JSON.stringify(result2.output, null, 2)); console.log(); // Example 3: Disable reliability (not recommended) console.log('šŸ“ Example 3: Reliability disabled (may fail with malformed JSON)'); try { const result3 = await generateText({ model: ollama('llama3.2', { structuredOutputs: true, reliableObjectGeneration: false, // Disable all reliability features }), output: Output.object({ schema: z.object({ message: z.string(), }), }), prompt: 'Generate a simple message', }); console.log('āœ… Succeeded without reliability:', JSON.stringify(result3.output, null, 2)); } catch (error) { console.log('āŒ Failed (as expected):', (error as Error).message); } console.log(); // Example 4: Fine-grained control - disable only repair, keep retries console.log('šŸ“ Example 4: Retries enabled, repair disabled'); try { const result4 = await generateText({ model: ollama('llama3.2', { structuredOutputs: true, reliableObjectGeneration: true, objectGenerationOptions: { enableTextRepair: false, // Disable repair only maxRetries: 3, // But keep retries }, }), output: Output.object({ schema: z.object({ message: z.string(), }), }), prompt: 'Generate a simple message', }); console.log('āœ… Succeeded with retries but no repair:', JSON.stringify(result4.output, null, 2)); } catch (error) { console.log('āŒ Failed:', (error as Error).message); } console.log(); // Example 5: Custom repair function console.log('šŸ“ Example 5: Using custom repair function'); const result5 = await generateText({ model: ollama('llama3.2', { structuredOutputs: true, reliableObjectGeneration: true, objectGenerationOptions: { repairText: async ({ text, error }) => { console.log(' šŸ” Custom repair function called'); console.log(' šŸ“„ Original text:', text.slice(0, 100) + '...'); console.log(' āŒ Error:', error.message); // Simple custom repair: just remove trailing comma const repaired = text.replace(/,(\s*[}\]])/g, '$1'); return repaired; }, }, }), output: Output.object({ schema: z.object({ title: z.string(), description: z.string(), }), }), prompt: 'Generate a title and description for a blog post about AI', }); console.log('āœ… Generated post:', JSON.stringify(result5.output, null, 2)); console.log('\n✨ JSON repair examples completed!'); console.log(' Tool-call JSON repair: npx tsx src/tool-json-repair-example.ts'); } catch (error) { console.error('āŒ Error:', error); process.exit(1); } } main().catch((error) => { console.error('JSON repair example failed:', error); process.exit(1); });