xxxxxxxxxx
65
// You can go to https://platform.openai.com/account/api-keys
// To get a API key
// my api key called "language-project": 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
const API_KEY = "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";
const url = "https://api.openai.com/v1/completions";
let options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
};
let myButton, myInput, myOutput;
let myOutputText = '';
function setup() {
noCanvas();
background(200);
myButton = createButton("Submit");
myButton.position(512, 120);
myButton.mousePressed(getText);
myButton.elt.style.fontSize = "20px";
myInput = createInput("What is p5.js?");
myInput.position(0, 120);
myInput.size(500);
myInput.elt.style.fontSize = "20px";
myOutput = createElement("p", "Results:");
myOutput.position(0, 150);
}
function getText() {
const inputValue = myInput.value();
console.log("myinput", inputValue);
if (!inputValue || inputValue.length <= 0) {
return;
}
// You can go to https://platform.openai.com/examples to find one example you like
// And copy paste the sample optiosn with "node.js"
// Don't forget to still include inputValue in the prompt
options.body = JSON.stringify({
model: "text-davinci-003",
prompt: inputValue,
temperature: 0.7,
max_tokens: 64,
top_p: 1.0,
frequency_penalty: 0.0,
presence_penalty: 0.0,
});
fetch(url, options)
.then((response) => {
console.log("response", response);
const res = response.json();
return res;
})
.then((response) => {
if (response.choices && response.choices[0]) {
myOutputText += '<br/>Q:' + inputValue + '<br/>A:' + response.choices[0].text;
myOutput.html(myOutputText);
}
});
}