Using Grok AI with Drafts

@agiletortoise Can you please update Drafts to use Grok AI like OpenAI and Claude?

1 Like

I believe the Grok AI API is Open AI-compatible, so the integration already exists, and can be used through the OpenAI object…you would just need to modify the host/model values for the object to point to Grok.

For an example, see the Deep Seek or Perplexity examples I’ve posted that do the same for those services.

1 Like

This seems to be working. This scripts modifies text selections with specific instructions.

// get your input selected text, and store range for later
const selection = editor.getSelectedText()
const [st, len] = editor.getSelectedRange()

// Prompts
let f = () => {
    let instruction = `Revise the provided input to make it concise, clear, and informative, adhering to a semi-formal tone. Follow Canadian English spelling and conventions. Preserve the abbreviation 'MVA'. Ensure the revised text is suitable for inclusion in a psychological report. Input: `
    let chatPrompt = `${instruction} "${selection}"`
    
    // Set up Grok AI with credentials and xAI API endpoint
    let host = "https://api.x.ai/v1" // xAI's API base URL
    let ai = OpenAI.create(null, host) // Initialize with xAI host
    ai.model = "grok-beta" // Using the Grok beta model
    ai.credentialIdentifier = "Grok" // Matches your credential setup
    
    // Send prompt to Grok AI
    let answer = ai.quickChatResponse(chatPrompt)
    
    // if we got no reply, cancel
    if (!answer || answer.length == 0) {
        return false
    }
    
    editor.setSelectedText(answer)
    editor.setSelectedRange(st, answer.length)
    return true
}

if (!f()) {
    context.fail()
}

Looks right…only change I might make is the below:

// change this...
let ai = OpenAI.create(null, host) // Initialize with xAI host
// to this...
let ai = OpenAI.create("Grok", host) // Initialize with xAI host

That first parameter tells the credential system to use a different identifier, so an API key you enter would not conflict with API keys for OpenAI, if you also use OpenAI actions.

Tried it but let ai = OpenAI.create("Grok", host) breaks the Action.

Error:

OpenAI: 400, {"code":"Client specified an invalid argument","error":"Incorrect API key provided: ***. You can obtain an API key from https://console.x.ai."}
undefined
Script step completed.

My bad, forgot the signature on that one…what I said was already handled by setting the credentialIdentifier

So no change needed?