Scroll to Top
💻
Free Code
Users get ready-to-use code at no cost.
📋
Easy Copy
Copy and use the code instantly.
Quick Learning
Understand concepts fast and clearly.
📝
Step-by-Step
Follow simple instructions to implement.
📅 August 16, 2024 💻 Tutorial ⭐ Beginner Friendly

Mistral AI Magic In Google Sheets with Free Apps Script

Author Avatar

Ashish Dwivedi

Editorial Team • Tech Writer

About This Tutorial

Bring Mistral AI’s magic into Google Sheets using a free Apps Script. Connect to Mistral’s API, send prompts or data from your sheet, and receive smart completions, insights, or content directly in cells. Ideal for automating tasks like writing, summarizing, or analyzing—all within your spreadsheet workflow.
  1. Step 1: Click on the Copy button to copy the code snippet.
  2. Step 2: Paste the copied code into your project’s script editor.

Apps Scripts Blog

Read Blog

📂 javascript
⚡ script1.js
⚡ script1.js
var apiKey = 'XRqs0ATTneIjz477JWtMBSgPtylMZdto';
var apiUrl = 'https://api.mistral.ai/v1/chat/completions';

// ------------------------------
// Add menu and create header
// ------------------------------
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Mistral AI')
    .addItem('Generate Answers', 'generateAnswers')
    .addToUi();
  createHeader();
}

// ------------------------------
// Create header row
// ------------------------------
function createHeader() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var headers = ["Type Mistral prompt", "Mistral Response"];
  var headerRange = sheet.getRange('A1:B1');
  headerRange.setValues([headers]);
  headerRange.setFontWeight("bold").setFontSize(14);
}

// ------------------------------
// Generate answers for active row
// ------------------------------
function generateAnswers() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var activeCell = sheet.getActiveCell();
  var row = activeCell.getRow();
  var column = activeCell.getColumn();

  if (column !== 1) {
    Logger.log('Active cell should be in column A (containing prompts)');
    return;
  }

  var promptText = activeCell.getValue();
  if (!promptText) {
    Logger.log('The selected cell is empty.');
    return;
  }

  var existingResponse = activeCell.offset(0, 1).getValue();
  if (existingResponse) {
    Logger.log('Response already exists for this prompt.');
    return;
  }

  var prompt = `Generate a response for the following question: "${promptText}"`;
  var response = getMistralAIResponse(prompt);

  if (response) {
    activeCell.offset(0, 1).setValue(response.trim());
    Logger.log('Response generated successfully.');
  } else {
    Logger.log('Failed to generate response for prompt: ' + promptText);
  }
}

// ------------------------------
// Call Mistral AI API
// ------------------------------
function getMistralAIResponse(prompt) {
  var payload = {
    model: "mistral-small-latest",
    messages: [{ role: "user", content: prompt }],
    temperature: 0.7,
    top_p: 1,
    max_tokens: 512,
    stream: false,
    safe_prompt: false,
    random_seed: 1337
  };

  var options = {
    method: 'post',
    contentType: 'application/json',
    headers: { 'Authorization': 'Bearer ' + apiKey },
    payload: JSON.stringify(payload),
    muteHttpExceptions: true
  };

  try {
    var response = UrlFetchApp.fetch(apiUrl, options);
    if (response.getResponseCode() === 200) {
      var data = JSON.parse(response.getContentText());
      return data.choices[0].message.content;
    } else {
      Logger.log('API Error: ' + response.getContentText());
      return null;
    }
  } catch (e) {
    Logger.log('Fetch Error: ' + e);
    return null;
  }
}