Any ChatGPT library for AppleScript that allows me to send questions and receive responses?

I just realised it would be very useful to be able to send questions and receive responses from ChatGPT in AppleScript. Has anyone written something that does that one can reuse?

I asked ChatGPT to write such script (Write an AppleScript that allows me to interact with ChatGPT. I want the AppleScript to send a question to ChatGPT and then receive the response as a string I can use in my AppleScript.)

-- Set your OpenAI API credentials
set apiKey to "YOUR_API_KEY"

-- Set the URL for the OpenAI API
set apiUrl to "https://api.openai.com/v1/engines/davinci-codex/completions"

-- Set the prompt for your question
set questionPrompt to "What is your question?"

-- Set the temperature for generating the response (0.0 to 1.0)
set temperature to 0.7

-- Set the maximum number of tokens in the response
set maxTokens to 100

-- Encode the question prompt for use in the API request
set encodedPrompt to do shell script "echo " & quoted form of questionPrompt & " | python -c 'import sys; import urllib.parse; sys.stdout.write(urllib.parse.quote(sys.stdin.read().strip()))'"

-- Prepare the JSON payload for the API request
set payload to "{\"prompt\": \"" & encodedPrompt & "\", \"temperature\": " & temperature & ", \"max_tokens\": " & maxTokens & "}"

-- Make the API request and get the response
set curlCommand to "curl -s -X POST -H 'Authorization: Bearer " & apiKey & "' -H 'Content-Type: application/json' -d '" & payload & "' " & apiUrl
set responseJson to do shell script curlCommand

-- Extract the response from the JSON
set AppleScript's text item delimiters to "\"text\":\""
set responseParts to text items of responseJson
set AppleScript's text item delimiters to "\""
set responseText to text item 2 of first item of responseParts

-- Display the response
display dialog responseText buttons {"OK"} default button 1

Doesn’t work out of the box but I will play around a bit and see if I can fix it.

I wrote it 4 month ago.
http://piyocast.com/as/archives/15558

1 Like