Google Sheet integration

This page guides users on how to use Google Apps Script to integrate MaiAgent's powerful AI features into Google Sheets. With this method, you can call your MaiAgent Chatbot directly within a spreadsheet and perform batch processing of multiple inputs, greatly improving work efficiency.

Get started

Step 1: Open the Google Apps Script editor

  1. Open the Google Sheets spreadsheet where you want to integrate MaiAgent, or create a new spreadsheet.

  2. Click "Extensions" > "Apps Script" in the top menu.

Step 2: Paste and configure the script

  1. In the Apps Script editor, you will see a file named Code.gs Clear the default contents from that file.

  2. At the bottom,Attachment Completely copy the Apps Script code provided by MaiAgent and paste it into the Code.gs file.

  3. Replace the API_KEY and CHATBOT_ID at the top.

  4. After replacing them, click the save icon (💾) at the top of the editor to save your script.

Using the MaiAgent function in Google Sheets

After completing the above setup and successfully authorizing, you can use maiagent like a built-in function in Google Sheets.

1. Single Agent call

In any cell, enter a formula in the following format:

=maiagent("The message content you want to send to the Agent")

For example:

  • =maiagent("Hello, please introduce yourself")

  • =maiagent("The weather is nice today")

After pressing Enter, the script will send your message to the specified MaiAgent AI assistant and display the AI assistant's response in that cell.

2. Read message content from another cell

You can let the maiagent function read the contents of another cell as the input message.

Assume cell A1 contains the message you want to send; in another cell (for example, B1) you can enter:

=maiagent(A1)

This way, theB1 cell will display MaiAgent's response to the A1 content.

Integration demo video

Conclusion

Integrating MaiAgent into Google Sheets via Google Apps Script opens new possibilities for automation and productivity improvements. Technicians can use this method to customize spreadsheets according to specific needs, turning them into powerful AI interaction tools for content generation, data analysis, or automated responses.

Attachment

Apps Script code
// --- Define your API key and Chatbot ID here ---
const API_KEY = '<Please replace with your actual API key>';
const CHATBOT_ID = '<Please replace with your actual Chatbot ID>';
// --- --- --- --- --- --- --- --- --- --- --- ---

/**
 * Send a message to the MaiAgent API and directly return the response content.
 * The API key and Chatbot ID use the constants defined at the top of the script.
 * is_streaming is fixed to false, and conversation and attachments are not sent.
 *
 * @param {string} messageContent The message content to send.
 * @return {string} The "content" field from the API response, or an error message.
 */
function maiagent(messageContent) {
  // Check whether API_KEY and CHATBOT_ID have been set
  if (API_KEY === 'YOUR_API_KEY' || CHATBOT_ID === 'YOUR_CHATBOT_ID') {
    const warningMessage = 'Warning: API key or Chatbot ID has not been set in the script. Please edit the script and replace YOUR_API_KEY and YOUR_CHATBOT_ID.';
    Logger.log(warningMessage);
    // You may choose to throw an error or return a warning here to prevent invalid API calls
    // throw new Error(warningMessage);
    return warningMessage;
  }

  const url = `https://api.maiagent.ai/api/v1/chatbots/${CHATBOT_ID}/completions/`;

  const payload = {
    message: {
      content: messageContent
    },
    is_streaming: false
  };

  const options = {
    method: 'post',
    contentType: 'application/json',
    headers: {
      'Authorization': `Api-Key ${API_KEY}`
    },
    payload: JSON.stringify(payload),
    muteHttpExceptions: true // Set to true to handle possible error messages returned by the API
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const responseCode = response.getResponseCode();
    const responseBody = response.getContentText();

    if (responseCode === 200) {
      Logger.log('API call succeeded:');
      Logger.log(responseBody); // Still log the full raw response for debugging
      try {
        const jsonResponse = JSON.parse(responseBody);
        if (jsonResponse && typeof jsonResponse.content !== 'undefined') {
          return jsonResponse.content; // Directly return the value of the content field
        } else {
          Logger.log('API responded successfully but the "content" field is missing or the format is incorrect.');
          Logger.log(responseBody);
          return 'Error: API responded successfully but the "content" field is missing.';
        }
      } catch (parseError) {
        Logger.log(`An error occurred while parsing the API response JSON: ${parseError.toString()}`);
        Logger.log(`Raw response content: ${responseBody}`);
        return `Error: Failed to parse API response - ${parseError.toString()}`;
      }
    } else {
      Logger.log(`API call failed, response code: ${responseCode}`);
      Logger.log(`Error response content: ${responseBody}`);
      return `Error: ${responseCode} - ${responseBody}`;
    }
  } catch (e) {
    Logger.log(`An exception occurred during the API call: ${e.toString()}`);
    Logger.log(e.stack); // Log the stack trace for more detailed debugging
    return `Exception: ${e.toString()}`;
  }
}

Last updated

Was this helpful?