Thursday, February 9, 2023

ChatGPT Null Value to API from Google Sheets Error

 Probably nothing, but some interesting results nonetheless. Check out the screenshots for example results.

  1. Create a new Google sheet
  2. Extensions | Apps Script | delete prefilled text
  3. Create function that calls ChatGPT and passes value from another cell to the API (example below that’s floating around) | Replace secret key with yours
  4. Click save project
  5. Navigate to cell B1 and type =AI(A1,0.7)
  6. Pull the formula down to get multiple results
  7. Screenshots of the few of the results below

const SECRET_KEY = "put-your-secret-key-from-openai-api-access-registration-here";

const MAX_TOKENS = 200;

// For more cool AI snippets and demos, follow me on Twitter: https://twitter.com/_abi_

/**

* Completes your prompt with GPT

* @param {string} prompt Prompt

* @param {number} temperature (Optional) Temperature. 1 is super creative while 0 is very exact and precise. Defaults to 0.4.

* @param {string} model (Optional) GPT-3 Model to use. Defaults to "text-davinci-003".

* @return Completion returned by GPT-3

* @customfunction

*/

function AI(prompttemperature = 0.4model = "text-davinci-003") {

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

  const payload = {

    modelmodel,

    promptprompt,

    temperaturetemperature,

    max_tokensMAX_TOKENS,

  };

  const options = {

    contentType"application/json",

    headers: { Authorization"Bearer " + SECRET_KEY },

    payloadJSON.stringify(payload),

  };

  const res = JSON.parse(UrlFetchApp.fetch(urloptions).getContentText());

  return res.choices[0].text.trim();

}

 

/**

 * Classifies an item into a fixed set of categories

 * @param {range} categories Set of categories

 * @param {string} item Item to classify

 * @param {range} rules (Optional) Set of rules written in plain text

 * @return Completion returned by GPT-3

 * @customfunction

 */

function CATEGORIZE(categoriesinputrules=[]) {

  const prompt = "The available categories are " + categories.map((c) => `"${c}"`).join(", ") + ". " + rules.join(". ") + "The category for '" + input + "' is ";

  console.log(prompt);

  const completion = AI(prompt0"text-davinci-003");

  // Replace "s and .s at the start and end of the string

  return completion.replace(/^"/g'').replace(/["|.]{0,2}$/'');

}