Skip to content

Instantly share code, notes, and snippets.

@estevecastells
Created August 17, 2024 16:06
Show Gist options
  • Save estevecastells/08ffa9064b57ab34a622dee16c32b629 to your computer and use it in GitHub Desktop.
Save estevecastells/08ffa9064b57ab34a622dee16c32b629 to your computer and use it in GitHub Desktop.
Use Anthropic's Claude API via Google Spreadsheets with AppScript
// REMINDER: Replace YOUR_API_KEY with your actual Anthropic API key
const ANTHROPIC_API_KEY = 'YOUR_API_KEY';
const ANTHROPIC_API_URL = 'https://api.anthropic.com/v1/messages';
/**
* Generates a response using Claude via the Anthropic API.
*
* @param {string} prompt - The input prompt for Claude.
* @return {string} The generated response from Claude.
* @customfunction
*/
function generateClaude(prompt) {
const options = {
'method': 'post',
'headers': {
'Content-Type': 'application/json',
'x-api-key': ANTHROPIC_API_KEY,
'anthropic-version': '2023-06-01'
},
'payload': JSON.stringify({
'model': 'claude-3-5-sonnet-20240620',
'max_tokens': 4000,
'messages': [
{
'role': 'user',
'content': prompt
}
]
})
};
try {
const response = UrlFetchApp.fetch(ANTHROPIC_API_URL, options);
const json = JSON.parse(response.getContentText());
return json.content[0].text;
} catch (error) {
return 'Error: ' + error.toString();
}
}
/**
* Adds a custom menu to easily reload the script.
*/
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Claude API')
.addItem('Reload Script', 'reloadScript')
.addToUi();
}
/**
* Reloads the script to update any changes.
*/
function reloadScript() {
SpreadsheetApp.getActive().toast('Script reloaded successfully!');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment