Created
May 1, 2023 16:34
-
-
Save rocket-pig/b20f8b7976eb00a08b08751741febfea to your computer and use it in GitHub Desktop.
chatGPT node.js CLI chat interface - as simple as posible. npm install openai langchain, then node chatgpt-cli.js and youre there.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//npm install openai langchain | |
async function loadModules() { | |
const openaiModule = await import("langchain/chat_models/openai"); | |
const schemaModule = await import("langchain/schema"); | |
const { ChatOpenAI } = openaiModule; | |
const { HumanChatMessage, SystemChatMessage } = schemaModule; | |
const chat = new ChatOpenAI({ openAIApiKey: 'sk-YOURKEY', temperature: 0 }); | |
// Now you can use the chat object to interact with the model: | |
async function generateOutput(message) { | |
const response = await chat.call([ | |
new HumanChatMessage(message) | |
]); | |
return response; | |
} | |
//chat on a loop until ctrl-c | |
function chatloop() { | |
const readline = require('readline'); | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
rl.prompt() | |
rl.on('line', async (input) => { | |
const response = await generateOutput(input); | |
if ('text' in response) { | |
console.log('\x1b[32m%s\x1b[0m',response.text); | |
} | |
if('error' in response) { | |
console.log('Error:',response.error) | |
} | |
rl.prompt() | |
}); | |
rl.on('SIGINT', () => { | |
rl.close(); | |
}); | |
} | |
chatloop() | |
}//END | |
loadModules().catch(error => { | |
console.error(`Failed to load modules: ${error}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment