@genkit-ai/dotprompt
Version:
Genkit AI framework `.prompt` file format and management library.
261 lines • 9.59 kB
JavaScript
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __objRest = (source, exclude) => {
var target = {};
for (var prop in source)
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
target[prop] = source[prop];
if (source != null && __getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(source)) {
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
target[prop] = source[prop];
}
return target;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
var prompt_exports = {};
__export(prompt_exports, {
Dotprompt: () => Dotprompt,
DotpromptRef: () => DotpromptRef,
defineDotprompt: () => defineDotprompt
});
module.exports = __toCommonJS(prompt_exports);
var import_ai = require("@genkit-ai/ai");
var import_core = require("@genkit-ai/core");
var import_schema = require("@genkit-ai/core/schema");
var import_crypto = require("crypto");
var import_front_matter = __toESM(require("front-matter"));
var import_zod = __toESM(require("zod"));
var import_metadata = require("./metadata.js");
var import_registry = require("./registry.js");
var import_template = require("./template.js");
class Dotprompt {
static parse(name, source) {
try {
const fmResult = (0, import_front_matter.default)(source.trimStart(), {
allowUnsafe: false
});
return new Dotprompt(
__spreadProps(__spreadValues({}, (0, import_metadata.toMetadata)(fmResult.attributes)), { name }),
fmResult.body
);
} catch (e) {
throw new import_core.GenkitError({
source: "Dotprompt",
status: "INVALID_ARGUMENT",
message: `Error parsing YAML frontmatter of '${name}' prompt: ${e.stack}`
});
}
}
static fromAction(action) {
var _b, _c, _d, _e;
const _a = action.__action.metadata.prompt, { template } = _a, options = __objRest(_a, ["template"]);
const pm = options;
if ((_b = pm.input) == null ? void 0 : _b.schema) {
pm.input.jsonSchema = (_c = options.input) == null ? void 0 : _c.schema;
delete pm.input.schema;
}
if ((_d = pm.output) == null ? void 0 : _d.schema) {
pm.output.jsonSchema = (_e = options.output) == null ? void 0 : _e.schema;
}
const prompt = new Dotprompt(options, template);
return prompt;
}
constructor(options, template) {
this.name = options.name || "untitledPrompt";
this.variant = options.variant;
this.model = options.model;
this.input = options.input || { schema: import_zod.default.any() };
this.output = options.output;
this.tools = options.tools;
this.config = options.config;
this.candidates = options.candidates;
this.template = template;
this.hash = (0, import_crypto.createHash)("sha256").update(JSON.stringify(this)).digest("hex");
this._render = (0, import_template.compile)(this.template, options);
}
renderText(input, options) {
const result = this.renderMessages(input, options);
if (result.length !== 1) {
throw new Error("Multi-message prompt can't be rendered as text.");
}
let out = "";
for (const part of result[0].content) {
if (!part.text) {
throw new Error("Multimodal prompt can't be rendered as text.");
}
out += part.text;
}
return out;
}
renderMessages(input, options) {
var _a, _b, _c;
input = (0, import_schema.parseSchema)(input, {
schema: (_a = this.input) == null ? void 0 : _a.schema,
jsonSchema: (_b = this.input) == null ? void 0 : _b.jsonSchema
});
return this._render(__spreadValues(__spreadValues({}, (_c = this.input) == null ? void 0 : _c.default), input), options);
}
toJSON() {
return __spreadProps(__spreadValues({}, (0, import_metadata.toFrontmatter)(this)), { template: this.template });
}
define(options) {
var _a, _b;
(0, import_ai.definePrompt)(
{
name: (0, import_registry.registryDefinitionKey)(this.name, this.variant, options == null ? void 0 : options.ns),
description: "Defined by Dotprompt",
inputSchema: (_a = this.input) == null ? void 0 : _a.schema,
inputJsonSchema: (_b = this.input) == null ? void 0 : _b.jsonSchema,
metadata: {
type: "prompt",
prompt: this.toJSON()
}
},
(input) => __async(this, null, function* () {
return (0, import_ai.toGenerateRequest)(this.render({ input }));
})
);
}
_generateOptions(options) {
var _a, _b, _c, _d, _e, _f;
const messages = this.renderMessages(options.input, {
history: options.history,
context: options.context
});
return {
model: options.model || this.model,
config: __spreadValues(__spreadValues({}, this.config), options.config),
history: messages.slice(0, messages.length - 1),
prompt: messages[messages.length - 1].content,
context: options.context,
candidates: options.candidates || this.candidates || 1,
output: {
format: ((_a = options.output) == null ? void 0 : _a.format) || ((_b = this.output) == null ? void 0 : _b.format) || void 0,
schema: ((_c = options.output) == null ? void 0 : _c.schema) || ((_d = this.output) == null ? void 0 : _d.schema),
jsonSchema: ((_e = options.output) == null ? void 0 : _e.jsonSchema) || ((_f = this.output) == null ? void 0 : _f.jsonSchema)
},
tools: (options.tools || []).concat(this.tools || []),
streamingCallback: options.streamingCallback,
returnToolRequests: options.returnToolRequests
};
}
render(opt) {
return this._generateOptions(opt);
}
generate(opt) {
return __async(this, null, function* () {
return (0, import_ai.generate)(this.render(opt));
});
}
generateStream(opt) {
return __async(this, null, function* () {
return (0, import_ai.generateStream)(this.render(opt));
});
}
}
class DotpromptRef {
constructor(name, options) {
this.name = name;
this.variant = options == null ? void 0 : options.variant;
this.dir = options == null ? void 0 : options.dir;
}
loadPrompt() {
return __async(this, null, function* () {
if (this._prompt)
return this._prompt;
this._prompt = yield (0, import_registry.lookupPrompt)(
this.name,
this.variant,
this.dir
);
return this._prompt;
});
}
generate(opt) {
return __async(this, null, function* () {
const prompt = yield this.loadPrompt();
return prompt.generate(opt);
});
}
render(opt) {
return __async(this, null, function* () {
const prompt = yield this.loadPrompt();
return prompt.render(opt);
});
}
}
function defineDotprompt(options, template) {
const prompt = new Dotprompt(options, template);
prompt.define();
return prompt;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Dotprompt,
DotpromptRef,
defineDotprompt
});
//# sourceMappingURL=prompt.js.map