html 从段落元素中抓取内容并传递给OpenAI API进行处理

00jrzges  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(144)

我正在使用OpenAI API构建一个脚本,该脚本从index.html中的点击段落元素中获取文本内容,并将其传递到explanation.html中的单独脚本,其中index.html中点击段落的内容被传递到explanation.html中的脚本,OpenAI将内容处理为“这句话是什么意思?”+p内容并返回输出,该输出是提供给OpenAI API的p内容的解释。
下面是我使用的代码:
index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Example</title>
    <script type="text/javascript">
      function showExplanation(element) {
        const sentence = element.textContent.trim();

        fetch('/explanation.html?sentence=' + encodeURIComponent(sentence))
          .then(response => response.text())
          .then(explanation => {
            const win = window.open('', '_blank');
            win.document.write('<html><head><title>Explanation</title></head><body><p>' + explanation + '</p></body></html>');
          })
          .catch(error => console.log(error));
      }
    </script>
  </head>
  <body>
    <a href="#" onclick="showExplanation(this)">Sentence 1</a>
    <a href="#" onclick="showExplanation(this)">Sentence 2</a>
    <a href="#" onclick="showExplanation(this)">Sentence 3</a>
  </body>
</html>

explanation.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Explanation</title>
  </head>
  <body>
    <p>Loading...</p>
    <script type="text/javascript">
      const sentence = new URLSearchParams(window.location.search).get('sentence');
      const api_key = 'YOUR_OPENAI_API_KEY_HERE';

      fetch('https://api.openai.com/v1/engines/davinci-codex/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + api_key
        },
        body: JSON.stringify({
          'prompt': "What does this sentence mean? " + sentence,
          'max_tokens': 512,
          'n': 1,
          'stop': '.'
        })
      })
        .then(response => response.json())
        .then(output => {
          const explanation = output.choices[0].text;
          const pElement = document.createElement('p');
          pElement.textContent = explanation;
          document.body.innerHTML = '';
          document.body.appendChild(pElement);
        })
        .catch(error => console.log(error));
    </script>
  </body>
</html>

我试着在My live site上运行代码,它似乎被一个"Loading ..."响应卡住了。代码中的静态"Loading ..."没有被从OpenAI API中使用提供的提示符+从p标签中提取的句子获取的动态解释所取代。如何让这个脚本返回动态解释?
编辑:
我编辑了代码以反映Kokodoko提供的localStorage建议。我还将API url替换为Kokodoko提供的url。我现在从OpenAI API获得响应,但它们是乱码,并且输出不反映GPT4中使用相同提示提供的答案。
下面是新代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Example</title>
    <script type="text/javascript">
      function showExplanation(element) {
        const sentence = element.textContent.trim();
        localStorage.setItem('sentence', sentence);
        window.open('/explanation.html', '_blank');
      }
    </script>
  </head>
  <body>
    <a href="#" onclick="showExplanation(this)">Sentence 1</a>
    <a href="#" onclick="showExplanation(this)">Sentence 2</a>
    <a href="#" onclick="showExplanation(this)">Sentence 3</a>
  </body>
</html>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Explanation</title>
  </head>
  <body>
    <p>Loading...</p>
    <script type="text/javascript">
      const sentence = localStorage.getItem('sentence');

      fetch('https://api.openai.com/v1/engines/davinci/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer API_KEY' // replace with your API key
        },
        body: JSON.stringify({
          'prompt': 'What does this sentence mean? ' + sentence,
          'temperature': 0.5,
          'max_tokens': 50
        })
      })
        .then(response => response.json())
        .then(output => {
          const explanation = output.choices[0].text.trim();
          const pElement = document.createElement('p');
          pElement.textContent = explanation;
          document.body.innerHTML = '';
          document.body.appendChild(pElement);
        })
        .catch(error => console.log(error));
    </script>
  </body>
</html>

编辑2:
我已经重新编写了脚本,这样就不需要单独的explanation.html页面了,而是在index.html中弹出的警告框中显示OpenAI API的输出。
下面是新代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Example</title>
    <script type="text/javascript">
      function showExplanation(element) {
        const sentence = element.textContent.trim();

        fetch('https://api.openai.com/v1/engines/davinci/completions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'
          },
          body: JSON.stringify({
            prompt: "What does this sentence mean? " + sentence,
            max_tokens: 128,
            temperature: 0.5
          })
        })
          .then(response => response.json())
          .then(output => {
            const explanation = output.choices[0].text.trim();
            alert(explanation);
          })
          .catch(error => console.log(error));
      }
    </script>
  </head>
  <body>
    <a href="#" onclick="showExplanation(this)">When push comes to shove in a situation defined by opposition deemed as evil according to the way the opponent dismisses any honor you show you must not expect that what corners you will let up for any premature retreat you make becomes bound to come back as a weakened ability to fight off attacks made on you.</a>
  </body>
</html>

我现在从OpenAI API得到了一个响应,但是这个响应是不连贯的,没有意义,并且当使用相同的提示时,与GPT4输出的响应不相比较(这句话是什么意思?+“句子”)。我已经包含了一个示例句子,它被发布到OpenAI API以供调试时参考。

rn0zuynd

rn0zuynd1#

对我来说,当我用一个简单的提示符测试时,连接就能工作。要测试OpenAI是否工作,你可以用一个基本的提示符测试。
如果它对您不起作用,您在控制台中得到的错误消息是什么?
要一次只关注一个问题,现在只需忽略localStorage和DOM操作,首先让fetch在控制台消息中工作。
我使用了一个与你的代码略有不同的URL。

<script type="text/javascript">
        const sentence = "can you create a recipe for salad and fries?"
        const url = "https://api.openai.com/v1/engines/davinci/completions";
        const bearer = 'Bearer ' + 'yourkeyhere'

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': bearer
            },
            body: JSON.stringify({
                'prompt': sentence,
                'temperature': 0.5,
                'max_tokens': 50
            })
        })
            .then(response => response.json())
            .then(output => {
                console.log(output)
            })
            .catch(error => console.log(error));
    </script>

相关问题