Resturant Oulu Finland

How to Use the GPT-4 Model with Google Docs: A Step-by-Step Guide to Setting Up and Writing the Extension Code in JavaScript

The GPT-4 model, developed by OpenAI, is an advanced language model that has revolutionized the field of natural language processing. It can generate human-like text, answer questions, and even write code. One of the many applications of GPT-4 is to enhance productivity in writing and editing documents. In this article, we will guide you through integrating the GPT-4 model with Google Docs using a custom extension written in JavaScript.

Prerequisites

Before we begin, make sure you have the following:

1. A Google account to access Google Docs.
2. Basic knowledge of JavaScript and Google Apps Script.
3. Access to the GPT-4 API. You can request access from OpenAI’s website.

Step 1: Create a new Google Docs add-on

1. Open Google Drive and create a new Google Docs document.
2. Click “Extensions” in the top menu, then “Apps Script.”

Step 2: Create a custom menu in Google Docs

1. Open the “Code.gs” file in the Apps Script editor.
2. Write the following code to create a custom menu with a “Generate Text” option:

var ui = DocumentApp.getUi();
var userProperties = PropertiesService.getUserProperties();

var API_KEY = userProperties.getProperty('api.key');

function onOpen() {
  const ui = DocumentApp.getUi();
  ui.createMenu('GPT-4')
    .addItem('Generate Text', 'generateText')
    .addItem('Set API key', 'setKey')
    .addItem('Delete API key', 'resetKey')
    .addItem('Delete all credentials', 'deleteAll')
    .addToUi();
}

function setKey(){
  var scriptValue = ui.prompt('Please provide your API key.' , ui.ButtonSet.OK);
  userProperties.setProperty('api.key', scriptValue.getResponseText());
  API_KEY = userProperties.getProperty('api.key');
}

function resetKey(){
  userProperties.deleteProperty(API_KEY);
}

function deleteAll(){
  userProperties.deleteAllProperties();
}

function generateText() 
{
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  const prompt = doc.getSelection().getRangeElements()[0].getElement().asText().getText();

  const url = "https://api.openai.com/v1/chat/completions";
  const data = {
    model: 'gpt-4',
    messages: [{role: "user", content: prompt}],
    temperature: 0,
    max_tokens: 2000
  };

  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer "+API_KEY
    },
    payload: JSON.stringify(data)
  };

  const response = UrlFetchApp.fetch(url, options);
  const jsonResponse = JSON.parse(response.getContentText());
  const generatedText = jsonResponse['choices'][0]['message']['content'];
  body.appendParagraph(generatedText.toString());
}

Step 3: Test the extension

1. Save your changes in the Apps Script editor.
2. Return to your Google Docs document and refresh the page.
3. You should see a new “GPT-4” menu in the top menu bar. Click on it and select “Generate Text.”
4. If everything is set up correctly, the GPT-4 model should generate text based on your current selection or cursor position.

Explanation of the code

Let’s break down each section of the code:

csharpCopy codevar ui = DocumentApp.getUi();
var userProperties = PropertiesService.getUserProperties();

var API_KEY = userProperties.getProperty('api.key');

The first two lines define variables ui and userProperties. ui It is used to create the add-on menu in Google Docs. userProperties Is used to store the user’s OpenAI API key. The third line gets the API key from userProperties.

csharpCopy codefunction onOpen() {
  const ui = DocumentApp.getUi();
  ui.createMenu('GPT-4')
    .addItem('Generate Text', 'generateText')
    .addItem('Set API key', 'setKey')
    .addItem('Delete API key', 'resetKey')
    .addItem('Delete all credentials', 'deleteAll')
    .addToUi();
}

The onOpen() the function creates a menu for the add-on in Google Docs. It has four items: Generate Text, Set API key, Delete API key, and Delete all credentials. When a user clicks on any of these items, it will execute the corresponding function.

csharpCopy codefunction setKey(){
  var scriptValue = ui.prompt('Please provide your API key.' , ui.ButtonSet.OK);
  userProperties.setProperty(API_KEY, scriptValue.getResponseText());
  API_KEY = userProperties.getProperty('api.key');
}

The setKey() function prompts the user to enter their OpenAI API key. The key is then stored in userProperties. The variable API_KEY is updated with the new value.

scssCopy codefunction resetKey(){
  userProperties.deleteProperty(API_KEY);
}

The resetKey() function deletes the OpenAI API key from userProperties.

scssCopy codefunction deleteAll(){
  userProperties.deleteAllProperties();
}

The deleteAll() function deletes all properties stored in userProperties.

javascriptCopy codefunction generateText() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  const prompt = doc.getSelection().getRangeElements()[0].getElement().asText().getText();

  const url = "https://api.openai.com/v1/chat/completions";
  const data = {
    model: 'gpt-4',
    messages: [{role: "user", content: prompt}],
    temperature: 0,
    max_tokens: 2000
  };

  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": "Bearer "+API_KEY
    },
    payload: JSON.stringify(data)
  };

  const response = UrlFetchApp.fetch(url, options);
  const jsonResponse = JSON.parse(response.getContentText());
  const generatedText = jsonResponse['choices'][0]['message']['content'];
  body.appendParagraph(generatedText.toString());
}

The generateText() function generates text using the OpenAI API. It first gets the selected text from the user in Google Docs. It then creates a request to the OpenAI API with the selected text as the prompt. The response from the API is parsed and the generated text is added to the end of the document.

Overall, this code provides an add-on for Google Docs, allowing users to generate text using the OpenAI API easily.

I hope that helps explain the code. If you have any questions, you can ask them in the comment box below.

Conclusion

You have now successfully integrated the GPT-4 model with Google Docs using a custom extension written in JavaScript. This powerful tool can help you improve your writing productivity and quickly generate high-quality content. Feel free to customize the code to suit your needs and explore other applications of the GPT-4 model.


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *