Create a secret key, add one route to your server, and point the grid's AI Assistant at it. Your users can then ask the grid in plain words, and the grid filters, sorts, groups or totals to show the answer.
This path uses MUI's own resolver. You install nothing from Gridsay.
DataGridPremium from @mui/x-data-grid-premium. Gridsay is compatible with MUI X Data Grid Premium and tested with version 9.18.0.Already forwarding to MUI's hosted service? Change two lines instead: Moving from MUI's service.
fast is the default and suits most grids; the tiers are compared below.Put both in your server's environment:
# Save at your app root, beside package.json. Restart your dev server after saving.GRIDSAY_URL=<your Gridsay URL, from the dashboard>GRIDSAY_SECRET_KEY=<your secret key>Keep the secret key on your server. Anyone who has it can spend your credits.
Send one question from a terminal before you change your app. It costs one credit on a fast key.
# Run from your app root, after filling .env.local.set -a. ./.env.localset +a curl -s -X POST "$GRIDSAY_URL/api/v1/datagrid/prompt" \ -H "content-type: application/json" \ -H "x-api-key: $GRIDSAY_SECRET_KEY" \ -d '{"query":"highest salary first","context":"[{\"field\":\"salary\",\"type\":\"number\",\"description\":null,\"examples\":[],\"allowedOperators\":[\">\",\"<\"]}]"}'The response has status 201:
{ "ok": true, "data": { "conversationId": "…", "select": -1, "filters": [], "filterOperator": "and", "aggregation": {}, "sorting": [{ "column": "salary", "direction": "desc" }], "grouping": [], "pivoting": {}, "chart": null }, "meta": { "tier": "fast", "usedQueries": 1, "remainingQueries": null, "resetAt": "…" }}data is what the grid applies: here, sorting. meta.tier is the tier that answered and was charged. If ok is false, the response has a code: look it up in Errors.
The route checks that the caller is signed in to your app, adds your secret key, and forwards the grid's request unchanged. It returns Gridsay's body and status as they came.
// If your app uses src/, create src/app/api/ai-assistant/route.ts instead. export async function POST(request: Request) { // Each question spends your credits, so only your signed-in users may ask. if (!(await isSignedIn(request))) { return Response.json({ ok: false, code: 'unauthenticated_user', message: 'Sign in to use the assistant.' }, { status: 401 }); } const key = process.env.GRIDSAY_SECRET_KEY; const gateway = process.env.GRIDSAY_URL; if (!key || !gateway) { console.error('[Gridsay] Set GRIDSAY_SECRET_KEY and GRIDSAY_URL in .env.local at your app root. Restart your dev server.'); return Response.json({ ok: false, message: 'The assistant is not configured. Please contact the app owner.' }, { status: 500 }); } const body = await request.text(); let response: Response; try { response = await fetch(`${gateway}/api/v1/datagrid/prompt`, { method: 'POST', headers: { 'content-type': 'application/json', 'x-api-key': key, origin: request.headers.get('origin') ?? '', }, body, // Never follow a redirect: it would send your key to another address. redirect: 'error', }); } catch { console.error('[Gridsay] Could not reach the gateway. Check GRIDSAY_URL and your server’s network connection.'); return Response.json({ ok: false, message: 'The assistant cannot connect right now. Try again later.' }, { status: 503 }); } if (!response.ok) console.error('[Gridsay] Request failed:', response.status, await response.clone().text()); const headers = new Headers({ 'content-type': 'application/json' }); const retryAfter = response.headers.get('Retry-After'); if (retryAfter !== null) headers.set('Retry-After', retryAfter); return new Response(response.body, { status: response.status, headers });} async function isSignedIn(request: Request) { // Your sign-in check goes here, e.g. return Boolean(await getSignedInUser(request)); if (process.env.NODE_ENV === 'development') return true; console.error('[Gridsay] Refused: add your sign-in check to isSignedIn before you deploy.'); return false;}Before you deploy, put your own sign-in check in isSignedIn. As copied, the route answers only on your development server and refuses every request in production. A secret key does not tell Gridsay who your user is: checking that is your route's job.
Not on Next.js? Do the same five things: check the caller, forward the JSON body unchanged with the x-api-key header, refuse redirects, forward the browser's Origin if your key is locked to origins, and return Gridsay's JSON body and status.
Give MUI's stock resolver the route's path. slots and showToolbar put the assistant's button and panel on the grid; leave them out if your grid has them already.
'use client'; import { DataGridPremium, GridAiAssistantPanel, unstable_gridDefaultPromptResolver,} from '@mui/x-data-grid-premium'; function onPrompt(query: string, context: string, conversationId?: string) { return unstable_gridDefaultPromptResolver('/api/ai-assistant', query, context, conversationId);} // Keep your rows and columns; put this in your client component's return value.// With Next.js Cache Components, wrap that component in Suspense in its parent.<DataGridPremium rows={rows} columns={columns} aiAssistant onPrompt={onPrompt} slots={{ aiAssistantPanel: GridAiAssistantPanel }} showToolbar/>With MUI's stock resolver, the browser sends the question and your column definitions: field, type, description, allowed filter operators and example values. Example values are cells from your rows only if you turn on allowAiAssistantDataSampling or write them into your columns.
Open the AI Assistant panel and ask about a column you have. On a table of employees with a remote column:
only remote people
filter remote is trueThen ask a follow-up, such as "now sort them by salary, highest first". The grid keeps the filter and adds the sort: Follow-up questions explains how.
Both questions appear under Requests on the Usage page of the dashboard.
Ask something the grid cannot show. A condition on a group's count is one:
departments with more than 100 people
I can't filter on counts of people per department, since that would be a condition on an aggregate.
Your user reads this sentence. The table stays as it was.The panel shows the sentence and the grid stays as it was. The response has status 422 and the code query_not_understood. A refusal is charged like an answer, because the model read the question. Refusals and errors lists every case.
Your route can add options to the body before it forwards it:
metadata.referenceId is your id for the user, up to 127 characters. The dashboard groups usage by it, and Gridsay stores it only as a keyed hash. Gridsay also counts its allowance for failed questions per user by it instead of for the whole key. It does not sign the user in or give them limits of their own.privateMode: true stops Gridsay storing the question and the answer. It also turns off follow-ups that build on earlier answers: see private mode.additionalContext explains your data in up to 20,000 characters, for example which currency an amount is in. Keep secrets and personal data out of it.// Replace const body = await request.text() with:const body = await request.json();body.options = { ...body.options, privateMode: true, metadata: { referenceId: currentUserId }, // your own user id};// In fetch, replace body, with body: JSON.stringify(body),To verify each user and give each their own limit, use a publishable key from the browser instead.
The key sets the tier. To use different tiers on different screens, create one key per tier.
| Tier | Credits per question | Use it for |
|---|---|---|
fast | 1 | Most grids |
standard | 10 | Vague or multi-step questions, and screens where a wrong answer is costly |
max | 25 | The questions where being right matters most |
auto | 1 or 10; 25 if the key allows max | Keys where you would rather not choose |
On auto, Gridsay picks the tier for each question, and the question costs what that tier costs. How often each tier is right: accuracy.
The grid shows the response's message to your user; code and detail are for you. A JSON parsing error in the panel usually means the grid is calling a path where your route is not.
Every status and code, what the user sees and whether it is charged: Refusals and errors.