UI

Query data

Natural-language analytics card that streams syntax-tinted SQL into a collapsible copyable panel, runs queries with a rolling rows-scanned counter, and renders interactive Bar, Line, and Table views with a streamed insight.

import { AskYourData } from '@uthereal/ui/ask-your-data'

Ask your data playground

Generated SQLPostgreSQL · analyticsanalytics
Ask in plain wordsAnswers are charted from a read only query on analytics
Loading interactive preview…

Overview

AskYourData turns plain-language questions into SQL and interactive charts inside one self-contained card. Readers submit a question against a labelled database source (or pick a starter suggestion). The model’s query streams into a collapsible, line-numbered Generated SQL panel with syntax tints and a one-click Copy SQL button. As the query executes, a rolling counter tracks rows scanned while a breathing skeleton reserves the chart height. Once data lands, the stage reveals a Bar, Line, or Table view with hover and keyboard crosshair readouts and streams a one-line analytical insight underneath.

Use AskYourData for self-serve BI panels, warehouse copilots, and precomputed metric cards that let readers inspect the underlying SQL. For static multi-series charts without a question bar or SQL drawer, use Bar chart or Line chart.

Usage

'use client'
import { AskYourData } from '@uthereal/ui/ask-your-data'

export function AnalyticsCopilot() {
  return (
    <AskYourData
      source={{ name: 'warehouse', dialect: 'PostgreSQL' }}
      generateSql={async (question, { signal, source }) => {
        const res = await fetch('/api/sql', {
          method: 'POST',
          signal,
          body: JSON.stringify({ question, source }),
        })
        if (!res.ok) throw new Error('Could not generate SQL')
        return (await res.json()).sql
      }}
      runQuery={async (sql, { signal, onProgress }) => {
        const res = await fetch('/api/query', {
          method: 'POST',
          signal,
          body: JSON.stringify({ sql }),
        })
        if (!res.ok) throw new Error(await res.text())
        const data = await res.json()
        onProgress(data.rowsScanned, data.rowsScanned)
        return data.result
      }}
      onResult={(result, { sql }) => {
        console.log('Charted', result.title, sql)
      }}
    />
  )
}

Omit generateSql and runQuery to run the deterministic local simulation (covering signups, revenue, and churn questions with zero network requests). Always execute runQuery on a read-only database role on your backend.

Examples

Precomputed line chart with open SQL

Pass initialResult alongside initialSql and keepSqlOpen={true} to render an already-answered query immediately with its syntax-tinted PostgreSQL panel expanded and ready to copy.

Generated SQLPostgreSQL · 21 rows · 184ms21 rows
SELECT
  date_trunc('week', created_at)::date AS week,
  plan,
  COUNT(*) AS signups
FROM workspaces
WHERE created_at >= DATE '2026-09-07'
GROUP BY 1, 2
ORDER BY 1, 2;
Weekly signups by planSep 7 – Oct 19, 2026 · 4,820 total
Chart type
Chart type
  • Starter2,595
  • Pro1,728
  • Enterprise457

Pro and Enterprise signups accelerated 72% over the six-week window, lifting total weekly volume from 537 to 851.

Non-stacked rate table on a custom warehouse

Set stacked={false} and chart="table" for rates or percentages that should not sum across series, paired with a custom source (billing_dw on Snowflake).

Generated SQLSnowflake · 18 rows · 312ms18 rows
SELECT
  TO_CHAR(month_start, 'Mon') AS month,
  segment,
  ROUND(100.0 * churned_logos / NULLIF(active_logos, 0), 2) AS churn_pct
FROM billing_dw.monthly_logo_retention
WHERE month_start >= '2026-05-01'
ORDER BY month_start, segment;
Monthly logo churn rate (%)May – Oct 2026 · billing_dw (Snowflake)
Chart type
Chart type
  • Starter %3.6
  • Growth %1.7
  • Enterprise %0.3
MonthStarter %Growth %Enterprise %
May4.82.40.6
Jun4.52.20.5
Jul4.32.10.5
Aug4.11.90.4
Sep3.91.80.4
Oct3.61.70.3

Churn improved across every segment since May, with Starter dropping 1.2 points to 3.6% and Enterprise holding at 0.3%.

Query lifecycle and views

Execution stages

StageHeader & SQL panelCancellation & recovery
IdlePrompts the reader with up to six clickable suggestions.Submitting a non-empty question starts the pipeline.
WritingExpands Generated SQL automatically and streams syntax-tinted tokens (4 tokens per 34ms).Pressing Stop or Escape aborts generateSql and keeps only arrived SQL.
RunningFolds SQL (unless keepSqlOpen or toggled by the reader) and displays a rolling rows-scanned count.Pressing Stop or Escape aborts runQuery and offers Run again.
DoneDraws the chart (bar, line, or table), updates SQL meta with row count and timing, and streams insight.Reader can switch views, inspect points, copy SQL, or ask a follow-up.
ErrorShows the SQL or database failure reason (plus monospace detail for query errors).Offers Try again or starter suggestions for unmatched questions.

Chart views

ViewBehavior
BarDraws stacked bars when stacked is true (default) or grouped bars when false; dims non-hovered columns on inspect.
LineTraces one smooth stroked path per series with focus markers at the active category.
TableRenders a sticky-header scrollable table with tabular numerals and a Total column when stacked is true.

API reference

These serializable arguments and defaults come directly from the component schema.

ArgumentType / defaultDescription
defaultQuestionstringDefault: "Weekly signups by plan since August"Starting question when uncontrolled. Edits do not reset a mounted instance.
placeholderstringDefault: "Ask a question about your data"Placeholder for the empty question field.
sourceAskYourDataSourceDefault: {"name":"analytics","dialect":"PostgreSQL"}The database the question runs against: its name and dialect. Defaults to analytics on PostgreSQL.
suggestionsstring[]Default: ["Weekly signups by plan since August","Monthly recurring revenue by region in 2026","Monthly churn rate by plan since May"]Questions offered in the empty state. Defaults to three samples; pass an empty array to hide them.
defaultChartbar | line | tableDefault: "bar"View for results that do not name their own chart. Defaults to bar.
keepSqlOpenbooleanDefault: falseKeep the SQL panel open after the query starts instead of folding it away. Once someone opens or closes the panel, their choice wins.
autoRunbooleanDefault: falseAsk the starting question once the card scrolls into view. On by default without generateSql; never over an initialResult.
initialResultAskYourDataResult—Precomputed result rendered immediately, without streaming or running. Pair with initialSql to show the query beside it.
initialSqlstring—SQL shown beside an initialResult, already complete and copyable.
askActionstring—Registered host action requested when Ask is pressed. The question itself travels through the React-only generateSql and runQuery callbacks.
localestring—BCP 47 locale for number formatting. Inherited from the page when omitted.
recipestudio | softDefault: "studio"Visual treatment. Both recipes preserve interaction behavior.
themeAskYourDataThemeDefault: {}Color mode, accent, and typed semantic token overrides.
motionnone | subtle | expressiveDefault: "subtle"Animation preset. System reduced-motion preferences take precedence.
motionOptionsAskYourDataMotionOptionsDefault: {}SQL stream pacing, header crossfades, and chart draw timing in milliseconds.
dirltr | rtl—Reading direction; inherited from the page when omitted.
  • AskYourDataSource accepts { name, dialect }.
  • AskYourDataResult accepts { title, subtitle?, categories, series, stacked?, legendValue?, chart?, categoryLabel?, insight?, rowCount?, durationMs? }, where each AskYourDataSeries is { id, label, values, color? } with unique IDs and values.length <= categories.length (up to 8 series).

React integration

PropPurpose
question / onQuestionChangeControlled question text and change callback.
chart / onChartChangeControlled view ("bar" | "line" | "table") and view-change callback.
generateSql(question, context)Returns SQL as a string (paced locally) or AsyncIterable<string> (streamed live). Honor context.signal.
runQuery(sql, context)Executes read-only SQL, calls context.onProgress(rowsScanned, totalRows?), and resolves with an AskYourDataResult.
onResult(result, { question, sql })Fires once a query resolves and is charted.
onError(error, { question, stage })Fires when generateSql ("sql") or runQuery ("query") throws a non-abort error.
onAction(action, itemId?)Called with askAction when the reader submits a question or picks a suggestion.
formatValue(value)Formats numeric values across Y-axis ticks, hover tooltips, legend summaries, and table cells.
renderSourceMark()Replaces the default 16px cylinder mark in the question bar and SQL panel header. Keep returned elements decorative.
presetApplication defaults overridden by explicit instance arguments.
tokensCSS variables applied after the typed theme, forwarded to the root card, buttons, and view switcher.
ref, className, styleApplied to the root <section> element.
Native attributesid, aria-*, data-*, and remaining <section> props forwarded to the root element.

Keyboard & accessibility

KeyAction
Enter (in question)Submits the question or stops an in-flight run.
Escape (in question)Aborts SQL streaming or query execution while busy.
ArrowLeft / ArrowRightSteps across categories on the focused Bar or Line chart to inspect values (respects RTL).
Home / EndJumps chart inspection to the first or last category.
Escape (on chart)Clears the active chart crosshair readout.
TabMoves across the question input, Ask/Stop button, SQL toggle, Copy SQL, SQL code block, view switch, and chart/table.
  • The plot region (tabIndex={0}, role="group") pairs its floating tooltip with a polite live region reading every series value and total for the focused category.
  • The SQL panel header uses an explicit aria-expanded / aria-controls disclosure button while keeping Copy SQL stacked cleanly above it as an independent focusable control.
  • Container queries adapt the card below 520px, shortening the SQL metadata pill, moving the view switcher inline below the heading, and compacting chart and table spacing. @media (forced-colors: active) maps borders, series dots, and hover bands to system colors.

Motion & theming

The SQL panel expands and collapses on the smooth spring (0.4s, bounce 0), bars rise with a short stagger (320ms), lines trace across the plot (460ms), and the analytical insight streams word-by-word inside a height-reserved band so nothing shifts.

Under prefers-reduced-motion: reduce, SQL and insights land whole, bar rises and line draws become immediate, the breathing skeleton stops, and the spinner slows to 1.6s. Setting motion="none" makes every swap immediate (0ms) and stops all spinner and skeleton animations.

theme accepts mode, accent, and typed tokens across these groups:

Token groupCSS custom properties
core--ui-surface, --ui-surface-raised, --ui-text, --ui-text-secondary, --ui-muted, --ui-border, --ui-highlight, --ui-accent, --ui-accent-foreground, --ui-danger, --ui-focus-ring, --ui-radius, --ui-border-width, --ui-shadow, --ui-disabled-opacity, --ui-font, --ui-font-size, --ui-font-weight
extended--ui-surface-sunken, --ui-border-strong, --ui-border-subtle, --ui-track, --ui-info, --ui-success, --ui-warning, --ui-tone-foreground, --ui-overlay, --ui-tint-strength
chart--ui-series-1 through --ui-series-8, --ui-series-other, --ui-sequential-1..7, --ui-diverging-1..7
shape--ui-radius-sm, --ui-popup-radius, --ui-surface-radius
type--ui-font-mono, --ui-font-display
elevation--ui-shadow-resting, --ui-shadow-raised
include--ui-accent-strong, --ui-accent-subtle, --ui-tone-foreground

An application-wide UtherealProvider supplies defaults.

Composition

In an agent composition, AskYourData is a leaf block. Provide source, starter suggestions, or a precomputed initialResult and initialSql, and wire askAction to a registered host action. See Building with agents.

{
  "type": "AskYourData",
  "props": {
    "source": { "name": "analytics", "dialect": "PostgreSQL" },
    "defaultQuestion": "Weekly signups by plan since August",
    "defaultChart": "bar",
    "keepSqlOpen": false,
    "askAction": "ask_warehouse"
  },
  "children": []
}

On this page