Skip to content

Instantly share code, notes, and snippets.

@mkagenius
Created March 25, 2023 09:23
Show Gist options
  • Save mkagenius/9f385dfebfc2fea713a6d7842825a932 to your computer and use it in GitHub Desktop.
Save mkagenius/9f385dfebfc2fea713a6d7842825a932 to your computer and use it in GitHub Desktop.
Chat GPT CLI for folks who have API access, `npm install openai` and `npm install @clack/prompts` . Replace keys.
const { intro, isCancel, outro, spinner, text } = require('@clack/prompts');
const prompts = require('@clack/prompts');
const { Configuration, OpenAIApi } = require('openai');
// Set up the OpenAI API client
const configuration = new Configuration({
apiKey: OPENAI_API_KEY,
organization: OPENAI_ORG_ID
});
const openaiClient = new OpenAIApi(configuration);
const askChatGPT = async (question, messages) => {
const prompt = {
messages: [],
};
for (let i = Math.max(messages.length - 20, 0); i < messages.length; i++) {
const m = messages[i];
prompt.messages.push({
role: i % 2 === 0 ? 'user' : 'assistant',
content: m,
});
}
prompt.messages.push({
role: 'user',
content: question,
});
const response = await openaiClient.createChatCompletion({
model: 'gpt-3.5-turbo',
messages: prompt.messages,
});
// Print the response from the OpenAI API
return response.data.choices[0].message.content;
};
(async () => {
const s = spinner();
const messages = [];
intro("Let's talk to ChatGPT (Ctrl-C or enter to end the conversation)...");
while (true) {
const question = await text({
message: 'How can I help?',
});
if (isCancel(question) || !question || question.trim().length === 0) break;
s.start('Thinking...');
const answer = await askChatGPT(question, messages);
messages.push(question, answer);
s.stop(`Response: ${answer}`);
}
outro('Tokens used: X ($0.0Y cost). See you next time!');
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment