注册自定义命令和提示
Available in Start plan
基础 AI 生成扩展提供了一组内置命令,但你也可以扩展它来定义自己的命令。这些自定义命令可用于通过你的自定义提示词调用 LLM。
注册自定义命令
要注册你自己的 AI 命令,只需扩展 Basic AI Generation 扩展,在 addCommands() 中添加你的命令(别忘了在 this.parent?.() 中继承预定义命令),然后执行 aiTextPrompt() 来运行你的单独提示词。
请注意,此示例是在客户端使用你的提示词,这意味着用户可以读取它。如果你想使用自定义语言模型(LLM)或在后端使用提示词,请参阅 自定义 LLM 指南。
import { Ai, getHTMLContentBetween } from '@tiptap-pro/extension-ai'
// … 其他导入
// 如果使用 TypeScript,声明扩展类型。
// 更多信息: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: `将以下文本翻译成法语并添加一些表情符号: ${selectedText}`,
...options,
})
},
}
},
})
// 初始化你的 Tiptap 编辑器实例并注册扩展后的扩展
const editor = new Editor({
extensions: [
StarterKit,
AiExtended.configure({
/* … */
}),
],
content: '',
})
// 运行你的自定义命令
// editor.chain().focus().aiCustomTextCommand().run()