I am trying to send a request through js in my html so that openai analyzes it and sends a response, but if in the js I put the following:
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: "sk-0000000000000ZXXXXXXXXXXXXXX",
});
const openai = new OpenAIApi(configuration);
async function test() {
console("test")
const response = await openai.createCompletion("text-davinci-002", {
prompt: "hello",
temperature: 0.7,
max_tokens: 64,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
console.log(response)
}
test();
return console these error
Uncaught ReferenceError: require is not defined
at buttons.js:94:38
I have tried to install it with node.js and it works fine but I don't know how to make it work in my own html
It took me a little while to figure this out.
Use the javascript as you would normally. The code will console log the response. You can change that to use the response in some other way in your code.
Tested and working examples (You could just adjust these examples to meet your needs):
Regular prompt:
let open_ai_response;
openai_test();
async function openai_test() {
var url = "https://api.openai.com/v1/engines/text-davinci-002/completions";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer YOUR_OPEN_AI_KEY_GOES_HERE");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
open_ai_response = xhr.responseText;
console.log(open_ai_response);
}};
var data = `{
"prompt": "YOUR TEXT HERE.",
"temperature": 0.7,
"max_tokens": 256,
"top_p": 1,
"frequency_penalty": 0.75,
"presence_penalty": 0
}`;
xhr.send(data);
}
Using variables for the prompt:
let open_ai_response;
openai_test();
async function openai_test() {
var prompt_text = "YOUR TEXT HERE."
var prompt_text2 = "MORE TEXT HERE."
var url = "https://api.openai.com/v1/engines/text-davinci-002/completions";
var xhr = new XMLHttpRequest();
xhr.open("POST", url);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer YOUR_OPEN_AI_KEY_GOES_HERE");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
open_ai_response = xhr.responseText;
console.log(open_ai_response);
}};
var data = `{
"prompt": "${prompt_text + prompt_text2}",
"temperature": 0.7,
"max_tokens": 256,
"top_p": 1,
"frequency_penalty": 0.75,
"presence_penalty": 0
}`;
xhr.send(data);
}