Reliably extract structured JSON from LLM responses. Schema validation, retry on malformed output, and fallback parsing strategies.
## Task Reliably extract structured data from LLM responses with validation and retry. ## Requirements - Language: TypeScript - Schema validation: Zod - LLM: Any (OpenAI, Anthropic, etc.) ## Specifications ```typescript // Define expected output schema const ProductReview = z.object({ sentiment: z.enum(["positive", "negative", "neutral"]), score: z.number().min(1).max(10), pros: z.array(z.string()).min(1), cons: z.array(z.string()), summary: z.string().max(200), }); // Parser should: // 1. Try native JSON mode (if provider supports it) // 2. Fallback: extract JSON from markdown code blocks // 3. Fallback: regex extract { ... } from response // 4. Validate with Zod schema // 5. On validation fail: retry with error feedback to LLM // 6. Max 3 retries before throwing ``` ## Implementation Notes 1. Use provider-native JSON mode when available (OpenAI response_format, Anthropic tool_use) 2. Include the Zod schema description in the system prompt 3. On retry, include the validation error: "Previous output failed: field 'score' must be 1-10, got 15" 4. Log all attempts for debugging 5. Support nested objects and arrays 6. Handle edge cases: empty arrays, null vs undefined, number-as-string
No gallery images yet.