Skip to content

Add an AI Assistant to RevoGrid with report previews and approved edits ​

Use RevoGrid AI Assistant to show European orders, summarize revenue by region, or change the amount on order 101. The filter runs immediately. The Pivot layout change and order edit open a preview with Apply and Cancel.

The example uses a small HTTP service to turn each request into a supported grid operation. It starts with scripted responses so you can test the previews without model credentials. Your application decides which operations to expose and handles authentication and persistence.

RevoGrid AI Assistant interface alongside a data grid.

Run the complete example ​

The starter source includes both browser integrations, an HTTP interpretation service, a narrow action policy, tests, and an optional model adapter.

sh
git clone https://github.com/revolist/revogrid-docs.git
cd revogrid-docs/examples/ai-assistant-workflows
npm ci
npm run dev

Use Node 24.13 or later and open http://127.0.0.1:5178. The starter installs pinned packages from the public trial registry. For production, follow the licensed installation guide.

In scripted mode, select one of the suggestions shown in the UI. The service returns a preset response so you can see exactly what the grid filters, previews or applies.

RequestWhat to doExpected result
Only EuropeSubmit in OrdersOrders 101 and 103 remain visible. Source values are unchanged.
Set order 101 amount to 1500Cancel the previewOrder 101 stays at 1200.
Set order 101 amount to 1500Submit again, then ApplyOrder 101 becomes 1500; order 103 remains 2400.
Show total amount by regionCancel, then repeat and Apply in ReportCancel preserves Year columns. Apply removes that axis: Europe 300, Asia 700, grand total 1000.

Orders and Report deliberately use independent fixtures. This example does not synchronize an editable order store with an analytical report. For that separate workflow, see an editable grid dashboard.

Decide which changes need approval ​

The assistant distinguishes view commands from prepared actions. A default filter/sort command updates view criteria directly. A data edit or pivot.configure action prepares a preview first. Do not promise that every request opens an approval dialog.

The interpreter never receives a callback capable of writing to the grid. It returns JSON. The browser validates that JSON against its configured fields and action registry before calling the existing owner. See the request and response contract.

Connect the Orders assistant ​

The starter creates a normal grid with AdvanceFilterPlugin, HistoryPlugin, and AiAssistantPlugin. The first supplies filtering, History owns accepted local data changes, and the assistant supplies the interaction.

ts
import {
  AdvanceFilterPlugin,
  AiAssistantPlugin,
  HistoryPlugin,
} from '@revolist/revogrid-pro';

grid.plugins = [AdvanceFilterPlugin, HistoryPlugin, AiAssistantPlugin];
grid.filter = true;
grid.columns = [
  { prop: 'id', name: 'Order', readonly: true, filter: 'number' },
  { prop: 'region', name: 'Region', readonly: true, filter: 'string' },
  { prop: 'amount', name: 'Amount', filter: 'number' },
];

grid.aiAssistant = {
  interpret: interpreter('grid'),
  mountTo: document.getElementById('orders-assistant')!,
  fields: [
    { field: 'region', label: 'Region', valueType: 'string', operators: ['equal'] },
    { field: 'amount', label: 'Amount', valueType: 'number', operators: ['equal'] },
  ],
  dataActions: {
    rowKey: 'id',
    enabled: ['cells.update'],
    maxRows: 1,
    canMutate: ({ before, after }) => before?.id === 101 &&
      after?.id === 101 && typeof after.amount === 'number' &&
      Number.isFinite(after.amount) && after.amount >= 0 && after.amount <= 10000,
  },
  ui: {
    mode: 'chat',
    suggestions: ['Only Europe', 'Set order 101 amount to 1500'],
  },
};

interpreter is our application function in the starter, not a RevoGrid export. It posts the prompt to /api/interpret/grid, forwards the abort signal, rejects failed HTTP responses, and returns the parsed result. The full source also waits for grid initialization and disposes the assistant when the page closes.

The stable key matters: order 101 remains the target after filtering or sorting. A visible row index would identify a different record when the view changes. The model cannot add or delete rows here because those actions are not enabled. The native data-action implementation checks writable fields and the configured mutation policy during preparation and again at Apply.

The service returns this result for the edit request:

json
{
  "kind": "action",
  "name": "cells.update",
  "input": {
    "rows": [101],
    "values": { "amount": 1500 }
  }
}

Receiving the result does not save the edit. The preview shows the old and proposed values. Cancel leaves the source untouched; Apply commits through the local grid owner. If the underlying data changes while approval is pending, the proposal must be prepared again.

Configure a Pivot report through its native adapter ​

A Pivot displays aggregate rows, so ordinary grid edits must not operate on that projection. The report assistant uses createPivotAiActions from @revolist/pivot, disables flat-grid field commands, and exposes only its approved dimensions.

ts
grid.aiAssistant = {
  interpret: interpreter('pivot'),
  mountTo: document.getElementById('pivot-assistant')!,
  fields: [],
  executor: {
    read: () => ({ sort: [] }),
    async apply() {
      throw new Error('Use native Pivot actions for this report.');
    },
  },
  actions: createPivotAiActions(pivot, {
    fields: ['region', 'year', 'amount'],
    readRows: false,
  }),
  ui: {
    mode: 'chat',
    suggestions: ['Show total amount by region'],
  },
};

Here pivot is the installed PivotPlugin instance, retrieved after the initial report is ready. The complete Pivot assistant guide covers that lifecycle. The starter starts with Region rows and Year columns, then proposes:

json
{
  "kind": "action",
  "name": "pivot.configure",
  "input": {
    "rows": ["region"],
    "columns": [],
    "values": [{ "field": "amount", "aggregator": "sum" }]
  }
}

An empty columns array removes the Year axis. Omitting it would preserve the current axis. Pivot performs the calculation after approval: the model does not add the numbers. Europe contains 100 + 200, Asia contains 300 + 400, and the grand total is 1000.

The adapter also documents a bounded pivot.read action, but the starter disables it: the installed trial 4.5.2 analytical read failed during browser verification while report configuration and rendering passed. This does not establish the behavior of a licensed build. Enable reads only after verifying your build and native analytical-query capability. Never treat loaded rows of a server-side report as complete database totals; use an application-owned analytical action for server-side Pivot.

Keep the action policy on the server ​

The example endpoint accepts a prompt but constructs every executable response itself. Its model-facing proposal has only two fields: an operation from a fixed catalog and an optional numeric amount. server/policy.mjs rejects unexpected properties, unknown operations, invalid amounts, and operations belonging to the other assistant.

ResponsibilityRevoGridApplication
Prompt, chat and approval UIAiAssistantPluginDecide placement and suggestions
Filtering and report calculationExisting grid/Pivot enginesChoose available fields and operations
Local edit preview and replay checksNative data actions and HistorySupply stable IDs and canMutate policy
Interpret natural languageCalls your interpret functionModel integration, credentials, usage limits
Save business recordsCustom prepared action can call your serviceAuthenticate, authorize, validate versions and commit

The included server is a localhost fixture with no user login or database. It binds to loopback and rejects other hosts and origins. Before publishing an endpoint, connect your existing authenticated session and tenant/report policy. Browser action descriptors describe capabilities; they cannot grant a caller permission to use them.

For persistent edits, preparation should fetch the authorized current record and produce a versioned proposal. Apply must recheck permission and the expected version, commit through your service, then publish the accepted result. This local cells.update example does not provide that transaction. The custom actions guide and batch conflict tutorial provide the next steps.

Enable live natural-language interpretation ​

The runnable service includes an optional OpenAI Responses adapter in server/provider.mjs. Export OPENAI_API_KEY and AI_MODEL in the server environment and restart npm run dev; the chosen model must support structured outputs. Other providers can replace that adapter without changing the RevoGrid integration.

The adapter requests a constrained JSON proposal, then the application validates and translates it to the native result. It rejects refusals, incomplete responses, and invalid proposals. Provider credentials remain on the server. Structured Outputs constrains response shape; it does not establish that the requested change is correct or authorized.

Only the prompt is forwarded in this starter. It does not send source rows, previous conversations, or returned report results to the model. Prompt text itself can still contain business information. Production integrations with dynamic field catalogs should review disclosure controls and build schemas from server-approved capabilities.

The reproducible tests use scripted responses. Live interpretation needs separate evaluation with your chosen model: paraphrases, ambiguous requests, attempts to edit other IDs, invalid numbers, and unsupported operations. Do not count a working scripted suggestion as a successful language-understanding test.

Verify failure paths as well as Apply ​

Run npm test and npm run build in the starter. The tests exercise the server-owned policy and provider-response parsing, while TypeScript checks the installed product APIs. In the UI, also try:

  • Cancel an edit, then reopen and Apply it. Cancel must leave no committed change.
  • Prepare an edit and manually change its source value before Apply. Request a fresh preview after the stale proposal is rejected.
  • Ask the Report assistant to edit an order. It must not write into aggregate rows.
  • Stop a pending interpretation. The browser forwards cancellation through the request.
  • Stop the local server. An HTTP failure must appear as an error, without a completed data change.

Try additional operations in the live AI Assistant demos.