@beparallel/langchain-ts
Version:
Extracts Langchain prompts and generates TypeScript types.
61 lines (60 loc) • 2.41 kB
JavaScript
import fs from 'fs';
import { toPascalCase } from './case.js';
export function generateTypes(prompts, outputPath) {
const lines = ['// Auto-generated file. Do not edit.', '', ''];
for (const prompt of prompts) {
const inputSchema = prompt.inputVariables;
const promptName = String(prompt.metadata?.lc_hub_repo ?? '');
const promptDict = prompt.toJSON();
// @ts-ignore
const schema = promptDict.kwargs.schema_;
lines.push('\n');
lines.push(`/*****************************/`);
lines.push(`// ${promptName}`);
lines.push(`/*****************************/`);
lines.push('\n');
// Input variables
lines.push(`export interface ${toPascalCase(promptName)}Variable {`, ` ${inputSchema.map((input) => `${input}: any`).join('\n ')}`, '}');
lines.push('\n');
// Output variables
lines.push(`export interface ${toPascalCase(promptName)}Output {`, ` ${jsonSchemaToType(schema)}`, '}');
}
fs.writeFileSync(outputPath, lines.join('\n'), 'utf-8');
}
function jsonSchemaToType(schema, rootName = 'Root') {
const parseSchema = (schema, name, increment) => {
if (schema.type === 'object' && schema.properties) {
const required = schema.required || [];
const props = Object.entries(schema.properties)
.map(([key, value]) => {
const optional = required.includes(key) ? '' : '?';
return `${' '.repeat(increment + 1)}${key}${optional}: ${parseSchema(value, key, increment + 1)}`;
})
.join('\n');
return `{\n${' '.repeat(increment)}${props}${' '.repeat(increment)}\n}`;
}
else if (schema.type === 'array' && schema.items) {
return `${parseSchema(schema.items, name, increment + 1)}[]`;
}
else if (schema.type === 'string') {
return 'string';
}
else if (schema.type === 'number') {
return 'number';
}
else if (schema.type === 'boolean') {
return 'boolean';
}
else if (schema.type === 'null') {
return 'null';
}
else {
return 'any';
}
};
if (!schema) {
return '';
}
const typeDef = `${schema.title || rootName}: ${parseSchema(schema, rootName, 1)}`;
return typeDef;
}