Step 1: Obtain an OpenAI API Key: Navigate to the OpenAI platform website (platform.openai.com), create an account or log in, then access your API keys section and generate a new secret key. Copy this key immediately as it will only be shown once.
Step 2: Securely Store the API Key in Script Properties: Open your Google Apps Script project. Go to Project Settings (the gear icon on the left sidebar). Scroll down to "Script Properties" and click "Add Script Property". Enter "OPENAI_API_KEY" as the property name and paste your OpenAI API key as the value. Click "Save". (For development, PropertiesService.getUserProperties() can be used, but getScriptProperties() is generally preferred for project-level keys.)
Step 3: Define Your OpenAI API Request Payload: Identify the OpenAI API endpoint you wish to use (e.g., /v1/chat/completions for text, /v1/images/generations for images). Construct a JavaScript object representing the request body, including parameters like model, messages (for chat), prompt (for DALL-E), max_tokens, temperature, etc. This object will be converted to JSON.
Step 4: Implement `UrlFetchApp` for the API Call: In your Apps Script code, use UrlFetchApp.fetch() to send an HTTP POST request. Set the url to the appropriate OpenAI endpoint. Set the method to 'post'. Set contentType to 'application/json'. Include headers containing your Authorization header with the API key (e.g., 'Authorization': 'Bearer ' + PropertiesService.getScriptProperties().getProperty('OPENAI_API_KEY')). Set payload to JSON.stringify() your request body object. Set muteHttpExceptions to true for robust error handling.
Step 5: Parse the API Response: After the fetch call, check the response code. If not 200, log the error. Use JSON.parse(response.getContentText()) to convert the JSON response string into a JavaScript object. Access the relevant data from the parsed object (e.g., responseObject.choices[0].message.content for text, responseObject.data[0].url for image URLs).
Step 6: Integrate AI Output into Google Workspace: Take the parsed AI output and use other Apps Script services (e.g., SpreadsheetApp, DocumentApp, GmailApp) to insert, update, or send the generated content.