To use the ChatGPT API in HTML, you'll need to make a GET request to the API endpoint and pass your prompt as a parameter. This can be done entirely within the HTML using client-side JavaScript. Here's an example HTML code that demonstrates how to use the ChatGPT API to get an answer to a given prompt:

<!DOCTYPE html>
<html>
  <head>
    <title>ChatGPT API Example</title>
  </head>
  <body>
    <h1>ChatGPT API Example</h1>
    <form>
      <label for='prompt'>Prompt:</label>
      <input type='text' id='prompt' name='prompt'><br><br>
      <label for='answer'>Answer:</label>
      <input type='text' id='answer' name='answer'><br><br>
      <button type='button' onclick='getAnswer()'>Get Answer</button>
    </form>
    <script>
      function getAnswer() {
        var prompt = document.getElementById('prompt').value;
        var url = 'https://api.openai.com/v1/engines/davinci-codex/completions?prompt=' + prompt + '&max_tokens=100';
        fetch(url, {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer YOUR_API_KEY'
          }
        })
        .then(response => response.json())
        .then(data => {
          var answer = data.choices[0].text;
          document.getElementById('answer').value = answer;
        })
        .catch(error => console.error(error));
      }
    </script>
  </body>
</html>

This example features a form with two textboxes: one for the prompt and one for the answer. Clicking the 'Get Answer' button triggers the getAnswer() function.

The getAnswer() function retrieves the prompt from the textbox, constructs a URL for the ChatGPT API endpoint, and makes a GET request. The prompt is passed as a parameter, and max_tokens is set to 100 to limit the response length.

The fetch() function makes the GET request, including your API key in the Authorization header. The response is parsed as JSON, and the answer is extracted from the first choice returned by the API.

Finally, the answer textbox is updated with the response from the API. Remember to replace YOUR_API_KEY with your actual ChatGPT API key.

ChatGPT API HTML Integration: Get Answers Without Server-Side Coding

原文地址: https://www.cveoy.top/t/topic/lDgK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录