@abhagsain/ai-cli
Version:
Get answers for CLI commands from GPT3 right from your terminal
107 lines (106 loc) • 4.05 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const core_1 = require("@oclif/core");
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const inquirer = tslib_1.__importStar(require("inquirer"));
const index_1 = require("../helpers/index");
const openai_1 = tslib_1.__importDefault(require("openai"));
class AI extends core_1.Command {
async getAnswersFromGPT3({ question, API_KEY, }) {
var _a;
const openai = new openai_1.default({
apiKey: API_KEY || process.env.OPENAI_API_KEY,
});
const messages = (0, index_1.getDefaultMessages)();
const { name: model } = (0, index_1.getCurrentModel)(this.config.configDir);
try {
const response = await openai.chat.completions.create({
model: model,
messages: [...messages, { role: "user", content: question }],
temperature: 0.8,
max_tokens: 64,
frequency_penalty: 0.5,
presence_penalty: 0,
stop: ['"""'],
});
const code = /`(.*?)`/;
const value = ((_a = response.choices[0].message.content) === null || _a === void 0 ? void 0 : _a.trim()) || "";
const matches = value.match(code) || [];
const match = matches.length > 1 ? matches[1] : value;
return match;
}
catch (error) {
// Error handling as suggested in openai v3->v4 migration guide
// https://github.com/openai/openai-node/discussions/217
if (error instanceof openai_1.default.APIError) {
throw new Error(JSON.stringify({
status: error.status,
message: error.message,
code: error.code,
type: error.type,
}));
}
else
throw new Error(error.message);
}
}
async showOptions(answer) {
const choices = ["Copy to clipboard", "Exit"];
const prompt = await inquirer.prompt([
{
name: "command",
message: "Select an option",
type: "list",
choices,
},
]);
const { command } = prompt;
switch (command) {
case "Copy to clipboard": {
const clipboardy = (await import("clipboardy")).default;
clipboardy.writeSync(answer);
break;
}
default: {
return;
}
}
}
async run() {
const API_KEY = await (0, index_1.getOpenAIKey)(this.config.configDir);
if (!API_KEY) {
this.log("You haven't set your OpenAI API key. Please login with", chalk_1.default.bold.yellow("ai auth"));
return;
}
const { args } = await this.parse(AI);
const { question } = args;
core_1.CliUx.ux.action.start("");
const answer = await this.getAnswersFromGPT3({
question: question.trim(),
API_KEY,
});
core_1.CliUx.ux.action.stop("");
if (answer.toLowerCase().startsWith("sorry")) {
this.log(answer);
return;
}
this.log(`> ${chalk_1.default.green(`Command is`)} ${chalk_1.default.bold.yellowBright(`\`${answer}\``)}\n`);
await this.showOptions((answer || "").trim());
this.log(`${chalk_1.default.red("Please don't run a command that you don't understand.")} ${chalk_1.default.underline.red("Especially destructive commands")} `);
}
}
exports.default = AI;
AI.description = "Ask question to GPT3 from your terminal";
AI.usage = "ask [question]";
AI.help = `ai ask "Check if a remote port is open"`;
AI.args = [
{
name: "question",
description: "Your question",
required: true,
},
];
AI.examples = [
`$ <%= config.bin %> <%= command.id %> "Check running process on port 3000"`,
];