Action

Claude: Translate Selection

Posted by agiletortoise, Last update 8 months ago

Prompt to select from a list of languages, and ask Anthropic’s Claude AI to translate the selected text in the editor to that language, replacing the text with the result.

For more information and examples incorporating Antropic Claude, visit the integration guide

Steps

  • script

    // setup languages available in prompt
    const targetLanguages = ["Spanish", "French", "German", "English"]
    const models = AnthropicAI.knownModels()
    
    let f = () => {
    	let p = new Prompt()
    	p.title = "Translate Selection"
    	p.message = "Select language for translation."
    	p.addSelect("lang", "Language", targetLanguages, [targetLanguages[0]])
    	p.addSelect("model", "Model", models, [models[0]], false)
    	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}, returning only the result: "${selection}"`
    
    	// create API object and use single response
    	// convenience function to send prompt
    	let ai = new AnthropicAI()
    	const model = p.fieldValues["model"][0]
    	let answer = ai.quickPrompt(chatPrompt, {"model": model})
    
    	// 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 {
    		context.fail()
    		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.