Skip to content

Instantly share code, notes, and snippets.

@KrishnaPG
Last active August 7, 2023 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KrishnaPG/750b51c71e3d68474f36c721e06e4e6e to your computer and use it in GitHub Desktop.
Save KrishnaPG/750b51c71e3d68474f36c721e06e4e6e to your computer and use it in GitHub Desktop.
OpenAI based SQL chat
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);
});
@KrishnaPG
Copy link
Author

KrishnaPG commented Aug 7, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment