Action

OpenAI: Add Punctuation in Selection

Posted by tomtjes, Last update 7 months ago

Add punctuation to the selected text using OpenAI’s GPT 3.5 turbo 16k model (works for longer texts). The result will replace the text selection.

For more information on using this action, visit our OpenAI integration guide

Steps

  • script

    // get editor values
    const [st, len] = editor.getSelectedRange()
    const selection = editor.getSelectedText()
    
    // build prompt
    const instruction = `Add punctuation to the following text:\n`
    const prompt = instruction + selection
    
    // create OpenAI API object and use single response
    // convenience function to send prompt
    let ai = new OpenAI()
    ai.timeout = 400;
    let response = ai.request({
        "path": "/chat/completions",
        "method": "POST",
        "data": {
            "model": "gpt-3.5-turbo-16k",
            "messages": [
                {
                    "role": "user",
                    "content": prompt
                }
            ]
        }
    })
    
    // report status
    console.log(`CODE: ${response.statusCode}
    
    ERR: ${response.error}
    `)
    
    // if we got a reply, add it to the draft
    if (!response.error) {
    	let answer = JSON.parse(response.responseText);
    	answer = answer["choices"][0]["message"]["content"]
    	answer = answer.replace(/^"+|"+$/g, '')
    	editor.setSelectedText(answer)
    	editor.setSelectedRange(st, answer.length)
    }
    else {
    	context.fail()
    }
    

Options

  • After Success Default
    Notification Info
    Log Level Info
Items available in the Drafts Directory are uploaded by community members. Use appropriate caution reviewing downloaded items before use.