Agents
You will learn how an agent works with a document: it reads the grammar from describe(), sends commands as JSON, dry-runs them with preview, and gets errors back as JSON it can act on.
dart
import 'dart:convert';
import 'package:vyuh_document/vyuh_document.dart';
import 'package:vyuh_document_elements/vyuh_document_elements.dart';
/// Lets an agent learn the grammar, then send commands as JSON.
void main() {
final configuration = notesConfiguration;
// Elements, content rules, attributes, traits and commands with their
// argument types: give this to the model as its tool description.
final grammar = jsonEncode(configuration.describe().toJson());
print(grammar.length);
final controller = DocumentController(
configuration,
author: const Author.agent('planner'),
);
// A command arrives as JSON. Decoding never throws.
final decoded = configuration.decodeCommand({
'command': 'InsertRwo', // a typo
'table': {'element': 'vyuh.document.block.table', 'id': 't1'},
'at': 2,
});
switch (decoded) {
case Done(:final value):
final result = controller.preview(value); // dry run first
print(result.isDone);
case Failed(:final error):
// UnknownCommand: "Did you mean InsertRow?" Return it to the agent.
print(jsonEncode(error.toJson()));
}
controller.close();
}The grammar
configuration.describe() returns a DocumentDescription: every element with its attributes and commands, the marks, and the shared commands. Put its toJson() (or toPrettyJson()) in the agent's tool description.
Commands as JSON
Every command has a generated JSON form: {"command": "InsertRow", ...arguments}.
| Call | Does |
|---|---|
command.toJson() | Serializes a typed command |
configuration.decodeCommand(json) | Result<Command>; UnknownCommand (with didYouMean) or InvalidDocument (with the argument path) |
controller.preview(command) | The resulting document, nothing applied |
controller.run(command) | Applies it, attributed to the controller's author |
error.toJson(), DocumentError.fromJson(json) | Errors as data |
References serialize as {"element": "vyuh.document.block.table", "id": "t1"}.
Patterns
- Give each agent its own controller with
Author.agent(name)andjoin; a person can undo their own edits without undoing the agent's. - Preview before running when the agent's plan has several steps.
- Return
error.toJson()to the model verbatim:where,expected,foundandhintare written for it.
Wrap decodeCommand and run in your own tool handler.
Next
- Commands: the full catalog.
- Loading and saving: persisting the JSON.