← All Apps Scripts templates
/
Use the API of ChatGPT

Use the API of ChatGPT

  1. Create a new Google Sheets file
  2. Go to Extensions → Apps Script
  3. Remove all the code and copy-paste the following instead
  4. Create an account on OpenAI, get its API key and paste it instead of OPENAI_API_KEY in the script below
  5. Save your project and go back to your sheet
  6. Use =runOpenAI(), like classic Google Sheets Formula

The new function in Google Sheets:


runOpenAI()

The code to paste in Apps Script inside Google Sheets:


function runOpenAI(messages) {


const API_KEY = "OPENAI_API_KEY";


model = "gpt-3.5-turbo"
 messages=[
    {"role": "user", "content": messages}
  ]




  // Set up the request body with the given parameters
  const requestBody = {
    "model": model,
    "messages": messages,
  };
  console.log(requestBody)


  // Set up the request options with the required headers
  const requestOptions = {
    "method": "POST",
    "headers": {
      "Content-Type": "application/json",
      "Authorization": "Bearer "+API_KEY
    },
    "payload": JSON.stringify(requestBody)
  };


  // Send the request to the ChatGPT API endpoint for completions
  const response = UrlFetchApp.fetch("https://api.openai.com/v1/chat/completions", requestOptions);


  console.log(response.getContentText())
 
  // Get the response body as a JSON object
  const responseBody = JSON.parse(response.getContentText());




  let answer= responseBody.choices[0].message.content




  // Return the generated text from the response
  return answer
}


Reach us if the process is unclear or if the script is outdated
Apps Scripts template

Use the API of ChatGPT

Last updated
3/4/2023
Built by
Avatar Placeholder
internal

Similar Apps Script for

ChatGPT

in Google Sheets

No similar items yet.