Unlock Claude 3 AI Brilliance with Free Apps Script into sheets

August 16, 2024 | 1 minute read


Editorial Team

blog-image

AppSScript Code

var api_key = "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";


function onEdit(e) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet();
  var show_error = 1; // Change this to 0 if you don't want to log errors


  // Set headers in cells A1 and B1 without background color
  sheet.getRange("A1").setValue("Type Claude Prompt").setFontWeight("bold").setFontSize(14);
  sheet.getRange("B1").setValue("Claude Response").setFontWeight("bold").setFontSize(14);


  // Get prompt from cell A2
  var prompt = sheet.getRange("A2").getValue();


  var end_point = 'https://api.anthropic.com/v1/complete';


  var payload = {
    "model": "claude-v1",
    "prompt": "\n\nHuman: " + prompt + "\n\nAssistant:",
    "max_tokens_to_sample": 100,
    "temperature": 1,
    "stop_sequences": ["\n\nHuman:", "\n\nAssistant:"]
  };


  var options = {
    "method": "post",
    "headers": {
      "Content-Type": "application/json",
      "x-api-key": api_key,
      "anthropic-version": "2023-06-01"
    },
    'payload': JSON.stringify(payload),
    "muteHttpExceptions": true
  }


  try {
    var response = UrlFetchApp.fetch(end_point, options);
    var responseData = JSON.parse(response.getContentText());
   
    // Log the completion
    var completionText = responseData.completion;
    Logger.log(completionText);


    // Put the completion in cell B2
    sheet.getRange("B2").setValue(completionText);


    return response;
  } catch (e) {
    if (show_error === 1) {
      Logger.log("Error: " + e);
    }
  }
}