-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (74 loc) · 2.08 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import OpenAI from "openai";
import fs from 'fs/promises';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function getCodeFromFile(filePath) {
try {
const code = await fs.readFile(filePath, 'utf-8');
return code;
} catch (error) {
throw new Error(`Error reading file: ${error.message}`);
}
}
async function detectLanguage(filePath) {
const fileExtension = filePath.split('.').pop().toLowerCase();
// Add more cases for other languages as needed
switch (fileExtension) {
case 'js':
return 'javascript';
case 'py':
return 'python';
case 'html':
return 'html';
case 'php':
return 'php';
case 'cpp':
return 'cpp';
case 'java':
return 'java';
case 'css':
return 'css';
case 'sql':
return 'sql';
// Add more cases for other languages
default:
throw new Error(`Unsupported file type: ${fileExtension}`);
}
}
async function main() {
const codeFilePath = 's.sql'; // Provide the actual path to your code file
try {
const code = await getCodeFromFile(codeFilePath);
const language = await detectLanguage(codeFilePath);
const explainCommand = process.argv[2];
if (explainCommand && explainCommand.toLowerCase() === `explain`) {
const response = await openai.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [
{
"role": "system",
"content": `explain the ${language} code`
},
{
"role": "user",
"content": code
}
],
temperature: 1,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
// Access the assistant's response within the choices array
const assistantResponse = response.choices[0].message.content;
console.log('Assistant\'s Response:', assistantResponse);
} else {
console.log(`To explain the ${language} code, run: node yourscript.js "explain ${language}"`);
}
} catch (error) {
console.error(error.message);
}
}
main();