Nowadays there are a lot of posts using the word ChatGPT
but many of them use it as a common noun to refer to GPT-3 and some chatbots, not to specically make refence to https://chat.openai.com/chat / ChatGPT, the chatbot released by OpenAI in November 2022, or make a brief mention of it but center all the discussion in other things.
I.E. Some posts mentions that for using ChatGPT in code we should use Open AI API. For the specific case of Google Sheets we could use it by using the UrlFetch Service of Google Apps Script to create a custom function among other.
Here is a sample custom function that uses OpenAI API to send a prompt and get response:
/**
* @param {string} prompt Prompt. Official guide for prompt design https://beta.openai.com/docs/guides/completion/prompt-design
* @param {string} apiKey OpenAI API key. Get yours from https://beta.openai.com/account/api-keys
* @customformula
*/
function getCompletion(prompt,apiKey){
const base = 'https://api.openai.com/v1/';
const maxTokens = 200;
const temperature = 0;
const url = base + 'completions';
const options = {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + apiKey
},
payload: JSON.stringify({
model: 'text-davinci-003',
prompt: prompt,
max_tokens: maxTokens,
temperature: temperature
}),
};
const response = UrlFetchApp.fetch(url, options);
const content = response.getContentText();
const code = response.getResponseCode();
if(code >= 200 && code < 300) {
/**
* TODO: Improve response handling
*/
const output = JSON.parse(content).choices[0].text;
return output.slice(0,50000);
} else {
console.error(content);
return new Error(content.slice(0,300));
}
}
Usage
A | |
---|---|
1 | =getCompletion("What is the capital of France","put here your OpenAI API key") |
One of the problems with this script is that it's only calling one end-point, https://api.openai.com/v1/completions
. Looking at the Chrome Developers Tools using https://chat.openai.com/chat it looks that there several end-points called. How to adapt this script use the end-points used by ChatGPT and make it work closer as a chat?
Let say that the converstion will be logged in a single column use one cell for the prompt and put the ChatGPT response inmediately below, then the next prompt will be added below and so on.
Related
Resources