How Canvas Works
When a user selects a portion of an artifact and requests an edit:- The selection’s start and end indices (character positions) are captured.
- The user provides a description of what they want to change.
- The artifact ID identifies which artifact to edit.
- Your agent receives this structured information to process the edit request.
- Know exactly which part of the artifact the user wants to modify.
- Access the original artifact content from history.
- Make targeted edits based on the user’s description.
- Generate a new artifact with the changes (using the same artifact_id to replace the previous version in the UI).
Example: Canvas with LLM
Here’s how to use canvas with an LLM, adapting your system prompt based on whether you’re generating new content or editing existing content:Import the canvas extension
Import
CanvasExtensionServer and CanvasExtensionSpec from agentstack_sdk.a2a.extensions.ui.canvas.Inject the extension
Add a canvas parameter to your agent function using the
Annotated type hint
with CanvasExtensionSpec().Parse edit requests
Call
await canvas.parse_canvas_edit_request(message=message) to check if the
incoming message contains a canvas edit request. This returns None if no
edit request is present, or a CanvasEditRequest object with:start_index | The starting character position of the selected text |
end_index | The ending character position of the selected text |
description | The user’s description of what they want to change |
artifact | The full original artifact object from history |
Access the original content
Extract the text from
artifact.parts[0].root.text (for text artifacts) into a content variable and
use the start/end indices to get the selected portion: selected_text = content[start_index:end_index].How to work with Canvas
Artifacts in history: The extension automatically retrieves the original artifact from history using theartifact_id. If not found, a ValueError is raised.
Text parts filtering: The extension filters out fallback text messages (sent for agents that don’t support canvas) so you only work with structured edit request data.