Skip to content

Instantly share code, notes, and snippets.

@hiroppy
Last active March 4, 2023 12:07
Show Gist options
  • Save hiroppy/a6b6c721e7a3df15c92532dcefe5b284 to your computer and use it in GitHub Desktop.
Save hiroppy/a6b6c721e7a3df15c92532dcefe5b284 to your computer and use it in GitHub Desktop.
communicating with chatGPT
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
const token = "your-token";
const messages = [];
const rl = readline.createInterface({ input, output });
rl.prompt();
rl.on('line', async (line) => {
const res = await fetchData(line);
console.log();
console.log(`\x1b[33m ${res.trim()} \x1b[0m`);
console.log();
rl.prompt();
});
async function fetchData(content) {
messages.push({ role: "user", content });
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages,
}),
}).then((res) => res.json());
const message = res.choices[0].message;
messages.push(message);
return message.content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment