How to Generate a Full Google Doc From an AI Prompt With Apps Script
Run an Apps Script that asks an AI model for content and creates a formatted Google Doc from the result automatically.
Sometimes you want a finished document, not a side panel. This guide writes an Apps Script that sends a topic to an AI model, gets back a structured outline and body, and creates a brand new Google Doc with a title and paragraphs already in place.
- A Google account with Google Drive and Docs
- An OpenAI API key
- The standalone Apps Script editor at script.google.com
- About 10 minutes
Step 1: Create a standalone script project
Go to script.google.com and click New project. A standalone project is not tied to a single file, which is what you want when the script creates documents on the fly.
Step 2: Write the generation function
Paste the code below. It calls the Chat Completions API, then uses the DocumentApp service to build a document. The first line of the AI output becomes the title and the rest becomes the body.
const OPENAI_KEY = "sk-PASTE_YOUR_KEY";
function generateDoc() {
const topic = "A one-page guide to writing better commit messages";
const content = askAI(topic);
const lines = content.split("\n").filter((l) => l.trim());
const doc = DocumentApp.create(lines[0]);
const body = doc.getBody();
lines.slice(1).forEach((line) => body.appendParagraph(line));
Logger.log("Created: " + doc.getUrl());
}
function askAI(topic) {
const res = UrlFetchApp.fetch("https://api.openai.com/v1/chat/completions", {
method: "post",
contentType: "application/json",
headers: { Authorization: "Bearer " + OPENAI_KEY },
payload: JSON.stringify({
model: "gpt-5",
messages: [{ role: "user", content: "Write: " + topic }],
}),
});
return JSON.parse(res.getContentText()).choices[0].message.content;
}Step 3: Run it and authorize
Select generateDoc and click Run. Apps Script will ask for permission to manage your documents and make external requests. Approve both. The execution log prints the URL of the new doc.
Step 4: Open the generated document
Click the URL in the log. A new doc appears in your Drive with the AI title at the top and one paragraph per line of generated content, ready to refine.
Result: a single run turns a prompt into a real, editable Google Doc. Wire it to a Google Form and your team can request drafts without touching code.
Watch related tutorials
12:38
14:09
17:53
15:00
12:00
25:00