<!--# if expr="$arg_server = /^(node|python|go|php|ruby|dotnet)$/" --><!--# set var="stack_server" value="$arg_server" --><!--# else --><!--# set var="stack_server" value="node" --><!--# endif --><!--# if expr="$arg_database = /^(postgresql|redshift|mysql|mssql|clickhouse|snowflake|bigquery|databricks)$/" --><!--# set var="stack_database" value="$arg_database" --><!--# else --><!--# set var="stack_database" value="postgresql" --><!--# endif --><!--# if expr="$arg_cache = /^(none|duckdb|redis)$/" --><!--# set var="stack_cache" value="$arg_cache" --><!--# else --><!--# set var="stack_cache" value="none" --><!--# endif --><!--# if expr="$arg_model = /^(jev|clef|openai|perplexity)$/" --><!--# set var="stack_model" value="$arg_model" --><!--# else --><!--# set var="stack_model" value="jev" --><!--# endif -->
# Generative UI (Jev)

A chat whose question fills a report form as it is typed.

> The code on this page is for the stack in its URL's query, by default `?server=node&model=jev&database=postgresql&cache=none`. Server: `node`, `python`, `go`, `php`, `ruby`, `dotnet`. Model: `jev`, `clef`, `openai`, `perplexity`. Database: `postgresql`, `redshift`, `mysql`, `mssql`, `clickhouse`, `snowflake`, `bigquery`, `databricks`. Cache: `none`, `duckdb` (`node` only), `redis`. A missing or unknown value is the default, the first listed.

[Open the demo](https://quill.co/docs-demo/blocks/#/adaptive-ui)

`AdaptiveUiBlock.tsx`

```tsx
import { Fragment, useEffect, useMemo, useRef, useState } from 'react';
import { Chart, useReport, useTableFilterEditor, useVirtualTables, type SetReportBuilderInput } from '@quillsql/react';
import { ArrowUp, LoaderCircle } from 'lucide-react';
import { MotionConfig } from 'motion/react';
import { Button } from '../components/button/button';
import { MultiSelect, Select } from '../components/filter-builder/filter-builder';
import { FilterSentence } from './FilterSentence';
import { askJev } from './jev';
import { applyBuilderRules, capitalize, draftOptions, draftQuestions, fieldLabel, sourceQuestions, type Draft, type SchemaTable } from './reportDraft';
import styles from './ReportBuilder.module.css';
import css from './AdaptiveUiBlock.module.css';

/** Jev is asked once typing pauses this long, and only about a message this long. */
const TYPING_DEBOUNCE_MS = 250;
const MIN_TEXT_LENGTH = 12;
/** Questions that type themselves when clicked, a phrase at a time, so each part of the form fills as it is read. */
const SUGGESTIONS = [
  ['Transaction revenue', ' by month', ' and plan', ' in the last 6 months'],
  ['Visitors', ' by week', ' and by device', ' in the last 90 days'],
  ['Average MRR', ' of Pro and Enterprise accounts', ' by status'],
];
const CHAR_MS = 28;
const PHRASE_PAUSE_MS = 1400;

/**
 * The report a message asks for, read by Jev from the schema alone, landing as one update per read: request one once
 * typing pauses (is it a report, from which table, as which chart), then request two once that table's fields and text
 * values are in (everything else, filters on values the message names, such as "Pro", included). The last read stays
 * up while the next is on its way. Edits to the draft keep the builder's rules; the next read replaces them.
 */
export function useJevDraft(text: string, endpoint: string) {
  const tables = useVirtualTables().data as SchemaTable[];
  const [asked, setAsked] = useState('');
  const [source, setSource] = useState<{ text: string; table: string; chartType?: string } | null>(null);
  const [draft, setDraft] = useState<Draft | null>(null);
  /** The request-one read the draft answers, so the read counts as underway until its draft lands. */
  const [readFor, setReadFor] = useState<typeof source>(null);
  const [pending, setPending] = useState(0);
  const [error, setError] = useState('');
  const track = (request: Promise<unknown>) => {
    setPending((count) => count + 1);
    request
      .then(() => setError(''), (err: Error) => err.name !== 'AbortError' && setError(err.message))
      .finally(() => setPending((count) => count - 1));
  };

  useEffect(() => {
    const next = text.trim();
    if (next && next.length < MIN_TEXT_LENGTH) return;
    const timer = setTimeout(() => setAsked(next), next ? TYPING_DEBOUNCE_MS : 0);
    return () => clearTimeout(timer);
  }, [text]);

  useEffect(() => {
    if (!asked) {
      setSource(null);
      return;
    }
    if (!tables.length) return;
    const controller = new AbortController();
    const plan = sourceQuestions(tables);
    track(askJev(endpoint, asked, plan.questions, controller.signal).then((answers) => {
      const read = plan.read(answers, asked);
      // A message that is not (yet) a report keeps the draft it extends while it is typed on, and drops it once rewritten.
      setSource((current) => (read ? { ...read, text: asked } : current && asked.startsWith(current.text) ? current : null));
    }));
    return () => controller.abort();
  }, [asked, tables, endpoint]);
  useEffect(() => {
    if (!source) setDraft(null);
  }, [source]);

  const table = useMemo(() => tables.filter(({ name }) => name === source?.table), [tables, source?.table]);
  const { props: filterProps, uniqueValuesLoading } = useTableFilterEditor(table as never);
  const fields = useRef(filterProps.fields);
  fields.current = filterProps.fields;
  const fieldsReady = table.length > 0 && filterProps.fields.length > 0 && !uniqueValuesLoading;
  useEffect(() => {
    if (!source || !fieldsReady) return;
    const controller = new AbortController();
    const plan = draftQuestions({ text: source.text, table: table[0], fields: fields.current, chartType: source.chartType });
    track(askJev(endpoint, source.text, plan.questions, controller.signal).then((answers) => {
      setDraft(plan.read(answers));
      setReadFor(source);
    }));
    return () => controller.abort();
  }, [source, fieldsReady, endpoint]);

  const edit = (patch: Partial<Draft>) => setDraft((current) => {
    const next = tables.find(({ name }) => name === (patch.table ?? current?.table));
    return current && next ? applyBuilderRules({ ...current, ...patch }, next) : current;
  });
  return { tables, draft: source ? draft : null, edit, filterProps, reading: pending > 0 || (!!source && readFor !== source), error };
}

/**
 * The report Jev reads from the message, as a form on the input like an autocomplete: each part shows once Jev is sure
 * of it and can be changed, and nothing is queried until Create report.
 */
function DraftForm({ jev }: { jev: ReturnType<typeof useJevDraft> }) {
  const { tables, edit, filterProps } = jev;
  const draft = jev.draft!;
  const options = draftOptions(draft, tables);

  return (
    <div className={`${styles.root} ${css.draft}`} aria-label="Report form">
      {/* Always shown, so a filter Jev did not read can be added before the report is created. */}
      <FilterSentence filters={draft.filters ?? { rules: [] }} queryBuilderProps={filterProps} labelOf={fieldLabel}
        onChange={(next) => typeof next !== 'function' && edit({ filters: next as Draft['filters'] })} />
      <div className={css.draftRow}>
        <div className={styles.controls}>
          <Select className={styles.group} label="From" options={options.sources} value={draft.table} onChange={(table) => edit({ table })} />
          {draft.groupRowsBy && (
            <Select className={styles.group} label="Group by" options={options.groupRowsBy} value={draft.groupRowsBy} onChange={(groupRowsBy) => edit({ groupRowsBy })} />
          )}
          {draft.groupColumnsBy && (
            <Select className={styles.group} label="Segment by" options={[{ value: '', label: 'None' }, ...options.groupColumnsBy]} value={draft.groupColumnsBy}
              onChange={(groupColumnsBy) => edit({ groupColumnsBy })} />
          )}
          {!!draft.aggregations?.length && (draft.aggregations.length > 1
            ? <MultiSelect className={`${styles.group} ${styles.wide}`} label="Aggregate by" options={options.aggregations} value={draft.aggregations} onChange={(aggregations) => edit({ aggregations })} />
            : <Select className={styles.group} label="Aggregate by" options={options.aggregations} value={draft.aggregations[0]} onChange={(v) => edit({ aggregations: [v] })} />)}
          {draft.dateBucket !== undefined && options.dateBuckets.length > 0 && (
            <Select className={styles.group} label="Date bucket" options={options.dateBuckets} value={draft.dateBucket} onChange={(dateBucket) => edit({ dateBucket })} />
          )}
          {draft.chartType && (
            <Select className={styles.group} label="Chart" options={options.chartTypes} value={draft.chartType} onChange={(chartType) => edit({ chartType })} />
          )}
        </div>
        {/* Submits the composer's form: the message goes into the thread with this report. */}
        <Button size="sm" type="submit">Create report</Button>
      </div>
    </div>
  );
}

/**
 * A created report in the thread, from one useReport: the whole form in one setReport, whose table creates the report
 * with the rest already in it, shown as the Insight block shows a report, its legend whenever it is segmented.
 */
export function ReportMessage({ draft }: { draft: Draft }) {
  const report = useReport(undefined, { destinationDashboardName: 'Metric explorer', showTableNames: false });
  const { reportId, datasources, setReport, setFilters } = report;
  // useReport takes a table once it has the schema, and clears its form when it mounts, so the form goes in again until
  // useReport holds it (then the report is created).
  const schemaReady = report.datasourceOptions.length > 0;
  useEffect(() => {
    if (!schemaReady || reportId || datasources.length) return;
    setReport({
      datasources: [draft.table],
      groupRowsBy: draft.groupRowsBy ?? '',
      groupColumnsBy: draft.groupColumnsBy ?? '',
      aggregations: draft.aggregations ?? [],
      dateBucket: (draft.dateBucket ?? '') as SetReportBuilderInput['dateBucket'],
      chartType: (draft.chartType ?? 'table') as SetReportBuilderInput['chartType'],
      filters: draft.filters ?? { combinator: 'and', rules: [] },
    });
  }, [schemaReady, reportId, datasources.length]);
  // Jev's number format goes on its main measure once useReport lists the measures, which is once the report is created.
  // Setting the y-axis sets every measure, so the others keep their formats.
  const measureCount = report.yAxis.fields.length;
  useEffect(() => {
    if (!draft.yAxisFormat || !reportId || !measureCount) return;
    setReport({ yAxis: { fields: report.yAxis.fields.map(({ field, format }, index) => ({ field, format: index ? format : draft.yAxisFormat })) } });
  }, [reportId, measureCount]);
  const isTable = report.chartType === 'table';
  // The chart is the one part still to load, so it shows Quill's chart skeleton until its rows, as the Insight block does.
  const chartLoading = report.chartLoading || !reportId;

  // The form is known, so its controls show as they were in the form, as soon as useReport holds it (its first effect).
  if (datasources[0] !== draft.table) return null;
  return (
    <section className={styles.root} aria-label="Report">
      <FilterSentence filters={report.filters} queryBuilderProps={report.filterQueryBuilderProps} onChange={setFilters} />
      <div className={styles.controls}>
        <Select className={styles.group} label="Group by" options={report.groupRowsByOptions} value={report.groupRowsBy} onChange={(groupRowsBy) => setReport({ groupRowsBy })} />
        <Select className={styles.group} label="Segment by" options={[{ value: '', label: 'None' }, ...report.groupColumnsByOptions]} value={report.groupColumnsBy}
          onChange={(groupColumnsBy) => setReport({ groupColumnsBy })} />
        <Select className={styles.group} label="Aggregate by" options={report.aggregationOptions} value={report.aggregations[0]} onChange={(v) => setReport({ aggregations: [v] })} />
        <Select className={styles.group} label="Chart" options={report.chartTypeOptions.map(({ value }) => ({ value, label: capitalize(value) }))} value={report.chartType}
          onChange={(chartType) => setReport({ chartType: chartType as SetReportBuilderInput['chartType'] })} />
      </div>
      <Chart chart={report.chart} chartLoading={chartLoading} showLegend={!!report.groupColumnsBy}
        containerStyle={{ width: '100%', height: isTable && !chartLoading ? undefined : 240 }} />
    </section>
  );
}

/**
 * A chat whose question fills a report form while it is typed: Jev classifies the message into the parts of a report
 * (its table, groupings, measure, time bucket, filters and chart type), each shows in a form over the input as soon as
 * Jev is sure of it, and Create report (or Enter) sends the message with its report into the thread.
 */
export function AdaptiveUiBlock({ jevEndpoint }: { jevEndpoint: string }) {
  const [messages, setMessages] = useState<{ id: number; text: string; draft: Draft | null }[]>([]);
  const [prompt, setPrompt] = useState('');
  const jev = useJevDraft(prompt, jevEndpoint);

  const typing = useRef<ReturnType<typeof setTimeout>>(undefined);
  useEffect(() => () => clearTimeout(typing.current), []);
  const typeOut = (phrases: string[]) => {
    clearTimeout(typing.current);
    const text = phrases.join('');
    const pauses = new Set(phrases.map((_, i) => phrases.slice(0, i + 1).join('').length));
    const step = (at: number) => {
      setPrompt(text.slice(0, at));
      if (at < text.length) typing.current = setTimeout(() => step(at + 1), pauses.has(at) ? PHRASE_PAUSE_MS : CHAR_MS);
    };
    step(1);
  };
  const send = () => {
    const text = prompt.trim();
    if (!text) return;
    clearTimeout(typing.current);
    setMessages((list) => [...list, { id: list.length, text, draft: jev.draft }]);
    setPrompt('');
  };

  // The form sits on the input while there is a message and Jev has read a report (or failed to).
  const attached = !!prompt.trim() && (!!jev.error || !!jev.draft);

  // The thread stays on its newest message: resize callbacks run before paint, so new content shows already in place
  // instead of sliding up to it.
  const thread = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const element = thread.current;
    if (!element?.firstElementChild) return;
    const observer = new ResizeObserver(() => { element.scrollTop = element.scrollHeight; });
    observer.observe(element.firstElementChild);
    return () => observer.disconnect();
  }, []);

  return (
    <MotionConfig reducedMotion="user">
      <section className={css.chat} aria-label="Generative UI">
        <div ref={thread} className={css.thread}>
          <div className={css.messages} role="log" aria-live="polite" aria-label="Chat messages">
            <p className={css.assistant}>Hi, I'm the Acme reporting assistant.</p>
            {messages.map(({ id, text, draft }) => (
              <Fragment key={id}>
                <p className={css.user}>{text}</p>
                {draft ? <ReportMessage draft={draft} /> : (
                  <p className={css.assistant}>Ask for a measure, what to break it down by, or a time range, and a report form fills in as you type.</p>
                )}
              </Fragment>
            ))}
          </div>
        </div>
        <div className={css.composer}>
          <div className={css.suggestions}>
            {SUGGESTIONS.map((phrases) => (
              <button key={phrases[0]} type="button" className={css.suggestion} onClick={() => typeOut(phrases)}>
                {phrases.join('')}
              </button>
            ))}
          </div>
          <form className={css.form} data-attached={attached ? '' : undefined} onSubmit={(event) => { event.preventDefault(); send(); }}>
            {attached && (jev.error ? <p className={`${css.error} ${css.draft}`}>{jev.error}</p> : <DraftForm jev={jev} />)}
            <div className={css.field}>
              <textarea name="chat-prompt" aria-label="Ask Acme assistant" placeholder="Ask Acme about revenue, customers, or retention..." value={prompt}
                onChange={(event) => { clearTimeout(typing.current); setPrompt(event.target.value); }}
                onKeyDown={(event) => {
                  if (event.key !== 'Enter' || event.shiftKey || event.nativeEvent.isComposing) return;
                  event.preventDefault();
                  event.currentTarget.form?.requestSubmit();
                }} />
              <div className={css.fieldFoot}>
                {jev.reading && (
                  <span className={css.reading} role="status">
                    <LoaderCircle size={14} aria-hidden="true" />
                    Reading
                  </span>
                )}
                <button type="submit" className={css.send} aria-label="Send" disabled={!prompt.trim()}>
                  <ArrowUp aria-hidden="true" />
                </button>
              </div>
            </div>
          </form>
        </div>
      </section>
    </MotionConfig>
  );
}
```

`reportDraft.ts`

```ts
import { buildAggregationOptions, PIVOT_DATE_BUCKET_OPTIONS, type UseFormQueryBuilderField } from '@quillsql/react';
import type { RuleType } from 'react-querybuilder';
import { choice, yes, yesNo, type JevAnswers, type JevQuestion, type Option } from './jev';

/**
 * A report read from a chat message as it is typed, the way Quill's BI tool fills a report draft from its agent chat:
 * Jev picks among the report builder's own options, code finds the message's literal facts (its numbers, the values
 * it names), and a part fills only when Jev clears the bar for it. Two requests: which table (as soon as typing
 * pauses), then everything else about that table in one batch of parallel questions.
 */

type Column = { field: string; label?: string; jsType?: string; fieldType?: string };
export type SchemaTable = { name: string; displayName?: string; description?: string; columns: Column[] };

/** The parts of a report `useReport().setReport` takes, each one only when Jev was sure of it. */
export type Draft = {
  table: string;
  groupRowsBy?: string;
  groupColumnsBy?: string;
  aggregations?: string[];
  dateBucket?: string;
  chartType?: string;
  filters?: { combinator: 'and' | 'or'; rules: RuleType[] };
  /** The measures' number format, which `setReport` takes on the y-axis once the report lists its measures. */
  yAxisFormat?: string;
};

/** The message must be this likely a request for a report before anything shows. */
const INTENT_THRESHOLD = 0.8;
/** Table, grouping, measure, bucket and chart type fill above this: they show, and are one click to change. */
const FIELD_THRESHOLD = 0.75;
/** Filters fill only above this: a wrong filter silently hides data. */
const FILTER_THRESHOLD = 0.85;
/** Each aggregation besides the main measure is a yes/no. */
const AGGREGATION_THRESHOLD = 0.8;
/** The main measure needs this share of Jev's pick among the aggregations. */
const MEASURE_THRESHOLD = 0.5;
/** A trend ("over time") groups by a date above this. */
const OVER_TIME_THRESHOLD = 0.7;
/** With a rate as the measure, the text field it is about splits the groups with only this share. */
const RATE_SPLIT_SHARE = 0.5;
/** A period's date field, among several, is Jev's lead when it has this share. */
const PERIOD_FIELD_SHARE = 0.4;
/** A value the message writes out only needs Jev to agree it is a filter, so it clears lower bars. */
const LITERAL_VALUE_THRESHOLD = 0.6;
const LITERAL_FIELD_THRESHOLD = 0.7;
/** Similar columns split a grouping vote; one the message names ("by plan") wins with this share while "no grouping" stays under the max. */
const LITERAL_GROUP_SHARE = 0.3;
const LITERAL_GROUP_MAX_NONE = 0.2;
/** A table the message only implies is taken when it leads with this share, and this many times the next one's. */
const SOURCE_LEAD_SHARE = 0.45;
const SOURCE_LEAD_RATIO = 2;
/** Question sizes: columns describing a table, aggregations asked about, numbers per message, values per field and in all. */
const MAX_SOURCE_COLUMNS = 40;
const MAX_AGGREGATION_QUESTIONS = 25;
const MAX_NUMBERS = 6;
const MAX_VALUES_PER_FIELD = 40;
const MAX_VALUE_QUESTIONS = 160;
const MAX_MATCHED_VALUES = 12;
/** Date columns that are a row's own date, preferred when a trend names no date field. */
const MAIN_DATE = /^(date|day|created_at|created|timestamp)$|_date$|_at$/i;

const DATE_UNITS = ['hour', 'day', 'week', 'month', 'quarter', 'year'];
const NUMBER_COMPARISONS = [
  { operator: '>', phrase: 'greater than' },
  { operator: '>=', phrase: 'at least' },
  { operator: '<', phrase: 'less than' },
  { operator: '<=', phrase: 'at most' },
  { operator: '=', phrase: 'exactly' },
];

/** The report builder's chart types, and what each needs. */
const CHART_TYPES = ['column', 'stacked', 'stacked bar', 'line', 'area', 'radar', 'table', 'metric', 'gauge', 'bar', 'pie'];
const SINGLE_AGGREGATION_CHART_TYPES = ['stacked', 'stacked bar', 'bar', 'pie', 'gauge', 'metric'];
const NO_COLUMN_GROUPING_CHART_TYPES = ['bar', 'pie'];
const NO_ROW_GROUPING_CHART_TYPES = ['table', 'metric', 'gauge'];
/** A chart type the rest rules out becomes the nearest allowed one: a bar chart split by a second field is a stacked bar. */
const CHART_TYPE_FALLBACKS: Record<string, string[]> = {
  bar: ['stacked bar', 'column'],
  'stacked bar': ['bar', 'column'],
  column: ['stacked', 'line'],
  stacked: ['column', 'line'],
  pie: ['column', 'table'],
  metric: ['table'],
  gauge: ['table'],
};
/** The report builder's number formats for a measure. */
const NUMBER_FORMATS: Option[] = [
  { value: 'whole_number', label: 'a whole number, such as a count (1,234)' },
  { value: 'one_decimal_place', label: 'a number with one decimal place (12.3)' },
  { value: 'two_decimal_places', label: 'a number with two decimal places, such as a ratio or a score (1.23)' },
  { value: 'dollar_amount', label: 'money in whole dollars, such as revenue, sales or MRR ($1,234)' },
  { value: 'dollar_cents', label: 'money with cents, such as a price or a fee ($12.34)' },
  { value: 'percent', label: 'a percent or a rate (12.3%)' },
];

const KINDS: Option[] = [
  {
    value: 'report',
    label: 'Asks to see, show, list, chart, or summarize data, or asks a question the data answers (a count, total, average, rate, or percent), including rows joined across tables or filtered to a time range, such as "show revenue by month", "what is the escalation rate per team", "what % of calls are flagged as fraud", or "show me orders joined with customers from last week"',
  },
  {
    value: 'virtual-table',
    label: 'Asks to create, define, or save a new reusable virtual table, dataset, or view for later use, such as "create a virtual table of orders joined with customers" or "make a dataset of active users"',
  },
  {
    value: 'neither',
    label: 'Anything else: questions about the assistant or how to use it, greetings, dashboard or environment management, edits to existing items, or unclear requests',
  },
];

const titleCase = (value: string) => value.replace(/[_-]+/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase());
export const tableLabel = (table: SchemaTable) => (table.displayName && table.displayName !== table.name ? table.displayName : titleCase(table.name));
/** Lowercase, accents and apostrophes dropped, punctuation as spaces: "McDonald's" and "mcdonalds" read alike. */
const normalize = (value: string) =>
  value.normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/['’`]/g, '').replace(/[^a-z0-9]+/g, ' ').trim();
/** `id`, `account_id`, `userId`: never grouped or aggregated on, as in the report builder. */
const isId = (field: string) => /^id$|_id$/i.test(field) || field.endsWith('Id');
/** Rows group by dates and text; columns only by text. */
const canGroupRows = (column?: Column) => !!column && (column.jsType === 'date' || column.jsType === 'string') && !isId(column.field);
const canGroupColumns = (column?: Column) => !!column && column.jsType === 'string' && !isId(column.field);
/** Whether the message names one of `names` as a whole word, singular or plural ("transaction", "transactions"). */
const namesIn = (text: string, names: string[]) => {
  const words = ` ${normalize(text)} `;
  return names.some((raw) => {
    const name = normalize(raw);
    const singular = name.replace(/s$/, '');
    return name.length >= 2 && [name, singular, `${singular}s`].some((form) => words.includes(` ${form} `));
  });
};

/** The numbers in a message ("$100", "1,250.50", "5k", "2 million"), each with a few words either side for Jev to read it in. */
function numbersIn(text: string) {
  const pattern = /(?<![\w.])-?\$?\s?(\d{1,3}(?:,\d{3})+|\d+)(\.\d+)?\s?(k|m|bn|thousand|million|billion)?(?![\w%])/gi;
  const scales: Record<string, number> = { k: 1e3, thousand: 1e3, m: 1e6, million: 1e6, bn: 1e9, billion: 1e9 };
  const found = new Map<number, string>();
  for (const match of text.matchAll(pattern)) {
    const sign = match[0].trimStart().startsWith('-') ? -1 : 1;
    const value = sign * Number(`${match[1].replace(/,/g, '')}${match[2] ?? ''}`) * (scales[(match[3] ?? '').toLowerCase()] ?? 1);
    if (!Number.isFinite(value) || found.has(value)) continue;
    const start = match.index ?? 0;
    const before = text.slice(0, start).split(/\s+/).slice(-4).join(' ');
    const after = text.slice(start + match[0].length).split(/\s+/).slice(0, 4).join(' ');
    found.set(value, `${before} ${match[0].trim()} ${after}`.replace(/\s+/g, ' ').trim());
    if (found.size >= MAX_NUMBERS) break;
  }
  return [...found].map(([value, mention]) => ({ value, mention }));
}

/** Request one: whether the message asks for a report, from which table, and as which chart, if it names one. */
export function sourceQuestions(tables: SchemaTable[]) {
  const kind = choice('Which kind of thing is this message to a BI assistant asking for? Pick neither unless it clearly asks for one of the others.', KINDS);
  const source = choice(
    'Which data source (a table or a saved query) has the fields this request needs: what it counts or measures, what it groups or compares by (such as "which team" or "per merchant"), and the date it tracks over time? Prefer a source that has all of them over one whose name only matches a word in the request.',
    tables.map((table) => ({
      value: table.name,
      label: `the ${tableLabel(table)} table${table.description ? `, ${table.description}` : ''}, with columns: ${table.columns.slice(0, MAX_SOURCE_COLUMNS).map((column) => column.field).join(', ')}`,
    })),
    'None of these clearly match the request',
  );
  const chart = choice(
    'Which chart type does this request ask for or clearly imply? Pick table when it asks for a list of rows.',
    CHART_TYPES.map((value) => ({ value })),
    'The request does not say or imply a chart type',
  );
  return {
    questions: { kind: kind.question, source: source.question, chartType: chart.question },
    read(answers: JevAnswers, text: string) {
      if (kind.decode(answers.kind, INTENT_THRESHOLD, true) !== 'report') return null;
      const answer = answers.source;
      const [top, next] = tables
        .map(({ name }) => ({ name, share: source.probabilityOf(answer, name) }))
        .sort((a, b) => b.share - a.share);
      // Similar tables split Jev's vote: one the message names outright wins as its lead by a majority, and one it only
      // implies when it clearly leads.
      const leading = source.decode(answer, 0.5, true);
      const named = tables.find((table) => table.name === leading && namesIn(text, [table.name, table.displayName ?? '']));
      const clearLead = top && top.share >= SOURCE_LEAD_SHARE && top.share > source.probabilityOf(answer, null) && top.share >= SOURCE_LEAD_RATIO * (next?.share ?? 0);
      const table = source.decode(answer, FIELD_THRESHOLD) ?? named?.name ?? (clearLead ? top.name : undefined);
      return table ? { table, chartType: chart.decode(answers.chartType, FIELD_THRESHOLD) } : null;
    },
  };
}

/**
 * Request two, once the table is known: grouping, measure, time bucket, filters and, when the message named none, a
 * chart type, as one batch of parallel questions. `fields` are the table's filter fields (`useTableFilterEditor`), with
 * text fields' values once they load.
 */
export function draftQuestions({ text, table, fields: editorFields, chartType }: { text: string; table: SchemaTable; fields: UseFormQueryBuilderField[]; chartType?: string }) {
  // Each filter field by its column's own name: Jev does not read "Account Days Plan" as the plan a message names ("Pro").
  const fields = editorFields.map((field) => ({ ...field, label: fieldLabel(field.name) }));
  const questions: Record<string, JevQuestion> = {};
  const readers: ((answers: JevAnswers, draft: Draft, rangedDateFields: Set<string>) => void)[] = [];
  const keyOf = (column: Column) => `${table.name}::${column.field}`;
  const columnOf = (value?: string) => table.columns.find((column) => keyOf(column) === value);
  const isDate = (value?: string) => columnOf(value)?.jsType === 'date';

  // Grouping, measure and time bucket. Jev names a first and a second grouping among the fields rows can group by, and
  // the reader arranges them the way the builder draws them: a date goes to rows, since columns only group by text.
  const groupOptions = table.columns.filter(canGroupRows).map((column) => ({ value: keyOf(column), label: `${tableLabel(table)} ${column.label || column.field}` }));
  const group = choice(
    'Which field should the results be grouped or broken down by first (the first "by", "per", or "grouped by" in the request)? A question about which one of something ("which team gets the most…", "which merchant has…") groups by that field, and one about what percent of rows have a value ("what % of calls are flagged as fraud") groups by the field that holds the value. Grouping by a text field such as a status or type (an enum) is how a rate or percent of its values is shown. When the request names a time granularity ("per day", "monthly", "by week", "each quarter"), the first grouping is a date field, and any other grouping comes second.',
    groupOptions,
    'The request does not ask to group or break down the results',
  );
  const columnGroup = choice(
    'Does the request group by a second, different field as well, such as "by month and merchant", "by merchant split by category", "by category and by date", or "per category for each merchant"? If so, which is the second field? A rate or percent per group ("fraud rate per team", "escalation rate by team") also groups by a second field: the text field whose values the rate is about (such as a fraud status or resolution type), so each group splits into its values.',
    groupOptions,
    'The request groups by one field at most, or by none',
  );
  const rows = `${tableLabel(table)} rows`;
  /** An aggregation, in words. */
  const describe = (value: string) => {
    const type = value.slice(0, value.indexOf(':'));
    const field = value.split('::')[1];
    if (!field) {
      return type === 'percentage'
        ? `each group's percent of all ${rows} (its share of the total count, such as "what percent of calls each team handles")`
        : `the count of ${rows}`;
    }
    const column = table.columns.find((entry) => entry.field === field);
    const name = column?.label || field;
    if (type === 'percentage') {
      return column?.jsType === 'boolean' || /bool/i.test(column?.fieldType ?? '')
        ? `the percent of ${rows} where ${name} is true (a rate, such as an escalation rate or a fraud rate)`
        : `each group's percent of the total ${name} (its share of the sum)`;
    }
    return `the ${{ sum: 'sum', average: 'average', max: 'maximum', min: 'minimum' }[type] ?? type} of ${name}`;
  };
  // The builder's own aggregations. Each is a choice for the main measure, and the first few also a yes/no, so a request
  // can ask for several ("count and total amount").
  const aggregationOptions = buildAggregationOptions({ tables: [table], hasRowGrouping: true, resolveTableDisplayLabel: () => tableLabel(table) })
    .options.map(({ value }) => ({ value, label: describe(value) }));
  const asYesNo = aggregationOptions.slice(0, MAX_AGGREGATION_QUESTIONS);
  // The main measure as one pick, so close readings ("the most escalations" is a total, not a maximum) do not split the
  // yes/no answers below the bar and leave the report with none.
  const measure = choice(
    'Which single value does the request mainly measure? "Most", "top", or "least" ranks the groups by that value; it does not ask for a maximum or minimum. A rate or a percent ("escalation rate", "% of calls flagged") is a percentage; when the rate is about the values of a text field (a status or type), it is the percent of total rows, with the rows grouped by that field.',
    aggregationOptions,
    'The request does not ask to count or measure anything',
  );
  const bucket = choice(
    'Which time granularity should results over time be shown in, such as daily, weekly, or monthly? A period that only limits the data ("this year", "last quarter", "this month") is not a granularity.',
    PIVOT_DATE_BUCKET_OPTIONS.filter((option) => option.value),
    'The request names no granularity (an automatic bucket fits), or only limits the period',
  );
  const format = choice(
    'How should the values the request measures be shown? Money (revenue, sales, amount, price, cost, MRR) is in dollars, and a rate or a share is a percent.',
    NUMBER_FORMATS,
    'The request measures nothing, or does not say or imply how its values look',
  );
  Object.assign(questions, {
    group: group.question,
    columnGroup: columnGroup.question,
    measure: measure.question,
    bucket: bucket.question,
    yAxisFormat: format.question,
    overTime: yesNo('Does the request ask to see the results over time, as a trend (such as "over time", "trend", "by date", or "each month")?'),
  });
  asYesNo.forEach((option, index) => (questions[`agg${index}`] = yesNo(`Does the request ask to calculate ${option.label}?`)));

  // The columns the message names as a whole word: the whole name ("account name") or its last word ("plan").
  const message = ` ${normalize(text)} `;
  const named = new Set(groupOptions.map((option) => option.value).filter((value) => {
    const name = normalize(columnOf(value)!.field);
    const last = name.split(' ').pop() ?? '';
    return [name, last.length >= 3 && last !== name ? last : ''].some((form) => form.length >= 2 && (message.includes(` ${form} `) || message.includes(` ${form}s `)));
  }));
  const decodeGroup = (question: typeof group, answer: JevAnswers[string]) => {
    const confident = question.decode(answer, FIELD_THRESHOLD);
    if ((confident && (named.has(confident) || !named.size)) || question.probabilityOf(answer, null) > LITERAL_GROUP_MAX_NONE) return confident;
    const contenders = [...named].filter((value) => question.probabilityOf(answer, value) >= LITERAL_GROUP_SHARE);
    return contenders.length === 1 ? contenders[0] : confident;
  };
  readers.push((answers, draft) => {
    const first = decodeGroup(group, answers.group);
    const mainMeasure = measure.decode(answers.measure, MEASURE_THRESHOLD, true);
    // A rate per group ("fraud rate per team") splits each group by the field the rate is about, which Jev is often less
    // sure of than the measure, so with a percentage it needs only a lead.
    const second = decodeGroup(columnGroup, answers.columnGroup)
      ?? (mainMeasure?.startsWith('percentage:') ? columnGroup.decode(answers.columnGroup, RATE_SPLIT_SHARE, true) : undefined);
    const dateBucket = bucket.decode(answers.bucket, FIELD_THRESHOLD);
    // A granularity ("by plan and month") or a trend ("over time") groups by a date even when the message names none:
    // the date Jev leans to across both groupings, else the row's own date by name, else the first.
    let implicitDate: string | undefined;
    if ((dateBucket || yes(answers.overTime) >= OVER_TIME_THRESHOLD) && !isDate(first) && !isDate(second)) {
      const dates = groupOptions.filter((option) => isDate(option.value));
      const [best] = dates
        .map(({ value }) => ({ value, share: group.probabilityOf(answers.group, value) + columnGroup.probabilityOf(answers.columnGroup, value) }))
        .sort((a, b) => b.share - a.share);
      implicitDate = best && (dates.length === 1 || best.share > 0)
        ? best.value
        : (dates.find(({ value }) => MAIN_DATE.test(columnOf(value)!.field)) ?? dates[0])?.value;
    }
    // A date takes the rows whichever order the message names it in; the other field splits them into columns.
    const [groupRowsBy, groupColumnsBy] = implicitDate ? [implicitDate, first] : isDate(second) && !isDate(first) ? [second, first] : [first, second];
    draft.groupRowsBy = groupRowsBy;
    draft.groupColumnsBy = groupRowsBy && groupColumnsBy !== groupRowsBy && canGroupColumns(columnOf(groupColumnsBy)) ? groupColumnsBy : undefined;
    draft.aggregations = [
      ...(mainMeasure ? [mainMeasure] : []),
      ...asYesNo.filter(({ value }, index) => value !== mainMeasure && yes(answers[`agg${index}`]) >= AGGREGATION_THRESHOLD).map(({ value }) => value),
    ];
    draft.dateBucket = dateBucket;
    // The percent format reads fractions (0.12 is 12%), which only a percentage measure gives; a rate column can hold 43.4.
    const yAxisFormat = format.decode(answers.yAxisFormat, FIELD_THRESHOLD);
    draft.yAxisFormat = yAxisFormat === 'percent' && !mainMeasure?.startsWith('percentage:') ? undefined : yAxisFormat;
  });

  const numberFields = fields.filter((field) => field.quillFieldType === 'number');
  const dateFields = fields.filter((field) => field.quillFieldType === 'date');
  const textFields = fields.filter((field) => field.quillFieldType === 'string' && field.values?.length);
  const addRule = (draft: Draft, rule: RuleType) => (draft.filters = { combinator: 'and', rules: [...(draft.filters?.rules ?? []), rule] });

  // Numbers: what each one does (a comparison on a number field, how far back to go on a date field, or nothing), and
  // its unit when it is an amount of time.
  numbersIn(text).forEach(({ value, mention }, index) => {
    const role = choice(
      `What does the number ${value} in the request do? It appears as: "${mention}"`,
      [
        ...numberFields.flatMap((field) => NUMBER_COMPARISONS.map(({ operator, phrase }) => ({
          value: `cmp|${operator}|${field.name}`,
          label: `Only include rows where ${field.label} is ${phrase} ${value}`,
        }))),
        ...dateFields.map((field) => ({
          value: `date|${field.name}`,
          label: `It is how far back to go: only include rows where ${field.label} is in the last ${value} units of time`,
        })),
      ],
      `${value} does not limit the rows: it is a count of results such as top 10, a name, or part of something else`,
    );
    const unit = choice(
      `If ${value} in "${mention}" is an amount of time, which unit is it in?`,
      DATE_UNITS.map((unitName) => ({ value: unitName, label: `${unitName}s` })),
      `${value} is not an amount of time`,
    );
    questions[`n${index}`] = role.question;
    if (dateFields.length) questions[`n${index}unit`] = unit.question;
    readers.push((answers, draft, rangedDateFields) => {
      const [kind, ...rest] = role.decode(answers[`n${index}`], FILTER_THRESHOLD)?.split('|') ?? [];
      if (kind === 'cmp') return addRule(draft, { field: rest[1], operator: rest[0], value });
      const unitName = unit.decode(answers[`n${index}unit`], FILTER_THRESHOLD);
      if (kind !== 'date' || !unitName || rangedDateFields.has(rest[0]) || value <= 0) return;
      rangedDateFields.add(rest[0]);
      // The filter editor keeps a relative date as an [amount, unit] tuple.
      addRule(draft, { field: rest[0], operator: 'inTheLast', value: [value, unitName] });
    });
  });

  // A whole period named without a number: "this month", "last quarter", "yesterday".
  if (dateFields.length) {
    const period = choice(
      'Does the request limit the data to a whole period named without a number, such as "this month", "last quarter", "YTD", or "yesterday"?',
      DATE_UNITS.flatMap((unitName) => [
        { value: `inTheCurrent|${unitName}`, label: `The current ${unitName} so far` },
        { value: `inThePrevious|${unitName}`, label: `The previous full ${unitName}` },
      ]),
      'No such period: the request names no period, or gives a time range with a number such as "last 30 days"',
    );
    const periodField = choice('Which date field should a time range in the request apply to?', dateFields.map((field) => ({ value: field.name, label: field.label })));
    questions.period = period.question;
    if (dateFields.length > 1) questions.periodField = periodField.question;
    readers.push((answers, draft, rangedDateFields) => {
      const decision = period.decode(answers.period, FILTER_THRESHOLD);
      if (!decision) return;
      // Jev is surer of the period than of which of several dates it means: it applies to Jev's lead, else the row's own date.
      const field = dateFields.length === 1
        ? dateFields[0].name
        : periodField.decode(answers.periodField, FILTER_THRESHOLD)
          ?? periodField.decode(answers.periodField, PERIOD_FIELD_SHARE, true)
          ?? (dateFields.find((entry) => MAIN_DATE.test(entry.name.split('.').pop() ?? '')) ?? dateFields[0]).name;
      if (rangedDateFields.has(field)) return;
      rangedDateFields.add(field);
      const [operator, unitName] = decision.split('|');
      addRule(draft, { field, operator, value: [1, unitName] });
    });
  }

  // Text fields: whether each is filtered (include or exclude), and per value whether the message names it. A field with
  // too many values only asks about the ones the message contains.
  let budget = MAX_VALUE_QUESTIONS;
  textFields.forEach((field, fieldIndex) => {
    const all = field.values!.map((option) => String(option.value ?? ''));
    const literal = new Set(all
      .filter((value) => normalize(value).length >= 2 && message.includes(` ${normalize(value)} `))
      .sort((a, b) => b.length - a.length)
      .slice(0, MAX_MATCHED_VALUES));
    const asked = (all.length <= MAX_VALUES_PER_FIELD ? all : [...literal]).slice(0, Math.max(0, budget));
    if (!asked.length) return;
    budget -= asked.length;
    const mode = choice(
      `Does the request limit rows by ${field.label}?`,
      [
        { value: 'in', label: `Yes: only include certain ${field.label} values` },
        { value: 'notIn', label: `Yes: exclude certain ${field.label} values` },
      ],
      `No. ${field.label} may be mentioned to group or break down results ("by ${field.label}"), but no values are kept or removed`,
    );
    questions[`s${fieldIndex}`] = mode.question;
    asked.forEach((value, valueIndex) => {
      questions[`s${fieldIndex}v${valueIndex}`] = yesNo(`Does the request name "${value}" as a ${field.label} to include or exclude?`);
    });
    readers.push((answers, draft) => {
      const picked = asked.filter((value, valueIndex) =>
        yes(answers[`s${fieldIndex}v${valueIndex}`]) >= (literal.has(value) ? LITERAL_VALUE_THRESHOLD : FILTER_THRESHOLD));
      // A value the message writes out, which Jev confirms, already says the field is filtered; the field question then
      // only settles include or exclude, so its probability is the signal.
      const literalPick = picked.some((value) => literal.has(value));
      const operator = mode.decode(answers[`s${fieldIndex}`], literalPick ? LITERAL_FIELD_THRESHOLD : FILTER_THRESHOLD, literalPick);
      if (operator && picked.length) addRule(draft, { field: field.name, operator, value: picked });
    });
  });

  // No chart type named: Jev recommends one, read once the groupings are known.
  const recommend = chartType ? null : choice(
    'The request does not name a chart type. Which chart type would best show the data it asks for? Prefer line or area for a trend over time, column or bar to compare categories, stacked when each category is split by a second field, pie for parts of a whole with few categories, metric or gauge for a single number, and table for a list of rows.',
    CHART_TYPES.map((value) => ({ value })),
  );
  if (recommend) questions.recommendChart = recommend.question;

  return {
    questions,
    read(answers: JevAnswers): Draft {
      const draft: Draft = { table: table.name, chartType };
      // Per read, so reading the same answers twice gives the same draft.
      const rangedDateFields = new Set<string>();
      for (const reader of readers) reader(answers, draft, rangedDateFields);
      return applyBuilderRules(draft, table, recommend && ((type) => recommend.probabilityOf(answers.recommendChart, type)));
    },
  };
}

/** The chart types the builder allows for a draft's groupings and aggregations. */
function chartTypesFor({ groupRowsBy, groupColumnsBy, aggregations = [] }: Draft) {
  const isPivot = !!(groupRowsBy || groupColumnsBy || aggregations.length);
  return CHART_TYPES.filter((type) => {
    if (aggregations.length > 1 && SINGLE_AGGREGATION_CHART_TYPES.includes(type)) return false;
    // A pivot without a row grouping is one row of totals.
    if (isPivot && !groupRowsBy) return NO_ROW_GROUPING_CHART_TYPES.includes(type);
    return !(groupColumnsBy && NO_COLUMN_GROUPING_CHART_TYPES.includes(type));
  });
}

/**
 * A draft one useReport can show, by the builder's rules, after Jev's read or an edit: only this table's fields; a
 * column grouping needs a row grouping (alone, it becomes one) and never repeats it; any grouping without an
 * aggregation gets a count; a date bucket needs a date row grouping; a chart type the rest rules out falls back to its
 * nearest allowed type, or Jev's favourite among them.
 */
export function applyBuilderRules(draft: Draft, table: SchemaTable, recommend?: ((type: string) => number) | null): Draft {
  const columnOf = (value?: string) => table.columns.find((column) => `${table.name}::${column.field}` === value);
  let groupRowsBy = canGroupRows(columnOf(draft.groupRowsBy)) ? draft.groupRowsBy : undefined;
  let groupColumnsBy = canGroupColumns(columnOf(draft.groupColumnsBy)) ? draft.groupColumnsBy : undefined;
  if (!groupRowsBy && groupColumnsBy) [groupRowsBy, groupColumnsBy] = [groupColumnsBy, undefined];
  if (groupColumnsBy === groupRowsBy) groupColumnsBy = undefined;
  const allowed = buildAggregationOptions({ tables: [table], hasRowGrouping: !!groupRowsBy, resolveTableDisplayLabel: () => '' }).options;
  let aggregations = (draft.aggregations ?? []).filter((value) => allowed.some((option) => option.value === value));
  if (groupRowsBy && !aggregations.length) aggregations = [`count:${table.name}`];
  const rules = draft.filters?.rules.filter((rule) => rule.field.startsWith(`${table.name}.`)) ?? [];
  const next: Draft = {
    table: table.name,
    groupRowsBy,
    groupColumnsBy,
    aggregations,
    dateBucket: columnOf(groupRowsBy)?.jsType === 'date' ? draft.dateBucket : undefined,
    filters: rules.length ? { ...draft.filters!, rules } : undefined,
    yAxisFormat: draft.yAxisFormat,
  };
  const types = chartTypesFor(next);
  const wanted = draft.chartType;
  next.chartType = wanted && types.includes(wanted) ? wanted : CHART_TYPE_FALLBACKS[wanted ?? '']?.find((type) => types.includes(type));
  if (!next.chartType && recommend) {
    const [best] = types.map((type) => ({ type, probability: recommend(type) })).sort((a, b) => b.probability - a.probability);
    if (best?.probability) next.chartType = best.type;
  }
  return next;
}

export const capitalize = (value: string) => value[0].toUpperCase() + value.slice(1);

/**
 * A draft's pick lists, from the schema alone (no report, no queries), the way `useReport` lists them for the same
 * table: groupings by column name, the builder's aggregations, date buckets under a date row grouping, and the chart
 * types the draft's groupings allow.
 */
export function draftOptions(draft: Draft, tables: SchemaTable[]) {
  const table = tables.find(({ name }) => name === draft.table);
  const columns = table?.columns ?? [];
  const optionOf = (column: Column) => ({ value: `${draft.table}::${column.field}`, label: titleCase(column.label || column.field) });
  const rowGrouping = columns.find((column) => `${draft.table}::${column.field}` === draft.groupRowsBy);
  return {
    sources: tables.map((entry) => ({ value: entry.name, label: tableLabel(entry) })),
    groupRowsBy: columns.filter(canGroupRows).map(optionOf),
    groupColumnsBy: columns.filter((column) => canGroupColumns(column) && column !== rowGrouping).map(optionOf),
    aggregations: table
      ? buildAggregationOptions({ tables: [table], hasRowGrouping: !!draft.groupRowsBy, resolveTableDisplayLabel: () => tableLabel(table), showTableNames: false }).options
      : [],
    dateBuckets: rowGrouping?.jsType === 'date' ? PIVOT_DATE_BUCKET_OPTIONS : [],
    chartTypes: chartTypesFor(draft).map((value) => ({ value, label: capitalize(value) })),
  };
}

/** A filter field's column, as the form names it: "Plan" for `account_days.plan`. */
export const fieldLabel = (field: string) => titleCase(field.slice(field.lastIndexOf('.') + 1));
```

`jev.ts`

```ts
/**
 * Jev (TypeSafe System One) answers closed questions about a text with probabilities: a pick among choices, or a yes/no
 * (a "noul"). The questions go to the app's server (server/index.ts), which adds the API key.
 */

export type JevQuestion =
  | { type: 'noul'; instructions: string }
  | { type: 'choice'; instructions: string; criteria: Record<string, string | null> };

export type JevAnswer =
  | { type: 'noul'; noul: number }
  | { type: 'choice'; choice: string; confidence: number; probabilities: Record<string, number> };

export type JevAnswers = Record<string, JevAnswer | undefined>;

export type Option = { value: string; label?: string };

/** Jev takes at most this many choices per question. */
const MAX_CHOICES = 255;
const NONE = 'none';

/** One batch of questions about `text`, asked in parallel. */
export async function askJev(endpoint: string, text: string, questions: Record<string, JevQuestion>, signal: AbortSignal) {
  const response = await fetch(endpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ state: { request: text }, questions }),
    signal,
  });
  if (!response.ok) throw new Error(`Jev answered ${response.status}`);
  return (await response.json()).answers as JevAnswers;
}

/**
 * A pick-one question over `options`, plus "none" when `none` describes it. Choice keys are indexes, so values of any
 * shape (`sum:kpi_transactions::amount`) round-trip.
 */
export function choice(instructions: string, options: Option[], none?: string) {
  const asked = options.slice(0, none ? MAX_CHOICES - 1 : MAX_CHOICES);
  const criteria: Record<string, string | null> = {};
  asked.forEach(({ value, label }, i) => (criteria[`o${i}`] = label && label !== value ? `${label} (${value})` : value));
  if (none) criteria[NONE] = none;

  /** The probability Jev gave one option, by its value, or "none" for `null`. */
  const probabilityOf = (answer: JevAnswer | undefined, value: string | null) => {
    if (answer?.type !== 'choice') return 0;
    if (value === null) return answer.probabilities[NONE] ?? 0;
    const index = asked.findIndex((option) => option.value === value);
    return index < 0 ? 0 : (answer.probabilities[`o${index}`] ?? 0);
  };
  /** The picked option's value, when it clears `threshold` on both Jev's confidence and its probability, or on the probability alone. */
  const decode = (answer: JevAnswer | undefined, threshold: number, probabilityOnly = false) => {
    if (answer?.type !== 'choice' || answer.choice === NONE) return undefined;
    const probability = answer.probabilities[answer.choice] ?? 0;
    const score = probabilityOnly ? probability : Math.min(answer.confidence ?? probability, probability);
    return score < threshold ? undefined : asked[Number(answer.choice.slice(1))]?.value;
  };
  return { question: { type: 'choice', instructions, criteria } as JevQuestion, decode, probabilityOf };
}

export const yesNo = (instructions: string): JevQuestion => ({ type: 'noul', instructions });

/** How sure Jev is that a yes/no question's answer is yes. */
export const yes = (answer: JevAnswer | undefined) => (answer?.type === 'noul' ? answer.noul : 0);
```

<!--# include virtual="/docs-md/code/server-file/$stack_server/$stack_database/$stack_cache.md" -->

<!--# include virtual="/docs-md/page/use-cases/adaptive-ui/1/$stack_model.md" -->

## Search bar

[Open the demo](https://quill.co/docs-demo/blocks/#/search-bar)

`SearchBarBlock.tsx`

```tsx
import { useCallback, useRef, useState } from 'react';
import { useVirtualTables } from '@quillsql/react';
import { ChartColumn, Table2 } from 'lucide-react';
import { AiSearchBar, demoSearch, type AiSearchAnswerRequest, type AiSearchResult } from '../components/blocks/ai-search-bar/ai-search-bar';
import { ReportMessage, useJevDraft } from './AdaptiveUiBlock';
import { draftOptions, tableLabel, type Draft, type SchemaTable } from './reportDraft';
import css from './SearchBarBlock.module.css';

const GROUPS = [
  { id: 'report', label: 'New report', icon: <ChartColumn size={16} strokeWidth={1.75} aria-hidden="true" /> },
  { id: 'tables', label: 'Tables', icon: <Table2 size={16} strokeWidth={1.75} aria-hidden="true" /> },
];
const SUGGESTIONS = ['Transaction revenue by month and plan in the last 6 months', 'Visitors by week and by device in the last 90 days'];
/** Jev reads a question once typing pauses (useJevDraft), so an answer waits at least this long for that read. */
const READ_PAUSE_MS = 300;

const sleep = (ms: number, signal: AbortSignal) => new Promise<void>((resolve, reject) => {
  const timer = setTimeout(resolve, ms);
  signal.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
});

/** The report Jev read, in words: "Sum amount by month and plan". */
function describe(draft: Draft, tables: SchemaTable[]) {
  const options = draftOptions(draft, tables);
  const label = (list: { value: string; label?: string }[], value?: string) => list.find((option) => option.value === value)?.label;
  const measure = label(options.aggregations, draft.aggregations?.[0]) ?? 'Rows';
  const by = [draft.dateBucket || label(options.groupRowsBy, draft.groupRowsBy), label(options.groupColumnsBy, draft.groupColumnsBy)].filter(Boolean);
  const text = by.length ? `${measure} by ${by.join(' and ')}` : measure;
  return text[0] + text.slice(1).toLowerCase();
}

/**
 * The app's search with Jev in it: typing searches the schema's tables, and Jev reads the question into a new report
 * (useJevDraft, as in Generative UI) listed above them. Opening the new report or a table creates it, one useReport,
 * under the bar. Ask AI only shows when Jev reads no report, and its answer says what Jev needs.
 */
export function SearchBarBlock({ jevEndpoint }: { jevEndpoint: string }) {
  const tables = useVirtualTables().data as SchemaTable[];
  const [question, setQuestion] = useState('');
  const jev = useJevDraft(question, jevEndpoint);
  const latest = useRef(jev);
  latest.current = jev;
  const [opened, setOpened] = useState<{ key: number; draft: Draft } | null>(null);

  // The bar calls search with each query, so it is also where the question reaches Jev. While Jev reads, the search
  // stays pending: the bar keeps its last results and spins, and the next ones land with Jev's read in one update.
  const search = useCallback((query: string) => {
    setQuestion(query);
    if (jev.reading) return new Promise<AiSearchResult[]>(() => {});
    const report: AiSearchResult[] = jev.draft ? [{
      id: 'new-report',
      group: 'report',
      title: describe(jev.draft, tables),
      description: [tableLabel(tables.find(({ name }) => name === jev.draft!.table)!), jev.draft.chartType && jev.draft.chartType[0].toUpperCase() + jev.draft.chartType.slice(1)]
        .filter(Boolean).join(' · '),
      action: 'Create report',
    }] : [];
    const matches = demoSearch(query, tables.map((table) => ({
      id: `table:${table.name}`,
      group: 'tables',
      title: tableLabel(table),
      meta: `${table.columns.length} columns`,
      action: 'Open',
      keywords: table.columns.map(({ field }) => field.replace(/_/g, ' ')),
    })));
    return [...report, ...matches];
  }, [jev.reading, jev.draft, tables]);

  const answer = useCallback(async function* ({ signal }: AiSearchAnswerRequest) {
    await sleep(READ_PAUSE_MS, signal);
    while (latest.current.reading) await sleep(50, signal);
    const { draft, error } = latest.current;
    if (error) throw new Error(error);
    // A report closes the answer (askAi below): its New report row already says what Jev read.
    if (draft) return;
    yield { type: 'text' as const, text: 'Jev doesn\'t read a report in this yet. Ask for a measure, what to break it down by, or a time range.' };
  }, []);

  return (
    <div className={css.root}>
      <AiSearchBar search={search} answer={answer} groups={GROUPS} recent={[]} suggestions={SUGGESTIONS} model={{ name: 'Jev 1.13' }}
        placeholder="Search tables, or ask for a report"
        // No AI once Jev reads a report, nor on the empty field, so a picked suggestion waits for Jev's read.
        askAi={(query) => query.trim() !== '' && !jev.draft}
        onSelect={(result) => setOpened((current) => ({
          key: (current?.key ?? 0) + 1,
          draft: result.id === 'new-report' ? latest.current.draft! : { table: result.id.slice('table:'.length) },
        }))} />
      {opened && <ReportMessage key={opened.key} draft={opened.draft} />}
    </div>
  );
}
```

<!--# include virtual="/docs-md/code/server-file/$stack_server/$stack_database/$stack_cache.md" -->
