AppsScriptPulse

Automating Data Extraction with the Gemini API Controlled Generation and AppSheet’s New Gmail Integration

Tired of manually processing invoices? I recently built a demo that automates this tedious task using the power of Gemini, AppSheet’s new Gmail integration, and a custom Apps Script library. Let me show you how it works!

Here’s the setup:

  • Gmail Integration: AppSheet’s new Gmail integration allows you to trigger automations based on incoming emails. I’ve set it up to monitor a specific Gmail label called “Invoices”.
  • Apps Script Library: Using my “GeminiApp” (available on Github) which simplifies the interaction with Google’s Gemini AI models directly from Apps Script. This library handles the heavy lifting of making API calls and managing responses.
  • Controlled Generation: Gemini’s “Controlled Generation” feature lets me define a JSON schema that structures the AI’s output. This is key for extracting invoice data in a consistent, machine-readable format.

The Workflow:

  1. Invoice Received: When an invoice email arrives and is labelled “Invoices”, AppSheet’s Gmail integration kicks in.
  2. Automation Triggered: AppSheet triggers an automation that calls a custom Apps Script function called jsonControlledGeneration.
  3. Data Extraction: The jsonControlledGeneration function uses the GeminiApp library to send the email body to Gemini with a predefined JSON schema for invoice data.
  4. Structured Output: Gemini processes the email content and extracts the relevant invoice details (e.g., invoice number, supplier name, date, amount) in a JSON format that adheres to the schema.
  5. Downstream Processing: The structured JSON output can then be easily returned to the AppSheet automation for further actions, such as automatically populating your data table, updating a database, or triggering a payment process.

If you would like to try this yourself, instructions are provided below.

Want to try it yourself?

To set this demo up you will either need a Google AI Studio API key or a Google Cloud project with Vertex AI enabled. Information on both these setups is included in the GeminiApp Setup Instructions. Once you have these you can follow these steps:

  1. Open the GeminiApp Controlled Generation Google Apps Script project and click ‘Make a copy’ from the Overview page
  2. Open the Invoice Tracker template and click ‘Copy and Customize’, then click OK on the Error Creating App: Apps Script function is invalid error
  3. Navigate to appsheet.com and from your ‘recent’ apps  open the ‘Invoice Tracker’ app
  4. Open Automations and for the ‘New Invoices’ event under the Gmail Event Source, click Authorize, then
  5. In the ‘Add a new data source’ enter a name e.g. Invoices Trigger, click the Gmail button and follow the authentication steps
  6. Once complete in the AppSheet Automation settings select your Gmail account and a Label to watch
  7. In the Process section click on the GeminiApp task and click on the blue file icon, then select your copied version of the Apps Script project and click Authorize
  8. Once Authorize, from the Function Name select jsonControlledGeneration

To test this app, you can copy and send this example invoice.

Step 7: Click on the blue file icon, then select your copied version of the Apps Script project

The Power of Controlled Generation

Controlled Generation is a powerful way for extracting information from unstructured data like emails. By defining a JSON schema, I can specify exactly what information I want Gemini to extract and how it should be structured. This ensures that the output is consistent and reliable, eliminating the need for manual cleanup or post-processing.

Here’s an example of a simple JSON schema for invoice data:

 const schema = {
    "type": "object",
    "properties": {
      "Invoice Reference": {
        "type": "string",
        "description": "Unique identifier for the invoice"
      },
      "Supplier Name": {
        "type": "string",
        "description": "Name of the supplier"
      },
      "Invoice Date": {
        "type": "string",
        "description": "Date the invoice was issued",
        "format": "date"
      },
      "Due Date": {
        "type": "string",
        "description": "Date the invoice is due",
        "format": "date"
      },
      "Invoice Amount": {
        "type": "number",
        "description": "Total amount due on the invoice"
      },
      "Notes": {
        "type": "string",
        "description": "Additional notes related to the invoice",
        "nullable": true
      }
    },
    "required": ["Invoice Reference"]
  }

Creating JSON Schemas with Gemini

Creating JSON schemas can seem a bit daunting at first, but Gemini can actually help you with that too! If you have sample data in a Google Sheet, you can use the Gemini Side Panel to generate a schema automatically. Just highlight the data and ask Gemini to create a JSON schema for you. You can even provide a description for each property to make your schema more understandable. Below is a prompt you can use in the Gemini Sheet Side Panel to generate a schema for your own data:

I'm using Controlled Generation with the Gemini API as described in the document https://drive.google.com/file/d/1ETKHlEUDQzJ-f2fmAzsuDjcwdt1D7R2y/view?usp=drive_link

I need help creating a JSON schema to capture data from a screen.

Could you generate a JSON schema suitable for using Controlled Generation with the Gemini API? I want to extract specific information from what's displayed on my screen.

Here are my requirements:

* **Comprehensive Schema:** The schema should be designed to capture a variety of relevant data points from the screen.  
* **Detailed Descriptions:** Please include a clear and concise \`description\` for each \`property\` in the schema. This will help me understand the purpose of each field.  
* **Format Specification:** If any columns contain date or datetime data, please use the \`format\` field to specify the appropriate format (e.g., "date", "date-time"). This is crucial for accurate data parsing.  
* **Output Example:** Please provide the schema in the following format:

```
const schema = {
  description: "Description of the data",
  type: "array", // or "object", depending on the structure
  items: { // If type is array
    type: "object",
    properties: {
      propertyName: {
        type: "string", // or other appropriate type
        description: "Description of the property",
        format: "date", // or "date-time", if applicable
        nullable: false, // or true
      },
      // ... more properties
    },
    required: ["propertyName"], // If any properties are required
  },
  properties: { // If type is object
      propertyName: {
        type: "string", // or other appropriate type
        description: "Description of the property",
        format: "date", // or "date-time", if applicable
        nullable: false, // or true
      },
      // ... more properties
    },
    required: ["propertyName"], // If any properties are required
};
```

Limitations and future developments

While the beta Gmail integration in AppSheet marks a significant new feature, it’s important to note a current limitation is support for processing email attachments. Currently, the integration focuses on metadata such as sender name, subject, and message body, but the AppSheet team have acknowledged attachment support will be added in the near future.

Looking ahead, at Google Cloud Next 2024 the AppSheet team announced an upcoming “Gemini Extract” feature, currently in private preview. This feature intends to include a native Gemini ‘controlled generation’ feature which would let app creators select the data fields they would like populated from sources including images and text. This should be a more intuitive approach to data extraction, directly integrating Gemini capabilities into AppSheet. The Next video includes a Google URL to sign up to the Gemini Extract feature https://goo.gle/appsheet-previews?r=qr

Summary

The Invoice Tracker example hopefully highlights the opportunity for streamlined solutions with data extraction with AppSheet’s Gmail integration, Gemini, and Apps Script.The GeminiApp library also  simplifies the integration of Google’s Gemini AI models into Google Workspace, providing developers with tools to create sophisticated AI-powered applications.

Using the structured JSON output with Controlled Generation can help AppSheet creators by making it easier to ensure you get the data back in a suitable format including the type of data you need, such as dates. With the GeminiApp library, rapid prototyping is achievable, in the ‘Invoice Tracker’ example I was able to get a functional prototype up and running in under 30 minutes.

AppSheet’s Gmail integration, generally available to all AppSheet and Google Workspace Core users, can trigger automations directly from incoming emails without requiring app deployment. Combined with Apps Script functions this opens the door to some powerful opportunities for AppSheet creators. Integrating Gemini-powered AI extraction with AppSheet and Apps Script provides an innovative solution for automating data extraction from emails. By taking advantage of these capabilities, citizen developers can create efficient and user-friendly solutions.

AppSheet’s New Gmail Integration: Bridging the Gap Between your Inbox and Applications

We’re pleased to announce the public preview of Gmail integration with AppSheet – something we know has been a longstanding community request. With this preview launch, your Gmail inbox can seamlessly connect to the full breadth of downstream processes AppSheet automation already offers.

AppSheet has introduced a Gmail integration in public preview, offering a workaround for situations including third-party applications that lack direct integration with Google Workspace via add-ons or APIs. With this new feature users can now connect their Gmail inboxes to AppSheet, enabling incoming emails to trigger various automations.

How it Works

Users can link their AppSheet apps to authorized Gmail accounts and select specific labels in their Gmail inboxes for monitoring. When an email arrives with a designated label, AppSheet receives information about the email, including the sender, subject, and body. This information can then be used to automate various tasks and processes within the AppSheet platform.

Things to Note

Currently, the beta release does not include support for attachments, but AppSheet is working on adding this feature for the full release later this year. Also, Gmail cannot be used as a full data source in AppSheet. To save Gmail messages in an app table, users need to create a process to add the email data.

Availability and Feedback

The Gmail integration is rolling out to all AppSheet users soon as part of the preview and the AppSheet team is encouraging users to provide feedback on this new integration. To read more and provide feedback follow the source link

Source: Gmail Integration in AppSheet: Now in Public Preview! (Beta)

Bulk Image Generation with Imagen 3, Sheets, and Apps Script

Discover how to combine Imagen 3 and Google Sheets for rapid image creation. Automate your workflow and generate visuals in bulk.

Have you ever wished you could create a bunch of images without the hassle of typing in each prompt one by one? Well, Stéphane Giron has shared a clever solution using Google’s Imagen 3, Google Sheets, and Apps Script to streamline this process. While Gemini for Workspace is rolling out to more users and includes Imagen 3 for image creation in apps like Slides and the Gemini side panel, it doesn’t offer an easy way to create images in bulk. That’s where this method comes in. Instead of making images one at a time, this approach allows you to generate multiple images at once, saving you time and effort.

To get started with this method, you’ll need a Google Cloud Project and creating a service account (see the Build an AI slides reviewer with Gemini tutorial for instructions on setting this up). Once that’s set up, you create a Google Sheet with a column for your text prompts, and another for the links to the generated images. The images are automatically saved into a specific folder in your Google Drive.

The real magic happens with Apps Script. It uses Vertex AI to connect with the Imagen 3 model. The script reads each prompt from your sheet, sends it to Imagen 3 to create an image, and then stores the image in Google Drive. It also helpfully adds the image’s link back into the Google Sheet.

Check out the source post for the required code and instructions.

Source: Imagen 3 + Google Sheets + Google Apps Script: The secret to effortless bulk image generation

Keep Your Google Sheet Data Tidy: Auto-Formatting Form Responses with a Little Apps Script

Learn how to automatically maintain consistent formatting, styles, and date formats when new Google Form responses are added to your Google Sheets.

Tired of Google Form responses messing up your carefully formatted Google Sheets? When new submissions come in, they often ignore the styles you’ve set, resulting in inconsistent looking data. Amit Agarwal, has created a guide that uses Google Apps Script to automatically maintain consistent formatting when new responses are added.

Google Forms does not apply any formatting when it adds new response data to a Google Sheet; this means that custom fonts, alignments, and date formats can be lost. Amit’s solution uses Google Apps Script to copy the formatting from the previous row to the new row, ensuring all data has a consistent look. The Apps Script runs automatically when a new form is submitted and identifies the new row and copies the formatting from the row above.

The guide provides a complete script with instructions for adding it to your Google Sheet and setting up a trigger. The script uses the copyFormatToRange method, which is designed specifically for copying only formatting between ranges. If you want to make sure your Google Sheet stays neatly formatted, check out Amit’s full guide to learn how to set up this handy automation for yourself.

Source: How to Automatically Format Google Form Responses in Google Sheets

Gassypedia January 2025 Update: Apps Script Ecosystem Growth

Quarterly update on the shared bigquery dataset all about the Apps Script developer ecosystem on Github, with reports available on looker.

Bruce Mcpherson’s latest Gassypedia update offers a look at the Apps Script ecosystem, using publicly shared code on GitHub. The report analyses data from over 3100 developers and nearly 100 million files across 200,000 repositories. You can read the full report from the source link at the bottom but here are some key points:

  • Growth: The Apps Script community is still expanding, but at a slightly slower pace than before.
    • The number of developers increased by 4%.
    • Shared repositories grew by 3%.
    • Manifests increased by 2%.
  • Add-ons: There’s a 13% increase in Add-ons shared on GitHub.
    • Chat Add-ons are now most popular, surpassing Sheets.
    • Chat Add-ons increased by 18%, and Sheets Add-ons by 10%.
    • Calendar Add-ons saw a slight decrease.
  • Code Sharing: While the number of Apps Script developers and related content has increased, the total number of all types of repositories and files associated with them has decreased by almost 5%. However, the percentage of those repositories that are Apps Script related has increased.
  • Clasp: 25.2% of manifests showed Clasp usage, a 1% increase.
  • OAuth: 851 repos and 1008 manifests use the auth/script_external_request scope, a 6% increase.
  • Advanced Services: Drive is the most popular advanced service, used in 499 manifests.
  • Web Apps: 53% of web apps are public, and 81% are executed as the user deploying. 6% of web apps are created in Japan.
  • Libraries: oauth2 is the most popular library, with 236 users.

Key Takeaways

  • Apps Script is still a growing platform, with many developers sharing their work.
  • The rise of Chat Add-ons indicates the maturing of the platform for Google Workspace users.
  • More developers are sharing Apps Script projects on Github.

Explore the Data

Bruce’s full report is on Looker, with the data available on BigQuery. You can use this data for your own research and share any findings with Bruce.

Source: Gassypedia – January 2025 update – Desktop liberation

GeminiApp Gets a Major Upgrade: Seamless Transition, Enhanced Functionality, and More!

The GeminiApp library, designed to bring Google’s Gemini AI models into your Google Apps Script projects, has just received a major update. This new release, version 2025.01, introduces significant enhancements that expand the library’s capabilities for building sophisticated AI-powered applications within Google Workspace.

Here’s a quick look at what’s new:

  • Seamless Transition: The updated library allows for a smooth transition from Google AI Studio to Vertex AI.
  • JSON-Controlled Generation: Generate content in JSON format, either by providing a schema or allowing the model to infer it from your prompt.
  • Code Execution: Generate and execute code directly within prompts using gemini-2.0 models.
  • System Instructions: Guide the model’s behavior by providing system instructions during initialization.
  • Caching: Improve efficiency and reduce token usage by caching file uploads.
  • Easier Copy/Paste: The library now supports initialization using both new GeminiApp() and new GoogleGenerativeAI(), making it easier to copy code from Google AI Studio.

The update includes over 1.5K new lines of code, primarily in src/GeminiApp.jssrc/GoogleAICacheManager.js, and tests/tests.js. Existing projects can be updated by replacing the existing GeminiApp.gs code with the updated library. This update provides a broader set of tools to create more personalized and efficient workflows.

For those new to the GeminiApp library, multiple setup options are available. Check out the updated examples and test cases in the README.md file to get started.

This update marks a step forward for developers integrating Gemini into Google Workspace. With new features and the ability to move between Google AI Studio and Vertex AI, the possibilities are vast.

Feel free to share your use cases, code improvements, and feature requests!

Source: GeminiApp Gets a Major Upgrade: Seamless Transition Between Google AI Studio and Vertex AI, Enhanced Functionality, Multimodal Input, and More!

AI Tutor: Ben Explores Google AI Studio for a Glimpse into the Future of Google Sheets

Let’s see whether Google’s AI Studio can teach me how to build a pivot table in Google Sheets. It’s wild how fast this technology is progressing and this gives us a glimpse into the near future when we’ll all have personal AI assistants helping us work more efficiently.

In a recent YouTube video, Ben Collins, a prominent figure in the Google Sheets community, explored the capabilities of Google’s AI Studio by using it to guide him through the process of creating a pivot table. This experiment provides a compelling glimpse into the future of how we might interact with software, suggesting that AI could soon enable conversational, real-time interactions that go beyond the traditional user-driven model.

Ben began by logging into Google AI Studio and initiating a real-time screen share of his Google Sheet, which contained real estate data. He then engaged the AI assistant, powered by Gemini, to help him create a pivot table to analyze this data. The initial request was straightforward: to see the sum of sales prices broken down by property type. The AI assistant demonstrated an understanding of this request and provided step-by-step instructions. The AI correctly instructed Ben to start by selecting any cell within his data and then navigating to the Insert menu to select “Pivot table”.

The AI assistant did stumble initially, incorrectly stating that the pivot table option could be found under the Data menu. This highlights an important point: while impressive, AI assistants are not yet infallible. As Ben pointed out in the video, that could be a stumbling block if someone didn’t know to look under the Insert menu. Ben’s familiarity with Google Sheets allowed him to identify and correct the AI’s misstep, and continue with the tutorial. This shows that even with sophisticated AI tools, a foundational understanding of the software is still essential.

Once the pivot table was created, the AI guided Ben through adding “property type” to the rows and “sales price” to the values section. It also prompted Ben to ensure the summarization of sales price was set to “sum” instead of “count” or another option. This highlights the AI’s ability to understand the nuances of data analysis in Google Sheets and guide users to the correct settings. This is a key insight, because the AI isn’t just providing instructions but it is also understanding the data context.

Ben’s experiment provides a vision of a future where AI agents become sophisticated collaborators within Google Sheets. These agents would not only provide step-by-step instructions, but could also actively carry out tasks, such as reformatting tables or creating charts and graphs based on conversational prompts. Imagine, for example, saying “reformat this table to be more visually appealing” or “create a chart showing sales trends over time” and having the AI make those changes automatically. This would move beyond current user workflows which depend on menu clicks, or even hand-written Apps Scripts, and would allow users to focus on high-level goals and analysis, rather than the mechanics of the software.

It is clear from the video that Google AI is an important area to watch for the future of Google Workspace. However, even with AI integration, it is still important to understand the tools you are using to ensure the advice you are receiving is correct. This is an important point, as it shows that AI should be seen as a helpful assistant, not as a replacement for user understanding. If you are interested in reading more about this I recently published an article on Empowering Enterprise Productivity While Preserving Critical Thinking.

Source: Can AI teach me how to build a pivot table?

How to Use Google Apps Script to Auto-Label and Archive Gmail

Are you overwhelmed by a cluttered inbox? If you’re a power Gmail user, you may already know about the plus addressing feature that allows you to create custom email variations by appending a + and a label to your email address. For example, username+shopping@gmail.

Are you tired of sifting through a mountain of emails every day? Gmail’s “plus addressing” feature can be a lifesaver, and with a little Google Apps Script magic, you can transform it into a powerful automation solution.

If you are not familiar ‘plus addressing’ is a feature of Gmail which allows you to create custom variations of your email address by adding a “+” symbol and a label after your username, but before the “@” symbol. For instance, if your email is [email protected], you can use [email protected] for newsletters. While these emails still land in your main inbox, this subtle tweak opens the door to some clever automations using Google Apps Script.

This blog post, written by Senior Product Designer Niyas V, provides a step-by-step guide on using Google Apps Script to automatically label and archive emails based on the “plus addressing” variations. The script scans incoming emails, extracts the label after the “+”, applies the corresponding Gmail label, and then neatly archives the thread. The post includes the complete script, instructions on setting up a time-driven trigger for automation, and clear steps to save, authorise, and test your creation.

This tutorial is a fantastic resource for developers looking to learn practical Gmail automation using Google Apps Script and a great starting point if you are thinking about building other solutions using your inbox.

Source: How to Use Google Apps Script to Auto-Label and Archive Gmail

Google Workspace Developer News: Google Chat features, Workspace Admin Policy API, and More!

Chanel Greco is back with more exciting news for Google Workspace developers in the latest Google Workspace Developer News video. As always Chanel is able to pack in lots of detail in under 4 minutes, and if you prefer text over video here are the highlights!

Spreadsheet Class Gets a Boost:

The Apps Script Spreadsheet class has received a handy new method: getSheetById(). This allows developers to directly fetch a sheet within a spreadsheet using its unique ID, simplifying sheet management within scripts.

Transparency for Calendar Events:

Developers can now control the transparency of Google Calendar events programmatically. The new functionality allows setting an event as TRANSPARENT (showing the calendar as Available during that time) or OPAQUE (showing the calendar as Busy). This granular control enhances calendar integration and automation possibilities.

Deprecation Notice:

While new features are welcomed, it’s also important to note deprecations. The getUrl() method for CellImageCellImageBuilder, and OverGridImage classes within the Apps Script Spreadsheet service is now deprecated. This change reflects the fact that an image’s source URL isn’t consistently accessible regardless of the image insertion method.

Workspace Policy API Goes GA:

A significant announcement for Workspace administrators is the general availability of the Workspace Policy API. This API enables programmatic access to over 60 Google Workspace Admin settings, making auditing and monitoring the Workspace environment more efficient.

Open-Source Drive Picker on NPM:

The Google Drive Picker web component has been published to NPM, making it easier for developers to integrate the Google Picker API into their web applications. This open-source component, designed as a reusable custom HTML element, simplifies the process of adding Google Drive file selection capabilities to web projects.

Chat App Enhancements:

For developers working with Google Chat, there are several exciting updates, primarily available through the Developer Preview Program. These include:

  • Quick Commands: Users can interact with Chat apps more quickly and efficiently using quick commands, which invoke the app directly without requiring slash commands or additional input.
  • AppCommandPayload for Slash Commands: Chat apps built as Google Workspace Add-ons now utilize AppCommandPayload instead of MessagePayload for handling slash and quick commands.
  • Carousel Support: Chat apps can incorporate carousels to display scrollable collections of items, further enhancing the user experience.
  • Announcement Space Management: Developers can programmatically create announcement spaces and manage space permission settings using the Chat API with App Authentication.
  • Expanded UI Widget Library: More Google Workspace Add-on UI widgets are now available for Chat apps, providing developers with a richer set of tools for creating interactive experiences.

Stay Up-to-Date:

To learn more and explore these features in detail, visit the Google Workspace Developers YouTube channel and check the video description for links to relevant documentation.

Source: Update to Apps Script’s Spreadsheet class, new Workspace Policy API, and more!

Unlocking Google Docs Content: A comprehensive guide to text extraction with Google Apps Script

4 Approaches to extracting the body text of a Google Doc with Google Apps Script. Full Code and tutorial

Scott Donald must be one of the most comprehensive Google Apps Script writers I know. All of his tutorials are packed with information and useful tips. This recent post is no exception, as Scott dives in and shares this detailed guide on retrieving a Google Docs body text using Google Apps Script.

The tutorial explores four approaches to extracting text from a Google Doc:

  1. DocumentApp: This approach is straightforward for basic text extraction but may not capture all elements, especially “Smart Chips.”
  2. DocumentApp with Element Iteration: This method allows for extracting text and URLs from standard text and supports some “Smart Chips” like Date, Rich Link, and Person.
  3. OCR Approach: This involves converting the document to a PDF, applying OCR, and reading the extracted text. It captures most displayed text but may not recognise emojis or some formula symbols.
  4. Docs API Advanced Service: This approach utilises the Docs REST API to access text, links, and specific “Smart Chip” data. It offers more control over data extraction but may require navigating complex JSON responses.

Scott’s tutorial provides a comprehensive and practical guide to retrieving Google Docs body text using Google Apps Script. Be sure to check out the full tutorial for detailed explanations, code examples, and helpful tips. And don’t forget to share your preferred approach and any challenges you’ve encountered on Scott’s post.

Source: Get a Google Docs Body Text with Apps Script – Yagisanatode