Selection awareness
Configure the AI so that it can read and edit the selected content in the editor.
Continuation from the AI agent chatbot guide
This guide continues the AI agent chatbot guide. Read it first.
See the source code on GitHub.
The readSelection tool 
The readSelection tool allows the AI agent to read the selected content in the editor.
It is included by default in the list of tool definitions that are passed to the AI model.
// Server-side code
import { toolDefinitions } from '@tiptap-pro/ai-toolkit-ai-sdk'
const definitions = toolDefinitions({
  // Enable the readSelection tool.
  // The readSelection tool is enabled by default.
  readSelection: true,
})The tool can then be executed in the client-side using the executeTool method. It does not require any parameters.
// Client-side code
const toolkit = getAiToolkit(editor)
const result = await toolkit.executeTool({
  toolName: 'readSelection',
})The output of the tool contains the following information:
- The content of the selection
 - The position of the selection
 
This information lets the AI know what content is selected, and where it is located in the document, so that it can edit it later.
If reading and writing the selection is not a requirement of your app, you can disable the tool by passing false to the readSelection option in the tool definitions.
// Server-side code
import { toolDefinitions } from '@tiptap-pro/ai-toolkit-ai-sdk'
const definitions = toolDefinitions({
  // Disable the readSelection tool.
  readSelection: false,
})Preserving the selection
Sometimes, while the AI is doing its work, the user changes the selection in the editor. This confuses the AI: when it has finished deciding what to do, it does not know that the selection has changed, so it reads the wrong selection content.
To avoid this, you can store the selection when the user sends a message to the AI, so that it does not change while the AI is thinking (even if the user changes it afterwards).
First, call the setActiveSelection method with the current selection when the user sends a message to the AI.
const toolkit = getAiToolkit(editor)
// Call this method just before the AI starts working.
toolkit.setActiveSelection(editor.state.selection)Then, when the AI finishes its work, call the setActiveSelection method with null to unset the active selection.
toolkit.setActiveSelection(null)You can also set the active selection to any position in the document.
toolkit.setActiveSelection({ from: 10, to: 20 })End result
With additional CSS styles, the result is a simple but polished AI chatbot that can edit the selected content:
See the source code on GitHub.
Next steps
- Learn more about the 
getActiveSelectionandsetActiveSelectionmethods in the API reference.