How to connect Anthropic Claude API to Google Sheets

The Anthropic Claude API is revolutionizing how people access and manipulate human-like text generation. Whereas Google Sheets has become an essential tool for many purposes like data management, organization, and collaboration.

And, by integrating the Anthropic Claude API with Google Sheets, you have a unique opportunity to amalgamate the strengths of both platforms, paving the way for seamless data manipulation and superior automated workflows.

In this guide, I’ll walk you through a streamlined approach to integrating the Anthropic Claude API with Google Sheets. I’ve designed the code as a custom function for Google Sheets that can be invoked directly from any cell. The function accepts the ‘Text Prompt’ parameter, sends a request to the API, and returns the response.

A. Setup and configuration

1. Prepare your Google Sheets document

Create a new Google Sheets file, giving it your desired name. Inside this sheet, you only need two columns:

  • Text Prompt: This column will store the text prompts you want the AI to process.
  • Claude Output: This column will receive the generated output from the Anthropic Claude API.

And there is no fixed rule to name the columns, you can name them just about anything you like.

2. Prepare Google Sheets Script Editor

Access the Script Editor by following these steps inside Google Sheets:

  1. Click ‘Extensions’ from the top menu.
  2. Select ‘Apps Script’.

This action will open Google Scripts in a new tab. In the Script Editor, perform the following tasks:

  1. Delete any existing code.
  2. Copy and paste the provided code, called callClaude(). (The function will be explained below.)
  3. Save your script by clicking the ‘Save’ icon.

B. Understanding the callClaude() function

The callClaude() function serves as a custom function specifically designed for Google Sheets. The purpose is to minimize the complexity of the script and keep your Sheets uncluttered.

Let’s break down the code into sections to understand the function’s inner workings:

3. Add the callClaude() function

function callClaude(promptText) {

As a custom function, callClaude() will work directly inside any cell in the ‘GPT Output’ column. The function takes one parameter: promptText, which corresponds to the ‘Text Prompt’ for each row.

3.1. Specify the API key

const apiKey = 'your_api_key';

Replace ‘your_api_key’ with your actual API key from Anthropic (as shown in the screenshot below). It’s important to do that; otherwise, the script will throw errors.

Claude API Keys

3.2. Create the request body

const requestBody = {
  prompt: "\n\nHuman: " + promptText + "\n\nAssistant: ",
  model: "claude-v1",
  max_tokens_to_sample: 100,
  stop_sequences: ["\n\nHuman:"]
};

This code sets up the necessary parameters for your request. Specifically:

  • prompt: This line formats your input text by concatenating the given promptText with predefined strings.
  • model: Set the appropriate model name for the Claude API.
  • max_tokens_to_sample: Define the maximum number of tokens to be returned in the response.
  • stop_sequences: Specify an array of stop sequences. In this case, we have just one stop sequence.

If you want a longer response from the Claude API, you can increase the max_tokens_to_sample from 100 to a larger number; maybe 500 or even 1000 (if you want really long response).

3.3. Configure the request options

const requestOptions = {
  method: 'post',
  contentType: 'application/json',
  payload: JSON.stringify(requestBody),
  headers: {
    'x-api-key': apiKey,
  },
};

Here, we build an options object to configure the API request. The necessary properties are specified as follows:

  • method: The HTTP request method (in our case, ‘post’).
  • contentType: Specify the content type for sending the request (‘application/json’ in our case).
  • payload: Convert the previously created requestBody object to a JSON-formatted payload.
  • headers: Add the ‘x-api-key’ key-value pair from the Anthropic API to the headers.

3.4. Make the request and parse the response

const apiResponse = UrlFetchApp.fetch('https://api.anthropic.com/v1/complete', requestOptions);
const responseText = JSON.parse(apiResponse.getContentText());

This section of the code sends a POST request to Anthropic’s API endpoint using the UrlFetchApp.fetch() method with the required requestOptions. The apiResponse object receives the data returned by Claude, while responseText parses the received JSON data.

3.5. Extract the assistant’s response and return it

const assistantResponse = responseText.completion.trim();
return assistantResponse;
}

In the final segment, the code extracts the assistant’s response text from responseText.completion, trims excess whitespace, and returns the resulting assistantResponse to the Google Sheet.

C. Using the callClaude() function

With the provided custom function integrated into Google Sheets, invoking it within any cell becomes remarkably simple.

To use the callClaude() function inside Google Sheets, follow these steps:

  1. Click on the cell in the ‘GPT Output’ column corresponding to the ‘Text Prompt’.
  2. Begin typing '=' followed by the function name: callClaude.
  3. Inside the parentheses, enter the cell reference containing the ‘Text Prompt’. For example, if the ‘Text Prompt’ is in cell A2, your function call should look like =callClaude(A2).
  4. Press Enter.

The function will now send a request to Claude API, process the ‘Text Prompt’, and return the generated response in the ‘GPT Output’ cell.

D. Get the complete working code

Now, that you understand how everything works, I am providing you with the complete code that you can just copy-paste to your Google Sheets script editor and it should work.

function callClaude(promptText) {
  // Your API key should be specified here.
  const apiKey = 'your_api_key';

  // Set necessary parameters for your request.
  const requestBody = {
    prompt: "\n\nHuman: " + promptText + "\n\nAssistant: ",
    model: "claude-v1",
    max_tokens_to_sample: 100,
    stop_sequences: ["\n\nHuman:"]
  };

  // Configure the options for your request.
  const requestOptions = {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify(requestBody),
    headers: {
      'x-api-key': apiKey,
    },
  };

  // Make the request and parse the response.
  const apiResponse = UrlFetchApp.fetch('https://api.anthropic.com/v1/complete', requestOptions);
  const responseText = JSON.parse(apiResponse.getContentText());

  // Extract the Assistant's response and return it.
  const assistantResponse = responseText.completion.trim();
  return assistantResponse;
}

If you’re unable to copy the above code somehow, you can click here to copy the same from this Gist.

I have also created a Claude pricing calculator that you can use to estimate how much it is going to cost you to generate a certain number of words by using the Claude API.

Hope you get this working on the first attempt, but if you get stuck somewhere, kindly feel free to let me know in the comments below.

Comments

  • No comments yet.
  • Add a comment