Script :: ChatGPT

This script will read the frontmost Bike document, pass it to ChatGPT, and write the response in the same document.

  • Top level rows are “roles” and their (immediate) children are the content of the messages
  • Deeper children are ignored
  • Collapsed rows are omitted
  • The API will only accept ‘system’, ‘assistant’, ‘user’, ‘function’ as roles. For more information see the chat API documentation
var apiKey = "";
var baseURL = "https://api.openai.com/v1/chat/completions";
var model = "gpt-3.5-turbo"
var headers = {
  "Content-Type": "application/json",
  "Authorization": "Bearer " + apiKey
};

// Get queries from Bike

var bikeApp = Application("Bike");
var frontDocument = bikeApp.documents[0]

var messages = [];
frontDocument.rows().forEach(function(row) {
  console.log("row: ", row.name());
  if (row.level() == 1 && !row.collapsed()) {
    row.rows().forEach(function(childItem) {
      const content = childItem.name();
      messages.push({ "role": row.name(), "content": content });
    });
  }
});

// Make http request, parse response

var payload = JSON.stringify({
  "model": "gpt-3.5-turbo",
  "messages": messages,
  "max_tokens": 50}).replace(/[\/\(\)\']/g, "'");

var command = 'curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer ' + apiKey + '" -d \'' + payload + '\' ' + baseURL;

var app = Application.currentApplication();
app.includeStandardAdditions = true;
var response = app.doShellScript(command);

var parsedData = JSON.parse(response);
var content = parsedData.choices[0].message.content;

// Write response back to Bike

var lastRow = null;
var rows = frontDocument.rows();
for (var i = rows.length - 1; i >= 0; i--) {
  var row = rows[i];
  if (row.level() == 1 && !row.collapsed()) {
    lastRow = row;
    break;
  }
}

if (lastRow.name() != "assistant") {
  lastRow = new bikeApp.Row({ name: "assistant" });
  frontDocument.rows.push(lastRow);
}

content.split("\n").forEach(function(line) {
  var newRow = new bikeApp.Row({ name: line });
  lastRow.rows.push(newRow);
});

It’s like a bicycle for your mind with a 25CC engine crudely bolted onto the frame.

2 Likes

Haha, I love the image! I will now go try out the script.

I ended up getting an “over quota” error, so the script didn’t work. I’m using free tier of chat, but I don’t think I’ve singed on for a month or so. Not sure what is up. Anyway thanks again for posting script. If you have a minute I think it would be useful to also include a simple “example” Bike outline so people have something to start with.