Skip to content

Instantly share code, notes, and snippets.

@shamasis
Created July 9, 2024 11:43
Show Gist options
  • Save shamasis/6ff462e4b6f29af1a50a47ee5909b595 to your computer and use it in GitHub Desktop.
Save shamasis/6ff462e4b6f29af1a50a47ee5909b595 to your computer and use it in GitHub Desktop.
OpenAI CLI chatbot
const OpenAI = require('openai'),
readline = require('readline');
// Initialize OpenAI with API key
const openai = new OpenAI({
apiKey: "" // your-api-key-here
// For extra safety, use the line below, comment the line above and pass the API key as an environment variable:
// apiKey: process.env['OPENAI_API_KEY']
});
// Function to get user input from the command line
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function askQuestionFromUser (query) {
return new Promise(resolve => rl.question(query, resolve));
}
// Function to handle user input and generate AI response
async function chatloop(messages) {
const userInput = await askQuestionFromUser('You: ');
// Magic starts here where we start creating the structured array that holds all conversation
messages.push({ role: 'user', content: userInput });
// Use the openai SDK to now send the message history with every call and get response
const stream = await openai.beta.chat.completions.stream({
model: 'gpt-4',
// We ensure that the entire message history array's first item is a special
// system prompt.
messages: [{ role: 'system', content: 'You are Muppy, a CLI chatbot.' },
...messages],
stream: true,
});
let aiResponse = '';
// Attach stream functions to handle AI response
stream
.on('content', (delta, snapshot) => {
process.stdout.write(delta);
aiResponse += delta;
})
.on('end', () => {
// Add AI's response to the message history
messages.push({ role: 'assistant', content: aiResponse });
console.log('\n');
// Recurse to continue the conversation
chatloop(messages);
});
}
// Start the conversation loop
function main() {
const messages = [];
console.log("Start chatting with the AI. Press Ctrl+C to stop.");
chatloop(messages);
}
// Invoke main function
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment