osr-mono/packages/osr-ai/commands/chatgpt-ex.js
2025-01-29 18:17:03 +01:00

218 lines
8.6 KiB
JavaScript

"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.register = void 0;
const path = __importStar(require("path"));
const read_1 = require("@plastichub/fs/read");
const write_1 = require("@plastichub/fs/write");
const exists_1 = require("@plastichub/fs/exists");
const osr_commons_1 = require("@plastichub/osr-commons");
const osr_commons_2 = require("@plastichub/osr-commons");
const __1 = require("../");
const _cli_1 = require("../_cli");
const filters_1 = require("../lib/filters");
const args_1 = require("../lib/args");
const openai_1 = require("../lib/openai");
const primitives_1 = require("@plastichub/core/primitives");
const defaultOptions = (yargs) => {
yargs.parserConfiguration({
"camel-case-expansion": false
});
return yargs.option('debug', {
default: false,
describe: 'debug messages',
type: 'boolean'
}).option('append', {
default: false,
describe: 'append to file instead of overwriting',
type: 'boolean'
}).option('showPrompt', {
default: false,
describe: 'insert prompt in output',
type: 'boolean'
}).option('cache', {
default: true,
describe: 'Enable cache',
type: 'boolean'
}).option('alt', {
default: false,
describe: 'Use alternative path variable token separator',
type: 'boolean'
}).option('query', {
description: 'query',
default: "list all towns of barcelona, as typescript enum, with gps coords, as strings"
}).option('dst', {
description: 'Destination output path',
_default: './tests/chatgpt/last.ts'
}).option('env_key', {
default: 'OSR-CONFIG',
describe: 'Environment key to the config path'
}).option('api_key', {
describe: 'OpenAI key'
}).option('model', {
describe: 'OpenAI Model',
default: "gpt-4o"
}).option('system', {
describe: 'Path to system instructions'
}).option('source', {
describe: 'Path to a source file'
}).option('response_format', {
describe: 'Format of the response (for transcribe)',
default: "text"
}).option('filters', {
describe: `An array of filters to apply to the response: JSON : ${Object.keys(filters_1.Filters)} `,
default: ""
}).option('files', {
describe: `List of files to attach to the query: String|Glob`
}).option('logLevel', {
describe: `Log level: warn|info|trace|debug|error|fatal`,
default: 'info'
}).option('gui', {
describe: `GUI: electron|puppeteer`,
default: false
}).option('prompts', {
describe: `Path to prompts file, JSON - Array`,
default: '${OSR_ROOT}/osr-ai-templates/prompts/documents.json',
type: 'string'
});
};
let options = (yargs) => defaultOptions(yargs);
const register = (cli) => {
return cli.command('chatgpt-ex <verb>', 'Prompt ChatGPT - Ex', options, async (argv) => {
(0, _cli_1.defaults)();
if (argv.help) {
return;
}
const args = argv;
const verb = args.verb || 'prompt';
const config = (0, osr_commons_1.CONFIG_DEFAULT)(args.env_key);
if (!config) {
__1.logger.warn('No config found!');
return;
}
if (config && !config.openai.key) {
__1.logger.warn('No OpenAI key found in config!');
return;
}
const variables = Object.assign({}, ...Object.keys(argv).filter((k) => k.startsWith('var-')).map((k) => {
return {
[k.replace('var-', '')]: argv[k]
};
}));
const opts = {
query: argv.query,
...argv,
dst: args.dst,
source: argv.source ? path.resolve((0, osr_commons_2.resolve)(args.source)) : undefined,
system: argv.system ? path.resolve((0, osr_commons_2.resolve)(args.system)) : undefined,
api_key: argv.openai_key || process.env.OPENAI_API_KEY || config.openai.key,
variables
};
__1.logger.debug('Options', opts);
const filters = (opts.filters || "").split(',');
opts.filters = [];
filters.forEach((f) => {
if (filters_1.Filters[f]) {
(opts.filters).push(filters_1.Filters[f]);
}
});
if (opts.cache === true && (0, exists_1.sync)(opts.dst)) {
__1.logger.debug('Output file already exists, skipping');
return;
}
if (!opts.api_key) {
__1.logger.error('No OpenAI key found in config or options!');
return;
}
if (!opts.query) {
__1.logger.error('No query specified');
return;
}
__1.logger.debug('Options', opts);
return new Promise(async (resolve, reject) => {
switch (verb) {
case 'prompt': {
if (opts.source && !(0, exists_1.sync)(opts.source)) {
__1.logger.error('Source specified but file not found', opts.source);
return;
}
const src = opts.source && (0, exists_1.sync)(opts.source) ? (0, read_1.sync)(opts.source, 'string') : '';
const stdin = await (0, args_1.readPipedInput)() || src || '';
let q = stdin ? `${opts.query} : "${stdin}"` : opts.query;
const queryPath = path.resolve((0, osr_commons_2.resolve)(opts.query));
if ((0, exists_1.sync)(queryPath)) {
q = (0, read_1.sync)(queryPath);
}
opts.query = `${opts.query} : ${src}`;
let ret = await (0, openai_1.queryEx)(opts.api_key, opts);
if (opts.filters) {
opts.filters.forEach((f) => {
let _ret = f(ret);
if ((0, primitives_1.isString)(_ret) && _ret.length > 0) {
ret = _ret;
}
});
}
if (opts.dst) {
let header = `${argv.showPrompt ? `// ${q}` : ''}\n`;
let content = `${argv.append ? (0, read_1.sync)(opts.dst) || '' : ''}\n${header}${ret}`;
(0, write_1.sync)(opts.dst, content);
}
if ((0, primitives_1.isString)(ret) || Buffer.isBuffer(ret)) {
process.stdout.write(ret);
}
else {
__1.logger.warn('Invalid response: not a string or buffer');
}
break;
}
case 'transcribe': {
const ret = await (0, openai_1.transcribe)(opts.query, opts.api_key, opts.dst, {
...opts
});
if (ret && opts.dst) {
(0, write_1.sync)(opts.dst, ret);
}
process.stdout.write(ret);
break;
}
}
resolve(1);
process.exit(0);
});
});
};
exports.register = register;
//# sourceMappingURL=chatgpt-ex.js.map