NodeJS 如何通过js在html中加载openai API配置?

bnl4lu3b  于 2022-12-22  发布在  Node.js
关注(0)|答案(1)|浏览(1488)

我试图通过js在我的html中发送一个请求,以便openai分析它并发送一个响应,但如果在js中我放了以下内容:

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();

返回控制台这些错误

Uncaught ReferenceError: require is not defined
at buttons.js:94:38

我试着用node.js安装它,它工作正常,但我不知道如何使它在我自己的html中工作

vyu0f0g1

vyu0f0g11#

我花了点时间才弄明白。
1.转到https://beta.openai.com/playground并选择所需的设置。
1.然后,单击右上角的“查看代码”。
1.选择“curl”作为您要查看的代码类型。
1.复制“curl”代码。
1.请转到:https://reqbin.com/req/javascript/c-wyuctivp/convert-curl-to-javascript
1.将代码从“curl”转换为“javascript/ AJAX ”。这将把它从“curl”更改为javascript/AJAX XMLHttpRequest。
像平常一样使用javascript。代码将控制台记录响应。你可以在代码中以其他方式使用响应。
测试和工作示例(您可以调整这些示例以满足您的需要,但最好创建自己的示例以获得您想要的确切结果):
常规提示:

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);
}

将变量用于提示:

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);
}

相关问题