Skip to content

Instantly share code, notes, and snippets.

@leenattress
Created October 3, 2023 09:45
Show Gist options
  • Save leenattress/66438b000fece019f09de881089169d4 to your computer and use it in GitHub Desktop.
Save leenattress/66438b000fece019f09de881089169d4 to your computer and use it in GitHub Desktop.
NodeJs OpenAI in the terminal.

Give the chatbot your OpenAI key like this:

export OPENAI_API_KEY=zxzxzxzxzxzxzxzxxzxz

Install the deps:

npm install

Run it:

node app.js

const OpenAI = require("openai");
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
async function getOpenAIResponse(prompt) {
const response = await openai.chat.completions.create({
messages: [{ role: "user", content: prompt }],
model: "gpt-3.5-turbo",
max_tokens: 150,
});
return response?.choices[0]?.message?.content;
}
async function chatLoop() {
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
while (true) {
const userInput = await new Promise(resolve => readline.question('🤔: ', resolve));
if (userInput.toLowerCase() === 'exit') {
readline.close();
break;
}
const response = await getOpenAIResponse(userInput);
console.log(`🤖: ${response}`);
console.log('---');
}
}
async function main() {
console.log('Ask a question...');
await chatLoop();
}
main().catch(console.error);
{
"name": "openai-chatbot",
"version": "1.0.0",
"description": "A simple terminal chatbot using OpenAI",
"main": "app.js",
"scripts": {
"start": "node app.js"
},
"dependencies": {
"openai": "^4.11.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment