Skip to content

Instantly share code, notes, and snippets.

@estevecastells
Last active August 12, 2024 16:09
Show Gist options
  • Save estevecastells/d7c176c6318cfcdd0755eab5ae7733a3 to your computer and use it in GitHub Desktop.
Save estevecastells/d7c176c6318cfcdd0755eab5ae7733a3 to your computer and use it in GitHub Desktop.
Use Google Gemini API in Spreadsheets
/**
* Generate content using the Gemini API with a hardcoded API key.
* @param {string} prompt - The text prompt to generate content.
* @return {string} The generated text from the API.
*/
function generateGeminiContent(prompt) {
const API_KEY = 'API_KEY'; // Replace with your actual API key
const API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-001:generateContent?key=' + API_KEY;
const requestBody = {
contents: [{
parts: [
{ text: prompt }
]
}],
generationConfig: {
temperature: 0.5,
maxOutputTokens: 3000
},
};
const options = {
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(requestBody)
};
try {
const response = UrlFetchApp.fetch(API_URL, options);
const jsonResponse = JSON.parse(response.getContentText());
const generatedText = jsonResponse.candidates[0].content.parts[0].text;
return generatedText;
} catch (error) {
Logger.log('Error fetching data from Gemini API: ' + error);
return 'An error occurred while generating content.';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment