Register a custom command and prompt

The AI Generation extension provides a list of built-in commands, but you can extend it to define your own. These custom commands can be used to call the LLM with your custom prompt.

Register a custom command

To register your own AI commands, simply extend the AI Generation extension, add your command in addCommands() (don't forget to inherit the predefined commands in this.parent?.()), and execute aiTextPrompt() to run your individual prompt.

Please note that this example uses your prompt on the client-side, which means that users could read it. If you're looking to use a custom Language Model (LLM) or a prompt on your backend, please refer to the example provided here.

import { Ai, getHTMLContentBetween } from '@tiptap-pro/extension-ai'

// … other imports

// Declare extension types if TypeScript is used.
// More info: https://tiptap.dev/docs/guides/typescript
//
// declare module '@tiptap/core' {
//   interface Commands<ReturnType> {
//     ai: {
//       aiCustomTextCommand: (options?: TextOptions) => ReturnType,
//     }
//   }
// }

const AiExtended = Ai.extend({
  addCommands() {
    return {
      ...this.parent?.(),

      aiCustomTextCommand:
        (options = {}) =>
        ({ editor, state }) => {
          const { from, to } = state.selection
          const selectedText = getHTMLContentBetween(editor, from, to)

          return editor.commands.aiTextPrompt({
            text: `Translate the following text to French and add some emojis: ${selectedText}`,
            ...options,
          })
        },
    }
  },
})

// Initialize your Tiptap editor instance and register the extended extension

const editor = new Editor{
  extensions: [
    StarterKit,
    AiExtended.configure({
      /* … */
    }),
  ],
  content: '',
})

// Run your custom command
// editor.chain().focus().aiCustomTextCommand().run()