-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathopenai.js
61 lines (51 loc) · 1.42 KB
/
openai.js
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
require('dotenv').config();
const { Configuration, OpenAIApi } = require('openai');
const fs = require('fs');
// Set color codes
const reset = '\x1b[0m';
const green = '\x1b[32m';
// Define a function to get a response from the OpenAI API.
// Documentation: https://platform.openai.com/docs/guides/chat
const getResponse = async (openai, request) => {
const completion = await openai.createChatCompletion(request);
const review = completion.data?.choices[0]?.message?.content;
return review;
};
// Get the file path from the command line.
const filePath = process.argv[2];
if (!filePath) {
console.error('Please provide a file path.');
process.exit(1);
}
// Read the file and get the code.
const code = fs.readFileSync(filePath, 'utf-8');
// Build the prompt for OpenAI API.
const prompt = `
Review the code below and provide feedback on how to improve it.
${code}
`
if (prompt == null) {
console.error('Please provide a valid command.');
process.exit(1);
}
// Config OpenAI API.
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
// Get a response from OpenAI API.
getResponse(openai, {
model: "gpt-3.5-turbo",
messages: [
{
role: "user",
content: prompt
}
]
})
.then((response) => {
console.log(`${green}Review ${filePath}:${reset}\n${response}${reset}\n`);
})
.catch((error) => {
console.error(error);
})