schema-force
v0.1.0
Published
Force LLM responses to match a schema. Validate, coerce types, apply defaults, and extract structured data from messy AI output.
Maintainers
Readme
schema-force
Force LLM responses to match a schema. Validate, coerce types, apply defaults, and extract structured data from messy AI output — zero dependencies.
Install
npm install schema-forceQuick Start
const { force, validate } = require('schema-force');
const schema = {
name: { type: 'string', required: true },
age: { type: 'number', min: 0 },
tags: { type: 'array', items: { type: 'string' } },
};
// Force LLM output to match schema (extract JSON + validate + coerce)
const data = force(llmOutput, schema);
// → { name: "Alice", age: 30, tags: ["dev"] }
// Just validate
const result = validate({ name: "Alice", age: "30" }, schema);
// → { valid: true, data: { name: "Alice", age: 30 }, errors: [] }
// Note: "30" was coerced to 30Schema Definition
const schema = {
name: { type: 'string', required: true, minLength: 1 },
score: { type: 'number', min: 0, max: 100, default: 50 },
status: { type: 'string', enum: ['active', 'inactive'] },
tags: { type: 'array', items: { type: 'string' }, maxLength: 10 },
meta: {
type: 'object',
properties: {
created: { type: 'string' },
},
},
};Type Coercion
Automatically converts compatible types:
"42"→42(string to number)"true"→true(string to boolean)1→true(number to boolean)42→"42"(number to string)
Features
- Schema validation with clear error messages
- Automatic type coercion
- Default values for missing fields
- Nested object/array validation
- Range checks (min/max for numbers, minLength/maxLength for strings/arrays)
- Enum validation
- Pattern matching (regex) for strings
- JSON extraction from LLM text (code blocks, embedded JSON)
- JSON repair (trailing commas, single quotes, etc.)
License
MIT
