UNPKG

@solvers-hub/llm-json

Version:

A TypeScript SDK to extract and correct JSON from LLM outputs

77 lines (76 loc) 2.54 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SchemaValidator = void 0; const ajv_1 = __importDefault(require("ajv")); const ajv_formats_1 = __importDefault(require("ajv-formats")); /** * SchemaValidator class for validating JSON against schemas. */ class SchemaValidator { /** * Creates a new instance of SchemaValidator. */ constructor() { this.ajv = new ajv_1.default({ allErrors: true, verbose: true }); // Add format validation support (0, ajv_formats_1.default)(this.ajv); } /** * Validates a JSON object against a set of schemas. * * @param json - The JSON object to validate. * @param schemas - The schemas to validate against. * @returns A validation result with matched schema information. */ validate(json, schemas) { if (!json || !schemas || schemas.length === 0) { return { json, matchedSchema: null, isValid: false }; } // Try each schema until one matches for (const schemaObj of schemas) { const validate = this.ajv.compile(schemaObj.schema); const isValid = validate(json); if (isValid) { return { json, matchedSchema: schemaObj.name, isValid: true }; } } // If we reach here, none of the schemas matched // Return the validation errors from the first schema as a fallback const firstTry = this.ajv.compile(schemas[0].schema); firstTry(json); return { json, matchedSchema: null, isValid: false, validationErrors: firstTry.errors || [] }; } /** * Validates an array of JSON objects against a set of schemas. * * @param jsonObjects - The JSON objects to validate. * @param schemas - The schemas to validate against. * @returns An array of validation results. */ validateAll(jsonObjects, schemas) { if (!jsonObjects || jsonObjects.length === 0 || !schemas || schemas.length === 0) { return []; } return jsonObjects.map(json => this.validate(json, schemas)); } } exports.SchemaValidator = SchemaValidator;