@solvers-hub/llm-json
Version:
A TypeScript SDK to extract and correct JSON from LLM outputs
80 lines (79 loc) • 3.13 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LlmJson = void 0;
const extractor_1 = require("./extractor");
const array_extractor_1 = require("./array-extractor");
/**
* Main factory class for the LLM-JSON extractor SDK.
*/
class LlmJson {
/**
* Creates a new LlmJson instance with the specified options.
* @param options - Configuration options for extraction.
*/
constructor(options = {}) {
this.objectExtractor = new extractor_1.JsonExtractor(options);
this.arrayExtractor = new array_extractor_1.JsonArrayExtractor(options);
}
/**
* Get or create a singleton instance of LlmJson.
* @param options - Configuration options for extraction.
* @returns The LlmJson singleton instance.
*/
static getInstance(options = {}) {
if (!LlmJson.instance) {
LlmJson.instance = new LlmJson(options);
}
return LlmJson.instance;
}
/**
* Extract JSON objects and text from a string input.
* @param input - The input string that may contain JSON.
* @returns An object containing arrays of extracted text and JSON.
*/
extract(input) {
return this.objectExtractor.extract(input);
}
/**
* Extract JSON objects, arrays, and text from a string input.
* @param input - The input string that may contain JSON.
* @returns An object containing arrays of extracted text and JSON.
*/
extractAll(input) {
if (!input || typeof input !== 'string') {
return { text: [], json: [] };
}
// First check if the input contains markdown code blocks
const codeBlockRegex = /```(?:json)?\s*\n([\s\S]*?)\n\s*```/g;
if (codeBlockRegex.test(input)) {
// Reset regex state
codeBlockRegex.lastIndex = 0;
// Extract from code blocks first
const codeBlockResult = this.objectExtractor.extract(input);
if (codeBlockResult.json.length > 0) {
// If we found JSON in code blocks, prioritize that
return codeBlockResult;
}
}
// If no code blocks with valid JSON were found, proceed with array extraction
return this.arrayExtractor.extractArrays(input);
}
}
exports.LlmJson = LlmJson;
// Export main class and types for convenience
__exportStar(require("./types"), exports);
exports.default = LlmJson;
;