Ask: grounded AI Q&A
Ask a natural-language question, get a chart. Grounded on the semantic layer so the planner cannot hallucinate columns or metrics. Multi-turn, auto-save, cross-persona handoff, diagnostic fan-out.
What this page does for you
A one-page tour of Goni’s grounded AI Q&A: how the planner is prevented from hallucinating, the three endpoints that back it, BYOK provider setup, and per-tenant token budgeting.
Endpoints on this page
POST /api/ask- natural-language question, grounded plan, executed chartGET /api/ask/catalog- the grounding surface the planner sees for this callerPOST /api/ask/eval- regression harness (faithfulness + hallucination refusal)GET /api/settings/ai,PATCH /api/settings/ai,DELETE /api/settings/ai- BYOK provider configGET /api/ai/budget- per-tenant hourly token headroom
How grounding works
Goni’s planner cannot reference a column, table, metric, dimension, or time grain that does not exist in the semantic layer. Before the LLM is called, Goni snapshots the loaded semantic project into a catalog: a map of metric name to {label, entities, grain}. That catalog is JSON-serialised and passed to the provider, and the compiled planner returns only metric names present in the catalog. Grounding is structurally enforced by the post-validation step below, not prompt-instructed.
After the LLM returns a Plan { metric, dimensions, time_grain, filters, limit }, Goni validates that metric is a key in the catalog, every dimension is in that metric’s entities list, and time_grain is one of day|week|month|quarter|year. Anything off the rails becomes status: "clarify" with the catalog echoed back so the UI can render “here is what you can ask”.
Row-level filters flow into the diagnose and planner paths, so they apply to the compiled SQL exactly as they would in a hand-built chart. See Access control.
Current limitation (per-metric ACL). The
AllowMetricsper-role gate that scopes what a caller can query through/api/metric/{name}/queryis not yet applied to the/api/askplanner path or to the/api/ask/cataloggrounding surface. Any authenticated caller in the tenant sees the full project catalog and can plan against any metric the semantic project exposes.row_filtersstill apply at execute time, so row-scoped restrictions hold; metric-scoped restrictions do not. A near-term release will foldAllowMetricsinto both surfaces so the planner cannot ground a metric the caller could not query directly.
POST /api/ask
Second-person walk-through: post the question, read the response, render the chart.
curl -sS -X POST https://your-goni-host/api/ask \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $GONI_PAT" \
-d '{"question": "Show me weekly ARR by country", "conversation_id": "demo-1"}'
Request shape:
{
"question": "Show me weekly ARR by country",
"conversation_id": "demo-1"
}
conversation_id is optional; when present, the store is keyed by (authenticated_user, conversation_id) so follow-ups like “by plan” or “now monthly” resolve against the prior turn without exposing another user’s history.
/api/ai/chat (the persona-scoped surface documented on Persona playbooks) accepts the same conversation_id and resolves against the same store: a client can start a turn on /api/ask and continue it on /api/ai/chat with the same id, because both endpoints share a single per-process conversation store.
Merge rules when a follow-up turn resolves against the prior plan:
- metric - inherited if the new question did not ground one on its own.
- time_grain - inherited if the new question did not name one.
- dimensions - REPLACE (not stack): a “by plan” follow-up on a prior “by country” plan swaps
countryout forplan. Only inherits when the new question produced no dimensions at all. - filters - union with new-wins on key conflict: a fresh
country=LToverrides the priorcountry=PL; a newplan=enterpriseis added alongside a carried-over country filter.
The merge is conservative on purpose: a false-positive follow-up detection only loses a fresh-start, never silently stacks an unwanted dimension on top of a previous slice.
Response shape:
{
"question": "Show me weekly ARR by country",
"status": "ok",
"plan": {
"metric": "active_arr",
"dimensions": ["country"],
"time_grain": "week",
"limit": 500
},
"sql": "SELECT toStartOfWeek(order_ts) AS week, country, sum(mrr)*12 AS active_arr FROM marts_semantic.fct_subscriptions WHERE status='active' GROUP BY week, country ORDER BY week LIMIT 500",
"chart_kind": "line",
"columns": [
{"name": "week", "type": "Date"},
{"name": "country", "type": "String"},
{"name": "active_arr", "type": "Float64"}
],
"rows": [
{"week": "2026-01-06", "country": "LT", "active_arr": 41200.00},
{"week": "2026-01-06", "country": "PL", "active_arr": 28800.00}
],
"conversation_id": "demo-1"
}
status is one of ok, clarify, diagnostic, error. Only error returns HTTP 5xx so uptime probes see real backend outages; clarify (planner did not ground the question) stays 200 with catalog populated for the UI to render the “here is what you can ask” surface.
Note:
/api/askrequires authentication. The body is capped at 64 KiB, and anonymous callers get 401 - not a planner run.
Grounding fields on the Ask response
Every /api/ask and /api/ai/chat response can carry a glossary_terms array alongside the plan and rows. These are the approved business glossary terms the server judged relevant to the question plus the resolved plan, and they are stapled into the LLM’s system prompt BEFORE the planner runs so the model is required to use your workspace’s definitions rather than guessing.
{
"status": "ok",
"plan": { "metric": "active_arr", "dimensions": ["country"], "time_grain": "week" },
"glossary_terms": [
{
"id": "active-arr",
"name": "Active ARR",
"definition_md": "Annualised recurring revenue for subscriptions in the `active` state. Excludes trials, past-due, and churned rows. Sums `mrr_eur * 12` on `fct_subscriptions`.",
"status": "approved",
"synonyms": ["ARR", "annualised recurring revenue"],
"domain": "finance",
"owners": ["finance-lead@example.com"],
"workspace_id": "finance"
}
]
}
Behaviour to rely on:
- Approved-only. Draft,
review, anddeprecatedterms are filtered out server-side. A private work-in-progress definition can never surface in an AI answer. - Ranked, not exhaustive. Terms are scored on whole-word matches against the question, the grounded metric name, and each grounded dimension (name, synonyms, and a smaller definition bonus). The default cap is 3 terms per response; the server oversamples 3x and post-filters by workspace ACL so callers with limited access still get up to the cap.
- Same shape as the term endpoints. Each element is a full
GlossaryTerm(id,name,definition_md,status,synonyms,related_terms,domain,owners,reviewers,tags,external_url,workspace_id,updated_at,author), so a client can render the terms in a drawer without re-fetching. See Business glossary - Term shape. - Absent when nothing matched. The field is omitted from the JSON response, not sent as an empty array. Treat
!response.glossary_terms || response.glossary_terms.length === 0as “no grounded definitions were surfaced”. - Rendered by the SPA under the chart. The Goni web app shows the term names as clickable chips beneath the answer so an analyst can expand the authoritative definition inline. Embedded / API-only callers can render them however they like.
This is the same primitive the Business glossary - Grounding: Ask reads approved terms section describes from the glossary side.
GET /api/ask/catalog
Inspect what the AI planner sees for this tenant. Useful when a customer says “why won’t it answer that?” - the catalog either lists the metric or does not.
Current limitation. As of today, this endpoint returns the full compiled project catalog to any authenticated caller regardless of their per-metric policy. In a near-term release the response will be filtered by the caller’s
AllowMetricsso it matches what the planner is willing to ground. Until then, do not treat the catalog response as a per-user ACL projection.
curl -sS https://your-goni-host/api/ask/catalog -H "Authorization: Bearer $GONI_PAT"
Response:
{
"metrics": {
"active_arr": {
"label": "Active ARR",
"entities": ["country", "plan", "plan_tier"],
"grain": "day"
},
"active_customers": { "label": "Active customers", "entities": ["plan", "country"] }
}
}
Everything the planner can produce comes from this document. If a metric is not here, no question can reach it.
POST /api/ask/eval
The regression harness runs the bundled YAML suite against the live grounded planner. It is admin-only because each prompt fans out a warehouse query.
curl -sS -X POST https://your-goni-host/api/ask/eval -H "Authorization: Bearer $GONI_PAT"
The suite ships inside bi-api. To run your own, point GONI_AI_EVAL_PATH at a file of the same shape (ai_eval.yml), which has two sections:
faithfulness:
- q: "weekly arr by country"
metric: active_arr
dims: [country]
grain: week
hallucination:
- q: "average tenure in years by region"
must_clarify: true
faithfulness requires status=ok and the plan to match the expected metric, dims, and grain. hallucination prompts must refuse (status=clarify or error). The response returns per-row pass/fail plus summary.faithfulness.rate and summary.hallucination.refusal_rate.
Plan-then-execute loop
Every question follows the same two stages:
- Plan. The provider maps NL to a
Plangrounded in the catalog. Temperature defaults to0.2because plan-then-execute wants consistency, not creativity. Prior conversation turns are carried so “by plan” resolves against the last question. Playbook context (see Persona playbooks) can be injected as a system-prompt augmentation. - Execute. Goni compiles the plan to ClickHouse SQL through the semantic layer, runs it under the caller’s row_filters, and returns rows plus the chart kind to render.
The rules backend is deterministic and zero-cost. It handles common cases ("weekly arr by country", "active customers by plan") using a synonym map. Providers escalate from there.
Save-as: auto-persist a chart / tile / alert
/api/ai/chat accepts a save_as field on any request. It lets a client convert a good answer into a real Goni artifact (chart, dashboard tile, alert) without leaving the chat surface. The dry-run default is deliberate: the SPA reads the preview shape, renders a “Save this as …” confirmation banner, and only sends the confirmed re-issue when the user clicks through.
Contract:
{
"question": "Weekly ARR by country",
"playbook_id": "data-analyst",
"conversation_id": "demo-1",
"save_as": {
"kind": "chart",
"name": "Weekly ARR by country",
"chart_kind": "line",
"confirm": false
}
}
kind is one of chart | tile | alert. Per-kind required fields:
| Kind | Required | Optional |
|---|---|---|
| chart | name | chart_kind (default bar) |
| tile | dashboard_id | name, chart_kind (default bar) |
| alert | name, threshold, operator | alert_type (default threshold), frequency (default 5m) |
With confirm: false (default) the server returns a save preview and writes NOTHING:
{
"status": "ok",
"metric": "active_arr",
"save": {
"kind": "chart",
"confirmed": false,
"artifact_id": "weekly-arr-by-country",
"name": "Weekly ARR by country",
"chart_kind": "line",
"payload": {
"metric": "active_arr",
"dimensions": ["country"],
"time_grain": "week",
"limit": 500
},
"message": "Preview: would save chart \"Weekly ARR by country\" (weekly-arr-by-country) rendered as a line chart. Reply with save_as.confirm=true to persist."
}
}
With confirm: true the same request writes through the same chart, dashboard, and alert save paths a human PUT would hit. RBAC (allow_save), validation, and git-commit history stay identical between AI-created and human-created artifacts. The audit row stamps origin=ai:<playbook> (see Audit and lineage) so ops can tell a persona-initiated save apart from a manual click.
Alert kinds: only threshold is wired today. change and anomaly need windowed context that a single plan does not carry; they return a 400 with a hint pointing at the manual alert editor.
Guards on the save path:
- No metric grounded (planner returned clarify) means the save is silently dropped; the client is not blocked on two errors at once (“unsupported question” AND “unsupported save”).
- No
allow_saverole bit returns 403 with the same message the alert / chart PUT handlers use. - A missing dashboard on
kind=tilereturns 404; the client should surface the dashboard picker. - A save that fails validation writes an
ai_chat.save.failedaudit row before returning 400, so ops can trace “user tried to save X, denied because Y”.
Cross-persona handoff
When the data-analyst persona hits a question outside its charter (a request that needs a new pipeline, a new metric definition, or a causal drill) its playbook trains it to name the target persona in the refusal explanation. The server scans that explanation and, when it recognises a persona name, returns a handoff field on the response. The SPA renders it as a routing banner instead of a dead-end “I can’t answer that” screen.
Detection is a case-insensitive substring check on data-engineer, data-architect, and diagnostic playbook / diagnostic persona. Precedence when the explanation names more than one: engineer wins because it is the only persona for which the server can auto-mint a concrete proposal today.
Wire shape:
{
"status": "clarify",
"playbook_id": "data-analyst",
"explanation": "This question needs a table we haven't loaded yet. Route the request to the data-engineer playbook so a pipeline can be proposed.",
"handoff": {
"to_persona": "data-engineer",
"suggested_action": "The analyst refused: the question needs a pipeline or model the semantic layer does not yet expose. The data-engineer persona can propose the pipeline to load the missing source table.",
"proposal_id": "prop_01HXYZ..."
}
}
Engineer handoffs auto-mint a stub propose_pipeline Proposal. The stub is intentionally incomplete (the analyst does not know the source-database topology) - it carries the user’s question, the analyst’s refusal, and a note telling the engineer to fill in connection_id, source_table, target_table, mode, and inc_column before applying. origin on the proposal is ai:data-analyst, attributing the handoff to the persona that initiated it. Failure to create the stub is best-effort: the routing hint still ships without proposal_id.
Architect and diagnostic handoffs are advisory only - the banner routes the user to the right persona, but no proposal is auto-created. A single conversation can continue across the handoff because conversation_id is preserved on the response.
Example flow: a user asks “sessions per user last week” against a semantic project that has no sessions metric. The analyst refuses with an explanation naming data-architect; the response carries handoff.to_persona="data-architect"; the SPA renders “This question needs the data-architect persona; reopen the chat to propose the metric definition.” When the user reopens with the architect persona, create_metric (see MCP server) is available.
Diagnostic: why did X change?
The diagnostic playbook is a fourth persona shipped for causal drills. Its charter is deliberately narrow: pick the metric and the optional filter scope, but do NOT compute the deltas. The server does the fan-out. The reason is grounding: a weaker model computing “ARR fell 12% because DE fell 31%” from raw rows will hallucinate the numbers; a server that runs one ClickHouse query per entity value cannot.
The dispatcher fires when playbook_id="diagnostic" and the LLM’s plan grounded a metric. The base plan is forced to dimensions=nil (the persona’s contract says so, but a mis-behaving model might still emit one). The server then fans out one query per declared entity on the metric, compares current vs prior period per entity value, ranks by absolute delta, and returns the top-3 as hypotheses on a new diagnostic response field.
Example - “why did active_arr drop last week?”:
{
"question": "why did active_arr drop last week?",
"playbook_id": "diagnostic",
"status": "ok",
"metric": "active_arr",
"time_grain": "week",
"diagnostic": {
"metric": "active_arr",
"window_description": "last week vs prior week",
"overall_delta_pct": -12.4,
"hypotheses": [
{"dimension": "country", "value": "DE", "current": 42100, "prior": 61200, "delta_pct": -31.2, "plan": {"metric": "active_arr", "filters": {"country": "DE"}}},
{"dimension": "plan", "value": "enterprise", "current": 88400, "prior": 108300, "delta_pct": -18.4, "plan": {"metric": "active_arr", "filters": {"plan": "enterprise"}}},
{"dimension": "country", "value": "PL", "current": 24500, "prior": 27100, "delta_pct": -9.6, "plan": {"metric": "active_arr", "filters": {"country": "PL"}}}
]
}
}
Each hypothesis carries its own plan so the SPA can render a “click to drill into DE” chip: the plan is a reproducible metric query the caller can execute against /api/metric/{name}/query.
RBAC is preserved. The diagnose fan-out runs each per-entity split query with the caller’s row-level filter applied - the same filter /api/metric/{name}/query uses - so a diagnostic drill cannot expose data the caller would not see through the normal chart surface.
Insufficient history (fewer than 2 time buckets in the warehouse) is not fatal: the diagnose failure prepends its error to explanation (“Diagnostic failed: need at least 2 time buckets to compare | Base plan: …”) and the LLM’s grounded plan is still returned, so the client can render “why? - not enough history yet” without a full error state.
LLM providers and BYOK
Four LLM providers are supported for BYOK: anthropic, openai, mistral, ollama. The rules backend is a zero-cost deterministic planner (no LLM) and needs no configuration. Provider configuration is per-tenant, BYOK - Goni never proxies through a shared key in production, and the production boot guard refuses to start with dev secrets when GONI_DEV_MODE=0.
Configure:
curl -sS -X PATCH https://your-goni-host/api/settings/ai \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $GONI_PAT" \
-d '{
"provider": "anthropic",
"api_key": "sk-ant-...",
"model": "claude-opus-4-7",
"endpoint": ""
}'
Notes on this endpoint:
- Requires
allow_save. - The API key is AES-256-GCM encrypted at rest. Reads (
GET /api/settings/ai) never return the key - only{configured, provider, model, endpoint, configured_at, configured_by}. - Endpoints are SSRF-guarded for cloud providers. Self-hosted Ollama on
127.0.0.1:11434is allowed via a loopback exception. DELETE /api/settings/aireverts the tenant to the rules-only planner (no LLM dispatch).
Per-tenant hourly token budget
Goni throttles LLM spend per tenant with a sliding one-hour window backed by Redis. Unit is tokens, not questions, because an 8k-context prompt costs 80x a one-liner.
| Plan | Hourly token limit | Approx questions/hr |
|---|---|---|
starter | 200,000 | ~100 mid-size |
growth | 1,000,000 | ~500 |
scale | 5,000,000 | ~2,500 |
enterprise | unlimited | - |
Peek headroom without spending:
curl -sS https://your-goni-host/api/ai/budget -H "Authorization: Bearer $GONI_PAT"
{
"configured": true,
"plan": "growth",
"limit_tokens": 1000000,
"remaining_tokens": 998720,
"reset_in_seconds": 0,
"exhausted": false
}
The Goni app shell renders remaining_tokens / limit_tokens as a chip next to the AI badge. When exhausted: true, /api/ask returns 429 with Retry-After: reset_in_seconds. Redis outages degrade open so a cache hiccup does not hard-deny a real question.
End-to-end example
Question: "Show me weekly ARR by country".
Grounded plan:
{ "metric": "active_arr", "dimensions": ["country"], "time_grain": "week", "limit": 500 }
Compiled SQL (rendered from the metric definition, not written by the LLM):
SELECT toStartOfWeek(order_ts) AS week,
country,
sum(mrr) * 12 AS active_arr
FROM marts_semantic.fct_subscriptions
WHERE status = 'active'
GROUP BY week, country
ORDER BY week
LIMIT 500
Chart kind: line. The Goni web app renders one series per country, plus the plan and SQL echoed under the chart so the user can verify what Goni actually ran. Any answer can be pinned to a dashboard with the “Save as tile” button on the response.
Related
- Semantic layer overview - what makes grounding possible
- Metrics - the shape of
active_arrand friends - Persona playbooks - the four personas (analyst / engineer / architect / diagnostic) and their
/api/ai/chatcontract - MCP server - the tool-calling surface for external agents
- Proposals - the propose / preview / apply flow the handoff and MCP write tools mint into
- Scheduled tasks - recurring
/api/ai/chatruns with Slack delivery - Access control - row_filters and metric ACLs the planner honours
- Environment variables - the
GONI_*set used by AI Q&A
Last updated