-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathselfDebug.js
161 lines (137 loc) · 4.68 KB
/
selfDebug.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
const fs = require("fs");
const cp = require("child_process");
const colors = require("colors");
const yargs = require("yargs/yargs");
const { hideBin } = require("yargs/helpers");
const { Configuration, OpenAIApi } = require("openai");
const diff = require("diff");
const prettier = require("prettier");
require("dotenv").config();
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
function runScript(scriptName) {
return new Promise((resolve, reject) => {
cp.execFile(process.execPath, [scriptName], (error, stdout, stderr) => {
if (error) {
reject({ error, stdout });
} else {
resolve(stdout);
}
});
});
}
async function sendErrorToGpt(filePath, errorMessage, model) {
const fileLines = fs.readFileSync(filePath, "utf-8").split("\n");
const fileWithLines = fileLines
.map((line, i) => `${i + 1}: ${line}`)
.join("\n");
const initialPromptText = fs.readFileSync("prompt.txt", "utf-8");
const prompt =
initialPromptText +
"\n\n" +
"Here is the script that needs fixing:\n\n" +
`${fileWithLines}\n\n` +
"Here is the error message:\n\n" +
`${errorMessage}\n` +
"Please provide your suggested changes, and remember to stick to the " +
"exact format as described above.";
const response = await openai.createChatCompletion({
model,
messages: [
{
role: "user",
content: prompt,
},
],
temperature: 1.0,
});
return response.data.choices[0].message.content.trim();
}
function applyChanges(filePath, changesJson) {
const originalFileLines = fs.readFileSync(filePath, "utf-8").split("\n");
const changes = JSON.parse(changesJson);
const operationChanges = changes.filter((change) => "operation" in change);
const explanations = changes
.filter((change) => "explanation" in change)
.map((change) => change.explanation);
operationChanges.sort((a, b) => b.line - a.line);
const fileLines = [...originalFileLines];
for (const change of operationChanges) {
const { operation, line, content } = change;
if (operation === "Replace") {
fileLines[line - 1] = content + "\n";
} else if (operation === "Delete") {
fileLines.splice(line - 1, 1);
} else if (operation === "InsertAfter") {
fileLines.splice(line, 0, content + "\n");
}
}
const content = fileLines.join("\n");
const formattedContent = prettier.format(content, { parser: "babel" });
fs.writeFileSync(filePath, formattedContent);
console.log(colors.brightCyan("Explanations:"));
for (const explanation of explanations) {
console.log(colors.cyan(`- ${explanation}`));
}
console.log(colors.brightCyan("\nChanges:"));
const createTwoFilesPatch = diff.createTwoFilesPatch;
const patchDiff = createTwoFilesPatch(
"",
"",
originalFileLines.join("\n"),
fileLines.join("\n")
);
for (const line of patchDiff.split("\n")) {
if (line.startsWith("+")) {
console.log(colors.green(line));
} else if (line.startsWith("-")) {
console.log(colors.red(line));
} else {
console.log(line);
}
}
}
async function main() {
console.log(colors.brightGreen("Attempting to run script"));
const argv = yargs(hideBin(process.argv))
.option("scriptName", { type: "string", demandOption: true })
.option("revert", { type: "boolean", default: false })
.option("model", { type: "string", default: "gpt-4" }).argv;
const { scriptName, revert, model } = argv;
if (revert) {
const backupFile = scriptName + ".bak";
if (fs.existsSync(backupFile)) {
fs.copyFileSync(backupFile, scriptName);
console.log(`Reverted changes to ${scriptName}`);
process.exit(0);
} else {
console.log(`No backup file found for ${scriptName}`);
process.exit(1);
}
}
fs.copyFileSync(scriptName, scriptName + ".bak");
while (true) {
try {
const output = await runScript(scriptName);
console.log("=========================================");
console.log(colors.blue("Script ran successfully."));
console.log(colors.brightCyan("Output:"));
console.log(colors.blue(output || "None"));
break;
} catch ({ error, stdout }) {
console.log("=========================================");
console.log(colors.blue("Script crashed. Trying to fix..."));
console.log(colors.brightCyan("Output:"));
console.log(colors.cyan(stdout));
const jsonResponse = await sendErrorToGpt(scriptName, stdout, model);
applyChanges(scriptName, jsonResponse);
console.log(colors.blue("Changes applied. Rerunning..."));
}
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});