ai-functions
Version:
A powerful TypeScript library for building AI-powered applications with template literals and structured outputs
40 lines • 1.8 kB
JavaScript
export function createTemplateResult(prompt, options, templateFn) {
const promise = templateFn(prompt, options);
const result = Object.assign((opts) => templateFn(prompt, { ...options, ...opts }), {
[Symbol.asyncIterator]: async function* () {
const response = await templateFn(prompt, options);
yield response;
},
call: (opts) => templateFn(prompt, { ...options, ...opts }),
then: (onfulfilled) => templateFn(prompt, options).then(onfulfilled),
catch: (onrejected) => templateFn(prompt, options).catch(onrejected),
finally: (onfinally) => templateFn(prompt, options).finally(onfinally)
});
return result;
}
export function parseTemplateInput(stringsOrOptions, values, defaultOptions) {
if (!stringsOrOptions) {
return { prompt: '', options: defaultOptions };
}
if (Array.isArray(stringsOrOptions)) {
const strings = stringsOrOptions;
const lastValue = values[values.length - 1];
const isOptionsObject = typeof lastValue === 'object' && !Array.isArray(lastValue) && lastValue !== null && Object.keys(lastValue).length > 0;
const options = isOptionsObject
? { ...defaultOptions, ...lastValue }
: defaultOptions;
const actualValues = isOptionsObject
? values.slice(0, -1)
: values;
if (strings.length - 1 !== actualValues.length) {
throw new Error('Template literal slots must match provided values');
}
const prompt = strings.reduce((acc, str, i) => acc + str + (actualValues[i] || ''), '');
return { prompt, options };
}
return {
prompt: '',
options: { ...defaultOptions, ...stringsOrOptions }
};
}
//# sourceMappingURL=result.js.map