Last active
February 15, 2023 22:31
-
-
Save jsfez/e91c1cae51c5a7d01cc96e0c36439ec1 to your computer and use it in GitHub Desktop.
Connect Google Sheet to chatGPT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Load OpenAI API key from script properties | |
const openaiApiKey = "YOUR_API_KEY"; | |
// Load Google Sheet data | |
const sheet = | |
SpreadsheetApp.getActiveSpreadsheet().getActiveSheet() || | |
SpreadsheetApp.getActiveSpreadsheet().getSheets()[0]; | |
const data = sheet.getDataRange().getValues(); | |
// Fetch response from OpenAI's completion API | |
function generateResponse(prompt) { | |
if (!openaiApiKey) throw new Error("OpenAI API key not found."); | |
const openaiUrl = "https://api.openai.com/v1/completions"; | |
const response = UrlFetchApp.fetch(openaiUrl, { | |
method: "post", | |
headers: { | |
"Content-Type": "application/json", | |
Authorization: `Bearer ${openaiApiKey}`, | |
}, | |
payload: JSON.stringify({ | |
prompt, | |
model: "text-davinci-003", | |
max_tokens: 1024, | |
n: 1, | |
stop: null, | |
temperature: 0.5, | |
presence_penalty: 0, | |
frequency_penalty: 0, | |
best_of: 1, | |
}), | |
}); | |
const responseData = JSON.parse(response.getContentText()); | |
return responseData.choices[0].text.trim(); | |
} | |
function gpt(prompt) { | |
const response = generateResponse( | |
`${data.map((row) => row.join("\t")).join("\n")}\n\n${prompt}` | |
); | |
Logger.log(response); | |
return response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Connect your Google Sheet to ChatGPT
This code send provide the
=gpt()
formule to your Google spreadsheet.When
gpt
formule is used, your sheet content is sent to chatGPT and used as context to answer your prompt.Installation
You are now able to use
=gpt()
in your google sheet.Example
Formule:
=gpt("What is Rose's age?")