Action

OpenAI: Translate Selection

Posted by agiletortoise, Last update about 1 month ago

UPDATES

about 1 month ago

Default to new “gpt-4o” model

Translate the selected text using OpenAI text edits. The action will prompt to select a language for the translation.

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

Steps

  • script

    // setup languages available in prompt
    const model = "gpt-4o"
    const targetLanguages = ["Spanish", "French", "German", "English"]
    
    let f = () => {
    	let p = new Prompt()
    	p.title = "Translate Selection"
    	p.message = "Select language for translation."
    	p.addSelect("lang", "Language", targetLanguages, [targetLanguages[0]])
    	p.addButton("Translate")
    
    	if (!p.show()) {
    		return false
    	}
    	const targetLanguage = p.fieldValues["lang"][0]
    	
    	// get editor values
    	const [st, len] = editor.getSelectedRange()
    	const selection = editor.getSelectedText()
    
    	// build prompt
    	const chatPrompt = `Translate the following text into ${targetLanguage}: "${selection}"`
    
    	// create OpenAI API object and use single response
    	// convenience function to send prompt
    	let ai = new OpenAI()
    	ai.model = model
    	let answer = ai.quickChatResponse(chatPrompt)
    
    	// if we got a reply, add it to the draft
    	if (answer && answer.length > 0) {
    		answer = answer.trim().replace(/^"+|"+$/g, '')
    		editor.setSelectedText(answer)
    		editor.setSelectedRange(st, answer.length)
    		return true
    	}
    	else {
    		return false
    	}
    }
    
    if (!f()) {
    	context.cancel()
    }
    

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.