Schema-first design
Every extraction starts with a JSON schema that defines the output structure:JSONSchemaType<T> from Ajv provides:
- Type safety: The schema is validated at compile time against your TypeScript type
- Type inference:
result.datais automatically typed asT - Runtime validation: Ajv validates LLM output matches the schema
Validation process
Struktur validates LLM outputs using Ajv with the following configuration:- allErrors: Collects all validation errors (not just the first)
- strict: false: Allows flexible schema definitions
- allowUnionTypes: Supports union types like
string | null - ajv-formats: Adds support for
formatkeywords (date-time,email,uri, etc.)
Automatic retries
When validation fails, Struktur automatically retries the LLM call with error feedback:Retry on failure
If validation fails, send errors back to the LLM and retry (up to 3 times by default).
runWithRetries in the LLM module:
Validation modes
Struktur supports two validation modes:Strict mode
Enforces all schema constraints includingrequired fields:
Lenient mode
Allows missingrequired fields (useful for partial extraction):
Error handling
Validation failures throwSchemaValidationError with detailed error information:
errors array is an Ajv ErrorObject:
Common schema patterns
Arrays with item validation
Nested objects
Format validation
ajv-formats):
date-time,date,timeemail,hostname,ipv4,ipv6uri,uri-reference,uri-templatejson-pointer,regexuuid
Enums and constants
Schema-aware merging
Auto-merge strategies use schema information to intelligently merge results:- Arrays accumulate items across batches
- Objects merge properties without duplication
- Scalars prefer the latest non-empty value
Best practices
Use JSONSchemaType for type safety
Use JSONSchemaType for type safety
Always use
JSONSchemaType<T> from Ajv to ensure your schema matches your TypeScript type:Set additionalProperties to false
Set additionalProperties to false
Prevent LLMs from adding unexpected fields:
Use formats for validation
Use formats for validation
Leverage
ajv-formats for common data types:Make fields nullable when optional
Make fields nullable when optional
For optional fields that can be
null, use nullable: true:Validation events
Monitor validation retries using theonMessage event: