Add ChatGPT 3.5 Turbo to Google Docs in 2 Minutes
All you need is an OpenAI API key
While there are plenty of blogs out there that show you how to integrate OpenAI’s GPT-3 with Google Apps Scripts, this particular integration takes it to the next level. Not only does it use the advanced GPT-3.5-turbo model, but it also features a sleek and easy-to-use modal window that lets you type in your own ChatGPT prompt.
Step 1: Obtain an OpenAI API Key
Before you can use the Google Docs ChatGPT Integration, you need to obtain an API key from OpenAI. You can do this by signing up for an account on the OpenAI website and following their instructions to generate an API key.
Step 2: Setting up the Google Docs ChatGPT Integration
- Create a copy of this Google Doc
- In the menu bar, click on “Tools” and then select “Script editor”.
- In the Script Editor, update the API key with your personal OpenAI API key.
//--------------------------------------
// API Key
//--------------------------------------
const apiKey = "YOUR API KEY";
const apiUrl = "https://api.openai.com/v1/chat/completions";
4. Save the script file by clicking the “Save Project” icon.
Step 3: Adding the ChatGPT Menu to Your Google Docs Document
- Return to your Google Docs document and refresh the page. A new menu should appear after a few seconds called “ChatGPT Menu” Select “New Prompt” from the “ChatGPT Menu”
2. Follow the prompts to grant the add-on permission to access your Google account. (You only have to do this the first time)
Step 4: Using the ChatGPT Integration to Generate Text in Your Document
- In your Google Docs document, click on the “ChatGPT Menu” in the menu bar.
- Select “New Prompt” to launch the ChatGPT prompt window.
- Type in your desired ChatGPT prompt in the input box provided, ensuring that your prompt is no longer than 4000 characters.
- Click “Submit” to submit your prompt to the OpenAI API.
- Wait a few moments for the API to generate a response.
- The API response will be added as a new paragraph to your document.
Congratulations, you have successfully set up and used the Google Docs ChatGPT Integration in your documents! With this integration, you can streamline your writing process and create more engaging content in less time.
Full Source Code with Comments
//--------------------------------------
// API Key
//--------------------------------------
const apiKey = "Your API Key";
const apiUrl = "https://api.openai.com/v1/chat/completions";
//--------------------------------------
// Create menu items in the Google Doc
//--------------------------------------
function onOpen() {
DocumentApp.getUi()
.createMenu("ChatGPT Menu")
.addItem("New Prompt", "gptgetInput")
.addToUi();
}
//--------------------------------------
// GPT Prompts Functions
//--------------------------------------
async function gptgetInput() {
const html = HtmlService.createHtmlOutput(`
<style>
.input-box {
height: 150px;
width: 450px;
}
</style>
<div>
<textarea id="input" class="input-box" oninput="updateCount()"></textarea>
<br>
<span id="count"></span>
<span id="message"></span>
<br>
<button id="submitButton" onclick="submitInput()">Submit</button>
</div>
<div id="loading" style="display:none; text-align:center">
<p>Please wait while the content is generated, may take a few minutes...</p>
<img src="https://www.google.com/images/spin-32.gif">
</div>
<script>
function submitInput() {
const userInput = document.getElementById("input").value;
const loadingDiv = document.getElementById("loading");
loadingDiv.style.display = "block";
google.script.run.withSuccessHandler(closeDialog).processgptInput(userInput);
}
function closeDialog() {
google.script.host.close();
}
function updateCount() {
const input = document.getElementById("input");
const count = input.value.length;
const countSpan = document.getElementById("count");
const message = document.getElementById("message");
const button = document.getElementById("submitButton");
if (count > 4000) {
countSpan.style.color = "red";
message.innerHTML = "Character count exceeds limit of 4000";
button.style.display = "none";
} else {
countSpan.style.color = "black";
message.innerHTML = "";
button.style.display = "block";
}
countSpan.innerHTML = count + "/4000";
}
</script>
`);
DocumentApp.getUi().showModalDialog(
html,
"Type in your prompt"
);
}
// Take the value from the modal dialog box and pass it to the OpenAI API
async function processgptInput(userInput) {
console.log("User Input:", userInput);
// Get the active document and body
const doc = DocumentApp.getActiveDocument();
const body = doc.getBody();
// We are using the chatgpt-3.5-turbo model
let requestBody = {
model: "gpt-3.5-turbo",
messages: [
{ role: "user", content: userInput },
],
};
let options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + apiKey,
},
payload: JSON.stringify(requestBody),
};
try {
let response = await UrlFetchApp.fetch(apiUrl, options);
console.log("API Response:", response.getContentText());
let data = JSON.parse(response.getContentText());
let chatResponseText = data.choices[0].message.content;
console.log("chatResponseText:", chatResponseText);
// Create custom headings for the prompt
var textStyle = {};
textStyle[DocumentApp.Attribute.FONT_SIZE] = 12;
textStyle[DocumentApp.Attribute.BOLD] = true;
textStyle[DocumentApp.Attribute.ITALIC] = false;
textStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = "#212121";
var boldPrompt = body.appendParagraph(userInput);
boldPrompt.setAttributes(textStyle);
// Append the server response paragraph and remove the bold font
var responseParagraph = body.appendParagraph(chatResponseText.trimStart());
textStyle[DocumentApp.Attribute.BOLD] = false;
responseParagraph.setAttributes(textStyle);
} catch (error) {
console.log("Error:", error);
return false;
}
return true;
}