Last active
August 7, 2023 13:33
-
-
Save KrishnaPG/750b51c71e3d68474f36c721e06e4e6e to your computer and use it in GitHub Desktop.
OpenAI based SQL chat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Configuration, OpenAIApi } = require("openai"); | |
const readline = require("readline"); | |
const configuration = new Configuration({ | |
apiKey: "sk-iHm1lxxxxxxxxxxxxxxWRgOB8DAJUcMK0Jhq", | |
}); | |
const openai = new OpenAIApi(configuration); | |
var stdin = process.openStdin(); | |
var rl = readline.createInterface(process.stdin, process.stdout); | |
rl.setPrompt("SQL Query> "); | |
rl.prompt(); | |
rl.on("line", async function (line) { | |
if (line === "exit") return rl.close(); | |
const input = line.trim(); | |
openai | |
.createChatCompletion({ | |
model: "gpt-3.5-turbo", | |
messages: [ | |
{ | |
role: "user", | |
content: "Return ONLY SQL for " + input, | |
}, | |
], | |
}) | |
.then((completion) => { | |
console.log(completion.data.choices[0].message.content); | |
}) | |
.catch((ex) => { | |
const error = ex.response?.data?.error; | |
console.error(error || ex.message); | |
}) | |
.finally(() => rl.prompt()); | |
}).on("close", function () { | |
process.exit(0); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This allows you to enter data queries in natural language and get back the SQL commands using OpenAI API. For example, enter "Create employees table" and the AI will reply with the SQL commands required to create an employee table. Nice thing is it automatically suggests the fields in the table.