Summarizing text with OpenAI API

Hey all!

I made a quick test with OpenAI GPT-3 to summarize text and add the TL;DR to another field. I find it kinda cool, and it was super quick to make, so sharing the example if someone finds it useful.

You’ll need to sign up to OpenAI and generate your own API key there.

Add a scripting app, and here’s the code (remember to edit your own table and field names, and add your own API key):

// Change this to the name of a table in your base
let table = base.getTable('Documents');

let openaiUrl = "https://api.openai.com/v1/engines/text-davinci-002/completions";

// Prompt the user to pick a record 
// If this script is run from a button field, this will use the button's record instead.
let record = await input.recordAsync('Select a record to use', table);

if (record) {

    // Construct the body
    // Change the field name to match yours.
    let body = {
        "prompt": record.getCellValue("Text") + "\n\nTl;dr",
        "temperature": 0.7,
        "max_tokens": 60,
        "top_p": 1.0,
        "frequency_penalty": 0.0,
        "presence_penalty": 0.0
        }

    // Make a request to OpenAI API
    // Add your own API key in the place of Xses.
    let response = await fetch(openaiUrl, {
        method: 'POST',
        body: JSON.stringify(body),
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
        },
    });
    let data = await response.json();

    // Comment this out if you don't want to see any outputs
    console.log(data)

    let str = /[^A-Za-z0-9](.+)/.exec(data.choices[0].text)[1];

    // Write to a cell, change field name to match your table.
    table.updateRecordAsync(record, 
        {
            'TLDR': str
        });
}

Sweet! And there is a ton of other things you can use OpenAI API for. And you could automate this to happen every time a record is created.

Check out a video from my Tweet how it looks in real life:

7 Likes

Very nice! I just tested it out this morning.

It wasn’t reading the Tl;dr at first, so added a space so it read " \n\nTl;dr" and that seemed to make it work better. Not sure if the space really did anything or GPT-3 was being weird. The first few times it was just spitting out a few lines from within the text.

The da-vinci engine’s 4000 token limit (~3000 words) makes it a bit less useful for many of the things I read or want summarized though.

I know, the token limit sucks right. But then again. This stuff will develop fast, and soon we have forgotten such limits…

Have you had any problems with the summarizer not finishing the summary? Sometimes it just ends on an incomplete sentence. I know the tl;dr has a 60 token limit for output.

I have seen the same happening. I’ve meant to take a look at the parameters in the api call, but have not unfortunately had any time this week for hobbies. :triumph: