node-ai-chatbot-cli
Version:
A lightweight Node.js package and CLI tool that allows developers to easily interact with OpenAI's ChatGPT API. Supports automated API key setup, simple chatbot creation, and seamless integration into JavaScript applications. Ideal for building AI-powered
49 lines (44 loc) ⢠1.6 kB
JavaScript
require('dotenv').config();
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const prompt = require('prompt-sync')();
class ChatGPTBot {
constructor(apiKey) {
this.apiKey = apiKey || process.env.OPENAI_API_KEY || this.askForApiKey();
this.apiUrl = "https://api.openai.com/v1/chat/completions";
}
askForApiKey() {
console.log("\nš No API key found! Please enter your OpenAI API Key.");
const key = prompt("API Key: ");
if (!key) {
console.error("ā API Key is required!");
process.exit(1);
}
fs.writeFileSync(path.join(__dirname, '.env'), `OPENAI_API_KEY=${key}\n`);
console.log("ā
API Key saved successfully!");
return key;
}
async sendMessage(message, model = "gpt-3.5-turbo") {
try {
const response = await axios.post(
this.apiUrl,
{
model,
messages: [{ role: "user", content: message }],
},
{
headers: {
"Authorization": `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
}
);
return response.data.choices[0].message.content;
} catch (error) {
console.error("ā Error in ChatGPT request:", error.response?.data || error.message);
throw error;
}
}
}
module.exports = ChatGPTBot;