Javascript  

 

 

 

 

 

Davinci API

 

This note is to show how to utilize OpenAPI engine with API. The script here is also generated by chatGPT. Code is simple but debugging was not as easy as I thought. I had similar difficulties not only with this application, but also with most of other application that need to use library from remote server (e.g, various cdn servers). Especially when the problem happens at initial connection with the server (e.g, 404 errors), chatGPT couldn't point out exact root cause of the failure unless the server provide any detailed information for the error. Unfortunately most of those servers would not provide much detailed information about the failure.

 

NOTE : Based on what I observed, when chatGPT write code using cdn or other remote library, it tend to use older version of server url which often cause many problems.  I would recommend you to visit the sites that provides the server and read latest document (or latest sample script) on the site and use the server url in the latest document or sample script.

 

 

 

Prerequisite

 

I usually got many errors at the initial execution of the script and it was not straightfoward to find the root cause. Most of the initial failure with API server connection would be related to following items. I would suggest you to visit the API document site and get the latest information at your hand before you start scripting.

  • Get your API Key : Visit this page to get
  • Install the required package : If you want to write a script using nodejs, you would need to install axios package.
  • Confirm the end point : Visit this page for reference (You may not want to do this unless you get some kind of access error)

 

 

 

nodejs

 

This is a simple template to get access to davinci text model in Javascript for nodejs. This is also written by chatGPT. It may or may not work by the time when you want to try by yourself. I would suggest you to visit the API site and double check on the information highlighed in red.

chatGPT_ex02.js

const axios = require('axios');

const readline = require('readline');

 

const API_KEY = 'YOUR API KEY';  // Get your own API key and paste it here.

 

const rl = readline.createInterface({

  input: process.stdin,

  output: process.stdout

});

 

const askQuestion = () => {

  rl.question('What is your question? ', (question) => {

    const options = {

      method: 'post',

      url: 'https://api.openai.com/v1/engines/davinci/completions',

      headers: {

        'Content-Type': 'application/json',

        'Authorization': `Bearer ${API_KEY}`

      },

      data: {

        prompt: question,

        temperature: 0.5,

        max_tokens: 256

      }

    };

 

    axios(options)

    .then(response => {

      console.log(response.data.choices[0].text);

      askQuestion();

    })

    .catch(error => {

      console.log(error);

      askQuestion();

    });

  });

};

 

askQuestion();

 

 

 

 

 

html

 

This is a simple template to get access to davinci text model in Javascript for html. This is also written by chatGPT. It may or may not work by the time when you want to try by yourself. I would suggest you to visit the API site and double check on the information highlighed in red.

OpenAI_Text_003.html

 

<!DOCTYPE html>

<html>

  <head>

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script>

  // Function to call OpenAI API

  async function completeText(prompt) {

    const responseField = document.getElementById("response");

    try {

      // Your OpenAI API key

      const apiKey = "YOUR_API_KEY"; // Get your own API key and paste it here.

      // Endpoint for text completion

      const endpoint = "https://api.openai.com/v1/completions";

      // Parameters for the API call

      const params = {

        prompt: prompt,

        model: "text-davinci-003",

        max_tokens: 500,

        n: 1

      };

      // Headers for the API call

      const headers = {

        "Content-Type": "application/json",

        "Authorization": `Bearer ${apiKey}`

      };

      // Make the API call

      const response = await axios.post(endpoint, params, { headers });

      // Return the completed text

      // console.log(response.data.choices[0].text);

      responseField.textContent =   response.data.choices[0].text;  

      return response.data.choices[0].text;

    } catch (error) {

      console.error(error);

    }

  }

</script>

 

  </head>

  <body>

    <textarea id="prompt" cols="80" rows="10"></textarea>

    <p>

    <button onclick="document.getElementById('completed').innerHTML = completeText(prompt.value)">Complete Text</button>

    </p>

    <p id="completed"></p>

    <p>

    <textarea id="response" cols="80" rows="20"></textarea>

    </p>

  </body>

</html>