ChatGPT script to use in action

Hi there
Trying to call chatGPT from a selected line in a note, this is the code I got from … GPT (must say I am not a developper at all).
I have entered my API Key (not displayed here).
Using iPad with iOS 16 latest release, Drafts latest release.
I get the displayed error in the screenshot.

Any help will be appreciated.

// Get the selected line from the Drafts note
const input = draft.getSelectedText();

// Replace this with your own API key
const apiKey = “your_api_key_here”;

const endpoint = “https://api.openai.com/v1/completions”;

const payload = {
“prompt”: input,
“model”: “text-davinci-002”,
“max_tokens”: 2048,
“top_p”: 1,
“frequency_penalty”: 0,
“presence_penalty”: 0
};

const options = {
“method”: “POST”,
“headers”: {
“Content-Type”: “application/json”,
“Authorization”: Bearer ${apiKey}
},
“payload”: JSON.stringify(payload)
};

const response = UrlFetchApp.fetch(endpoint, options);
const output = response.getContentText();

// Replace the selected line with the generated text from GPT
draft.setSelectedText(output);

In a general sense, that generated code doesn’t look like it will work. How about modifying an existing GPT action like this one? I haven’t used it, but maybe you could start by trying it out?

Do also note that selected text is not the same as a line of text. You can select part of a line, or multiple lines for example.

Thanks a lot for reference action, I did not find it previously.
First test does not send back anything.

I typed in my API Key in credential.addPasswordField(‘gptKey’, “my_key”), is that correct ?

Then what about “Credentials for a GPT toy” ?
I only have an API Key so I do not know what to type in where ?

I said I am not a developper :smiley:

You should not have had to make any changes to that script. The Credentials would have prompted you for that information when the action was run.

Try to re-install the default version of the action and try again.

1 Like

Thanks a lot.
Fixed.
I had to reset the credentials, then it is ok and I get an answer.

Thanks a lot for your support, both of you :slight_smile:

1 Like

Have a similar issue - 401 and 429 errors - when I uninstall the action - and reinstall, it doesn’t ask for the new API - as if it is picking it up from previous install - how do I kill that and start again?

Many thanks in anticipation.

See “Forgetting Credentials (Logout)” in the docs.

1 Like

Thankyou Stephen - that did the trick.

I am now getting a 429 error - according to the action log. Which I understand is ‘too many requests’ - any ideas how I can fix that?

See details here for recommendations. I suspect being on the free plan is the main way to address this for most users.

https://help.openai.com/en/articles/6891829-error-code-429-rate-limit-reached-for-requests