Skip to content

Instantly share code, notes, and snippets.

@bricemaurin
Forked from abi/gpt3-in-your-sheets.js
Last active March 28, 2023 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bricemaurin/270076c347c085c4085444b0a57cd968 to your computer and use it in GitHub Desktop.
Save bricemaurin/270076c347c085c4085444b0a57cd968 to your computer and use it in GitHub Desktop.
// Copiez votre API key depuis https://platform.openai.com/account/api-keys
const SECRET_KEY = ENTER YOUR SECRET KEY HERE;
// utile pour éviter de cramer trop de crédits par query.
const MAX_TOKENS = 200;
// Forké & mis à jour pour supporter GPT3.5 depuis le code de Abi. Suivez Abi sur Twitter: https://twitter.com/_abi_
/**
* Completes your prompt with GPT-3
*
* @param {string} prompt Prompt
* @param {number} temperature (Optional) Temperature. 1 is super creative while 0 is very exact and precise. Defaults to 1 to copy chatGPT.
* @param {string} model (Optional) GPT-3 Model to use. Defaults to "gpt-3.5-turbo".
* @return Completion returned by GPT-3
* @customfunction
*/
function AskGPT(prompt, temperature = 1, model = "gpt-3.5-turbo") {
const url = "https://api.openai.com/v1/chat/completions";
const payload = {
model: model,
messages: [{"role": "user", "content": prompt}],
temperature: temperature,
max_tokens: MAX_TOKENS,
};
const options = {
contentType: "application/json",
headers: { Authorization: "Bearer " + SECRET_KEY },
payload: JSON.stringify(payload),
};
const res = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
return res.choices[0].message.content.trim();
}
/**
* Classifies an item into a fixed set of categories
* @param {range} categories Set of categories
* @param {string} item Item to classify
* @param {range} rules (Optional) Set of rules written in plain text
* @return Completion returned by GPT-3
* @customfunction
*/
function CategorizeGPT(categories, input, rules=[]) {
const prompt = "The available categories are " + categories.map((c) => `"${c}"`).join(", ") + ". " + rules.join(". ") + "The category for '" + input + "' is ";
console.log(prompt);
const completion = AskGPT(prompt, 0, "gpt-3.5-turbo");
// Replace "s and .s at the start and end of the string
return completion.replace(/^"/g, '').replace(/["|.]{0,2}$/, '');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment