ai-utils.js
Version:
Build AI applications, chatbots, and agents with JavaScript and TypeScript.
75 lines (74 loc) • 2.72 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateJsonOrText = void 0;
const executeCall_js_1 = require("../executeCall.cjs");
const NoSuchSchemaError_js_1 = require("./NoSuchSchemaError.cjs");
const SchemaValidationError_js_1 = require("./SchemaValidationError.cjs");
async function generateJsonOrText(model, schemaDefinitions, prompt, options) {
const expandedPrompt = prompt(schemaDefinitions);
const result = await (0, executeCall_js_1.executeCall)({
model,
options,
generateResponse: (options) => model.generateJsonResponse(expandedPrompt, options),
extractOutputValue: (response) => {
const { schema, value, text } = expandedPrompt.extractJsonAndText(response);
// text generation:
if (schema == null) {
return { schema, value, text };
}
const definition = schemaDefinitions.find((d) => d.name === schema);
if (definition == undefined) {
throw new NoSuchSchemaError_js_1.NoSuchSchemaError(schema);
}
const parseResult = definition.schema.safeParse(value);
if (!parseResult.success) {
throw new SchemaValidationError_js_1.SchemaValidationError({
schemaName: schema,
value,
errors: parseResult.error,
});
}
return {
schema: schema,
value: parseResult.data,
text: text, // text is string | null, which is part of the response for schema values
};
},
getStartEvent: (metadata, settings) => ({
type: "json-generation-started",
metadata,
settings,
prompt,
}),
getAbortEvent: (metadata, settings) => ({
type: "json-generation-finished",
status: "abort",
metadata,
settings,
prompt,
}),
getFailureEvent: (metadata, settings, error) => ({
type: "json-generation-finished",
status: "failure",
metadata,
settings,
prompt,
error,
}),
getSuccessEvent: (metadata, settings, response, output) => ({
type: "json-generation-finished",
status: "success",
metadata,
settings,
prompt,
response,
generatedJson: output,
}),
});
return {
...result.output,
response: result.response,
metadata: result.metadata,
};
}
exports.generateJsonOrText = generateJsonOrText;