langextract
Version:
A TypeScript library for extracting structured and grounded information from text using LLMs
161 lines • 6.17 kB
JavaScript
;
/**
* Copyright 2025 kmbro.
*
* This is a TypeScript translation of the original Python LangExtract library
* by Google LLC (https://github.com/google/langextract).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.QAPromptGeneratorImpl = exports.ParseError = exports.PromptBuilderError = void 0;
exports.readPromptTemplateStructuredFromFile = readPromptTemplateStructuredFromFile;
/**
* Library for building prompts.
*/
const yaml = __importStar(require("js-yaml"));
const types_1 = require("./types");
const schema_1 = require("./schema");
class PromptBuilderError extends Error {
constructor(message) {
super(message);
this.name = "PromptBuilderError";
}
}
exports.PromptBuilderError = PromptBuilderError;
class ParseError extends PromptBuilderError {
constructor(message) {
super(message);
this.name = "ParseError";
}
}
exports.ParseError = ParseError;
/**
* Reads a structured prompt template from a file.
*/
function readPromptTemplateStructuredFromFile(promptPath) {
try {
// In a real implementation, you would read from file system
// For now, we'll throw an error as this would require Node.js fs module
throw new Error("File reading not implemented in this version");
}
catch (error) {
throw new ParseError(`Failed to parse prompt template from file: ${promptPath}`);
}
}
class QAPromptGeneratorImpl {
constructor(template) {
this.formatType = types_1.FormatType.YAML;
this.attributeSuffix = "_attributes";
this.examplesHeading = "Examples";
this.questionPrefix = "Q: ";
this.answerPrefix = "A: ";
this.fenceOutput = true;
this.template = template;
}
formatExampleAsText(example) {
const question = example.text;
// Build a dictionary for serialization
const dataDict = { [schema_1.EXTRACTIONS_KEY]: [] };
for (const extraction of example.extractions) {
const dataEntry = {
[extraction.extractionClass]: extraction.extractionText,
[`${extraction.extractionClass}${this.attributeSuffix}`]: extraction.attributes || {},
};
dataDict[schema_1.EXTRACTIONS_KEY].push(dataEntry);
}
let answer;
if (this.formatType === types_1.FormatType.YAML) {
const formattedContent = yaml.dump(dataDict, {
flowLevel: -1,
sortKeys: false,
});
if (this.fenceOutput) {
answer = `\`\`\`yaml\n${formattedContent.trim()}\n\`\`\``;
}
else {
answer = formattedContent.trim();
}
}
else if (this.formatType === types_1.FormatType.JSON) {
const formattedContent = JSON.stringify(dataDict, null, 2);
if (this.fenceOutput) {
answer = `\`\`\`json\n${formattedContent.trim()}\n\`\`\``;
}
else {
answer = formattedContent.trim();
}
}
else {
throw new Error(`Unsupported format type: ${this.formatType}`);
}
return [`${this.questionPrefix}${question}`, `${this.answerPrefix}${answer}\n`].join("\n");
}
render(question, additionalContext) {
const promptLines = [`${this.template.description}\n`];
if (additionalContext) {
promptLines.push(`${additionalContext}\n`);
}
if (this.template.examples.length > 0) {
promptLines.push(this.examplesHeading);
for (const ex of this.template.examples) {
promptLines.push(this.formatExampleAsText(ex));
}
}
// Add format instruction for OpenAI compatibility
if (this.formatType === types_1.FormatType.JSON) {
promptLines.push("Please respond with a JSON object.");
}
promptLines.push(`${this.questionPrefix}${question}`);
promptLines.push(this.answerPrefix);
return promptLines.join("\n");
}
toString() {
return this.render("");
}
}
exports.QAPromptGeneratorImpl = QAPromptGeneratorImpl;
//# sourceMappingURL=prompting.js.map