Google Sheet Integration

This page guides users on how to integrate MaiAgent's powerful AI capabilities into Google Sheets using Google Apps Script. Through this method, you'll be able to directly call your MaiAgent Chatbot within spreadsheets and implement batch processing for multiple inputs, significantly improving work efficiency.

Getting Started

Step 1: Open Google Apps Script Editor

  1. Open the Google Sheet 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'll see a file named Code.gs. Clear its default content.

  2. Copy and paste the complete Apps Script code provided by MaiAgent in the attachment below into the Code.gs file.

  3. Replace the API_KEY and CHATBOT_ID at the beginning.

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

Using MaiAgent Functions in Google Sheet

After completing the above setup and successful authorization, you can use the maiagent function in Google Sheet just like built-in functions.

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. Reading Message Content from Other Cells

You can have the maiagent function read content from other cells as input messages.

Suppose cell A1 contains the message you want to send, you can enter in another cell (e.g., B1):

=maiagent(A1)

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

Integration Demo Video

Conclusion

Integrating MaiAgent into Google Sheets through Google Apps Script opens up new possibilities for automation and productivity enhancement. Technical personnel can use this method to customize spreadsheets according to specific needs, making them powerful AI interaction tools, whether 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 messages to MaiAgent API and directly return response content.
 * API key and Chatbot ID use constants defined at the beginning of the script.
 * is_streaming is fixed as false, no conversation and attachments sent.
 *
 * @param {string} messageContent Message content to send.
 * @return {string} "content" field from API response, or error message.
 */
function maiagent(messageContent) {
  // Check if API_KEY and CHATBOT_ID are set
  if (API_KEY === 'YOUR_API_KEY' || CHATBOT_ID === 'YOUR_CHATBOT_ID') {
    const warningMessage = 'Warning: API key or Chatbot ID not yet set in script. Please edit script and replace YOUR_API_KEY and YOUR_CHATBOT_ID.';
    Logger.log(warningMessage);
    // Can choose to throw error or return 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 API error messages
  };

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

    if (responseCode === 200) {
      Logger.log('API call successful:');
      Logger.log(responseBody); // Still log complete original response for debugging
      try {
        const jsonResponse = JSON.parse(responseBody);
        if (jsonResponse && typeof jsonResponse.content !== 'undefined') {
          return jsonResponse.content; // Directly return content field value
        } else {
          Logger.log('API response successful but missing "content" field or format mismatch.');
          Logger.log(responseBody);
          return 'Error: API response successful but missing "content" field.';
        }
      } catch (parseError) {
        Logger.log(`Error parsing API response JSON: ${parseError.toString()}`);
        Logger.log(`Original 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(`Exception occurred during API call: ${e.toString()}`);
    Logger.log(e.stack); // Log stack trace for more detailed debugging
    return `Exception: ${e.toString()}`;
  }
}

Last updated

Was this helpful?