Created
April 29, 2023 18:24
-
-
Save signalwerk/cd3afd77ac0667fb7c050e221cc2fa7d to your computer and use it in GitHub Desktop.
Minimal ChatGPT request to the OpenAI-API
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
// This code sends a prompt to the OpenAI API and then outputs the response | |
// to the terminal and to a file. | |
// Setup: | |
// npm init -y && npm i dotenv node-fetch | |
// echo "OPENAI_API_KEY=sk-XXX" > .env | |
import fs from "fs"; | |
import fetch from "node-fetch"; | |
import * as dotenv from "dotenv"; | |
dotenv.config(); | |
const { OPENAI_API_KEY } = process.env; | |
const prompt = `please write me a hello-world program in JavaScript`; | |
const requestOptions = { | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
Authorization: `Bearer ${OPENAI_API_KEY}`, | |
}, | |
body: JSON.stringify({ | |
model: "gpt-3.5-turbo", | |
// temperature: 0, // to have no randomnes | |
messages: [ | |
{ | |
role: "system", | |
content: `You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible. Knowledge cutoff: 2021-09-01. Current date: ${new Date() | |
.toISOString() | |
.slice(0, 10)}`, | |
}, | |
{ role: "user", content: prompt.trim() }, | |
], | |
}), | |
}; | |
console.log("start"); | |
fetch("https://api.openai.com/v1/chat/completions", requestOptions) | |
.then((response) => response.json()) | |
.then((data) => { | |
fs.writeFileSync("out.json", JSON.stringify(data, null, 2)); | |
// write raw answer to file | |
let answer = data.choices[0].message.content; | |
fs.writeFileSync("out.txt", answer); | |
console.log(answer); | |
console.log("done"); | |
}) | |
.catch((error) => console.error(error)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment