UNPKG

ai-utils.js

Version:

Build AI applications, chatbots, and agents with JavaScript and TypeScript.

71 lines (70 loc) 2.47 kB
import { executeCall } from "../executeCall.js"; import { NoSuchSchemaError } from "./NoSuchSchemaError.js"; import { SchemaValidationError } from "./SchemaValidationError.js"; export async function generateJsonOrText(model, schemaDefinitions, prompt, options) { const expandedPrompt = prompt(schemaDefinitions); const result = await 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(schema); } const parseResult = definition.schema.safeParse(value); if (!parseResult.success) { throw new 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, }; }