Skip to content

Instantly share code, notes, and snippets.

@cybercase
Created April 27, 2024 16:34
Show Gist options
  • Save cybercase/84654824b2cee3a21a5c524470ea4b36 to your computer and use it in GitHub Desktop.
Save cybercase/84654824b2cee3a21a5c524470ea4b36 to your computer and use it in GitHub Desktop.
A Mac Automation Script to run OpenAI GPTs over selected text
/*
# A Mac Automation Script to run OpenAI GPTs over selected text.
Copy this script into your home directory, then:
1. Set the OPENAI_API_KEY variable in the script
2. Open the Automator app on your Mac and Create a new "Quick Action" workflow.
3. Set the workflow to receive "text" in "any application".
4. Add a "Run Shell Script" action.
5. Copy and paste the following command into the script box:
cat ~/gptactions.js | osascript -l JavaScript - $(cat)
6. Save the workflow with a name like "GPT Actions".
MIT License
Copyright (c) 2024 Stefano Brilli
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const OPENAI_API_KEY = ""; // Insert your API Key
const SHOW_LOGS = false; // For debugging purposes
// Simple actions
const SUMMARIZE_ACTION = "Summarize its content";
const SUMMARIZE_PROMPT =
"Summarize the following text using the same language of the text itself. The text might be coming from a web page so be sure to focus on the main content and ignore all advertisements if you find any:\n${selected_text_will_be_inserted_here}";
const TRANSLATE_ACTION = "Translate";
const TRANSLATE_PROMPT = "Translate the following text to English:\n${selected_text_will_be_inserted_here}";
const SIMPLE_ACTIONS = {
[SUMMARIZE_ACTION]: SUMMARIZE_PROMPT,
[TRANSLATE_ACTION]: TRANSLATE_PROMPT,
};
// Complex actions
const QUESTION_ACTION = "Ask a question about it";
const CUSTOM_ACTION = "Use a custom prompt";
const COMPLEX_ACTIONS = [QUESTION_ACTION, CUSTOM_ACTION];
let app = Application.currentApplication();
app.includeStandardAdditions = true;
function _run(args) {
if (!OPENAI_API_KEY) {
// If the API key is still not set, show an error to the user
showMissingOpenAIKeyDialog();
return;
}
let input = typeof args === "string" ? args : args.join(" ");
let action = showPromptsDialog();
if (!action) {
log("User cancelled the dialog. Exiting...");
return;
}
action = action[0];
let prompt = "";
if (action in SIMPLE_ACTIONS) {
prompt = SIMPLE_ACTIONS[action];
} else if (action === QUESTION_ACTION) {
prompt = showQuestionDialog();
} else if (action === CUSTOM_ACTION) {
prompt = showCustomPromptDialog();
} else {
log("Invalid action: " + action);
return;
}
if (!prompt) {
log("Prompt is empty. Exiting...");
return;
}
prompt = prompt.replace("${selected_text_will_be_inserted_here}", input + "\n");
log("Prompt: " + prompt);
let result = makeOpenAIRequest(prompt);
if (result === null) {
log("Error making OpenAI request. Exiting...");
return;
}
// Add new lines after each sentence
result = result.replace(/\.\s/g, ".\n\n");
showResultDialog(result);
return;
}
function run(args) {
try {
_run(args);
} catch(error) {
// Global error handler
if (error.message !== 'User cancelled.') {
showGenericErrorDialog("An error occurred: " + error.message);
}
}
}
function showPromptsDialog() {
let options = Object.keys(SIMPLE_ACTIONS).concat(COMPLEX_ACTIONS);
let response = app.chooseFromList(options, {
withTitle: "Choose an Action",
withPrompt: "What would you like to do with selected text?",
defaultItems: [options[0]],
okButtonName: "OK",
cancelButtonName: "Cancel",
});
return response;
}
function showCustomPromptDialog() {
let response = app.displayDialog("Please enter your prompt:", {
withTitle: "Use your own Prompt",
defaultAnswer: "${selected_text_will_be_inserted_here}\nTell me what you think about it.",
withIcon: "note",
buttons: ["OK", "Cancel"],
defaultButton: "OK",
});
return response.textReturned;
}
function showQuestionDialog() {
let response = app.displayDialog("Please enter your question about the text:", {
withTitle: "Ask a Question",
defaultAnswer: "Here is a text:\n${selected_text_will_be_inserted_here}\nWhat do you think about it?",
withIcon: "note",
buttons: ["OK", "Cancel"],
defaultButton: "OK",
});
return response.textReturned;
}
function showGenericErrorDialog(message) {
app.displayDialog(message, {
withTitle: "Error",
withIcon: "stop",
buttons: ["OK"],
defaultButton: "OK",
});
}
function showMissingOpenAIKeyDialog() {
app.displayDialog("Please set the OPENAI_API_KEY variable in the script or set it as an environment variable.", {
withTitle: "Missing OpenAI API Key",
withIcon: "stop",
buttons: ["OK"],
defaultButton: "OK",
});
}
function showResultDialog(result) {
app.displayDialog(result, {
withTitle: "Result",
buttons: ["OK"],
defaultButton: "OK",
});
}
function log(arguments) {
if (SHOW_LOGS) {
console.log(new Date().toISOString() + ": " + JSON.stringify(arguments));
}
}
function makeHttpRequest(url, method = "GET", headers = {}, data = null) {
let curlCommand = "curl -s -X " + method;
for (let key in headers) {
curlCommand += ' -H "' + key + ": " + headers[key] + '"';
}
if (method === "POST" && data) {
let dataString = JSON.stringify(data);
dataString = dataString.replace(/'/g, "'\\''"); // https://stackoverflow.com/questions/32122586/curl-escape-single-quote
curlCommand += " -d '" + dataString + "'";
}
curlCommand += ' "' + url + '"';
try {
// Execute the curl command
let result = app.doShellScript(curlCommand);
return result;
} catch (error) {
showGenericErrorDialog("Error making HTTP request: " + error.message);
return null;
}
}
function makeOpenAIRequest(prompt) {
let result = makeHttpRequest(
"https://api.openai.com/v1/chat/completions",
"POST",
{
"Content-type": "application/json",
Authorization: "Bearer " + OPENAI_API_KEY,
},
{
model: "gpt-3.5-turbo-0125",
messages: [
{
role: "system",
content: "You are a helpful assistant.",
},
{
role: "user",
content: prompt,
},
],
}
);
let response;
try {
response = JSON.parse(result);
} catch (error) {
showGenericErrorDialog("Error parsing OpenAI response: " + error.message);
return null;
}
try {
return response.choices[0].message.content;
} catch (error) {
showGenericErrorDialog("Error getting message content from: " + JSON.stringify(response, null, 2));
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment