-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
73 lines (66 loc) · 2.3 KB
/
Copy pathindex.js
File metadata and controls
73 lines (66 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env node
import inquirer from "inquirer";
import OpenAI from "openai";
import { createRequire } from "module";
const require = createRequire(import.meta.url);
const { exec } = require("child_process");
const openAI = new OpenAI({ apiKey: "YOUR_API_KEY" });
inquirer.prompt([{
type: "input",
name: "userInput",
message: "What would you like to perform?",
}]).then((answers) => { runOpenAI(answers.userInput) });
/**
* Call OpenAI API to get the command-line code for the user input
* @param {string} userInput
* @returns {Promise<void>}
*/
const runOpenAI = async (userInput) => {
/**
* Get the response from OpenAI API
* @returns {Promise<string>}
* */
const getOpenAIResponse = async () => {
const completion = await openAI.chat.completions.create({
messages: [{ role: "system", content: `Just return the command-line query to ${userInput}` }],
model: "gpt-3.5-turbo",
});
console.log(completion.choices[0]);
return completion.choices[0]?.message?.content;
};
const openAIResponse = await getOpenAIResponse();
// Run the command-line code upon user's consent
// If not, prompt the user to retry or abort
inquirer
.prompt([
{
type: "list",
name: "execute",
message: "Would you like to execute the generated command?",
choices: ["Yes", "No", "Retry"],
},
])
.then((answers) => {
if (answers.execute === "Yes") {
exec(openAIResponse, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log("Output:\n", stdout);
});
} else if (answers.execute === "Retry") {
inquirer
.prompt([
{
type: "input",
name: "userInput",
message: "What would you like to perform?",
},
])
.then((answers) => {
runOpenAI(answers.userInput);
});
}
});
};