# Chart a query result

> Ask your model which chart fits the rows your application got from AskDB's SQL, get back a chart spec, and draw it with your own charting library. The model never sees a row.

AskDB returns SQL, and your application runs it. This guide turns those rows into a chart. `@askdb/client/charts` asks your model which chart fits the result. It returns a chart spec, a small object that names the chart type and columns. Your application draws the chart from its own rows, with its own charting library.

The model gets the question, the SQL and the column kinds, never a row. AskDB draws nothing.

If this is new to you, start with the tutorial [Chart your first answer](https://askdb.tools/chart-your-first-answer/), which draws this chart in the Quickstart’s project.

![A horizontal bar chart titled Total Spending by Customers (Highest First). Grace 398, Margaret 377, Ada 138.99, Linus 49.99.](https://askdb.tools/_astro/total-spent-light.BR0ZJmWI_ZNM71I.svg)

*Figure: The chart answers one question on the Quickstart’s shop database: “How much has each customer spent in total, highest first?” For that question, `planChart()` returned the chart type, the two columns, the title and the description, from gpt-4o-mini on 2026-11-15. The example drew it with ECharts from that run’s 4 rows.*

## Who does what

- **Your application** runs the SQL and keeps the rows. It calls `classifyResult()` and `planChart()`, and it draws the chart.
- **`@askdb/client/charts`** runs in your process. It classifies the columns, builds the prompt and checks the model’s answer. It reads the rows you pass to `classifyResult()` and sends them nowhere.
- **Your model** picks the chart type, the columns, a title and a description. It gets the question, the SQL with every value replaced by `?`, each column’s name and kind, and the row count. It gets no row.

* **AskDB:** runs in your process

- **AskDB:** `ask()` returns checked SQL
  - → runs it and keeps the rows: SQL

- **Your application:** runs it and keeps the rows

  - → `classifyResult()`, in your process: rows
  - → your charting library draws the chart: rows

- **AskDB:** `classifyResult()`, in your process
  - → `planChart()`: column names and kinds, the row count

- **AskDB:** `planChart()`

  - → your model: the question, the SQL with `?` for values, column names and kinds
  - → your charting library draws the chart: checked chart spec

- **Your model:** your model
  - → `planChart()`: chart spec (in reply)

- **Your application:** your charting library draws the chart

*Figure: The rows go to two places: `classifyResult()`, which runs in your process, and your own charting library. `planChart()` sends your model three things. They are the question, the SQL with `?` for every value, and the column names and kinds. It checks the chart spec the model returns, and your application draws that spec.*

[Chart planning](https://askdb.tools/concepts/chart-planning/) explains the design: what the model never sees, what the checks refuse, what a chart costs, and when to skip the planner.

> **Experimental**
>
> `@askdb/client/charts` is outside AskDB’s stability promise: a minor release of `@askdb/client` may change it ([ADR 0030](https://github.com/Ygilany/AskDB/blob/main/docs/adrs/0030-1-0-promises-checked-sql-only.md)).

## Before you start

- A service that calls `ask()` or `client.ask()` and runs the SQL under your own connection. [Embed in a Node app](https://askdb.tools/guides/embed-in-node/) builds one.
- A row cap on that connection. A chart from a cut result needs to know it was cut; [Cap the rows a query returns](https://askdb.tools/guides/cap-the-rows-a-query-returns/) returns `{ rows, truncated }`.
- A charting library. Step 4 has the code for [Apache ECharts](https://echarts.apache.org/) and for [shadcn/ui charts](https://ui.shadcn.com/docs/components/chart), which are Recharts. It also says what changes for another library.
- Room for one more model call per chart, after the call `ask()` makes.

Install `@askdb/client`, which holds the `@askdb/client/charts` entry point. A service from [Embed in a Node app](https://askdb.tools/guides/embed-in-node/) has all of these, and the package for its model. You install your charting library in step 4. Two details on the packages:

- **Imports.** The entry point imports only `@askdb/core` and `ai`.
- **Peer.** `@askdb/config` is a peer of `@askdb/client`.

**npm**

```bash
npm install @askdb/client @askdb/core @askdb/config ai
```

**pnpm**

```bash
pnpm add @askdb/client @askdb/core @askdb/config ai
```

**yarn**

```bash
yarn add @askdb/client @askdb/core @askdb/config ai
```

The whole flow, on the Quickstart’s shop database, is in [examples/chart-a-result](https://github.com/Ygilany/AskDB/tree/main/examples/chart-a-result). Its `draw-recorded.mjs` draws the chart above with no API key. The output in each step below is from that example’s recorded run.

## 1. Run the query

Generate the SQL and run it yourself. AskDB returns the SQL and never runs it.

```ts
const question = "How much has each customer spent in total, highest first?";
const { sql } = await askdb.ask(question);        // or ask({ question, schema, model, dialect })
const { rows, truncated } = await runCapped(sql); // your own connection and row cap
```

On the shop database, the model wrote this SQL, and the application got 4 rows:

```sql
SELECT customers.name, SUM(products.price * orders.quantity) AS total_spent
FROM customers
JOIN orders ON customers.id = orders.customer_id
JOIN products ON orders.product_id = products.id
GROUP BY customers.id
ORDER BY total_spent DESC;
```

```json
[
  { "name": "Grace", "total_spent": 398 },
  { "name": "Margaret", "total_spent": 377 },
  { "name": "Ada", "total_spent": 138.99 },
  { "name": "Linus", "total_spent": 49.99 }
]
```

## 2. Classify the result in your process

Pass the columns and the rows to `classifyResult()`. It runs in your process and makes no model call.

```ts
import { classifyResult } from "@askdb/client/charts";

const result = classifyResult({
  // Your driver's column list, with each column's database type when it reports one.
  columns: Object.keys(rows[0] ?? {}).map((name) => ({ name })),
  rowCount: rows.length,
  truncated,
  rows, // optional: read here, never sent to a model
});
```

It returns two parts. `result.shape` is all the model sees of the result:

```json
{
  "columns": [
    { "name": "name", "kind": "category" },
    { "name": "total_spent", "kind": "currency" }
  ],
  "rowCount": 4,
  "truncated": false
}
```

`result.local` holds facts read from the rows, such as negative values and label lengths. They stay in your process, for the checks in step 3.

If your driver doesn’t report a column’s type, pass `schema`, the schema artifact `ask()` used. A result column then takes the type of the one schema column with its name. [Column kinds](https://askdb.tools/reference/client-charts-api/#column-kinds) lists every kind and how it’s read.

## 3. Plan the chart

Pass the question, the SQL and the classified result to `planChart()`, with the model you give `ask()`. Pass `dialect` as you do to `ask()`: it decides how `planChart()` finds the values to mask in the SQL.

**AskDB builds the model**

```ts
import { planChart } from "@askdb/client/charts";
import { createAiRegistry } from "@askdb/ai";

const model = await createAiRegistry().createLanguageModelFromEnv(process.env);
if (!model) throw new Error("No AI provider is configured: set its API key.");
const plan = await planChart({ question, sql, result, model, dialect: "sqlite" });
```

**Your app builds the model**

```ts
import { planChart } from "@askdb/client/charts";
import { openai } from "@ai-sdk/openai";

const model = openai("gpt-4o-mini"); // the model you pass to ask()
const plan = await planChart({ question, sql, result, model, dialect: "sqlite" });
```

The recorded run returned this plan:

```json
{
  "primary": {
    "type": "horizontal-bar",
    "category": "name",
    "series": ["total_spent"],
    "title": "Total Spending by Customers (Highest First)",
    "description": "Displays the total amount spent by each customer, ranked from highest to lowest."
  },
  "source": "model",
  "latencyMs": 1287
}
```

`plan.primary` is the chart spec. It names columns of your result and holds no data. The model picks it, so yours can differ. The spec has five fields:

- `type`
- `category`, the column that labels each bar, slice or point
- `series`, the columns to plot
- `title`
- `description`

## 4. Draw the chart from your rows

The chart spec is the same for every charting library. The only code that depends on your library is one mapping from the spec to that library’s config. Your rows go in as they are.

Pick your library. Each tab has its install line, the mapping as a table, the code that does it, and the code that calls it.

**ECharts**

Install ECharts:

**npm**

```bash
npm install echarts
```

**pnpm**

```bash
pnpm add echarts
```

**yarn**

```bash
yarn add echarts
```

Map the chart spec onto an ECharts option, and give ECharts your rows:

| Chart spec               | ECharts option                                                                                   |
| ------------------------ | ------------------------------------------------------------------------------------------------ |
| Your rows                | `dataset.source`                                                                                 |
| `title`, `description`   | `title.text`, `title.subtext`                                                                    |
| Each name in `series`    | One entry in `series`, named after the column                                                    |
| `type: "bar"`            | `series[].type: "bar"`, with `encode: { x: category, y: column }`                                |
| `type: "horizontal-bar"` | The same, with the axes swapped: `encode: { x: column, y: category }`                            |
| `type: "line"`           | `series[].type: "line"`                                                                          |
| `type: "area"`           | A line series with `areaStyle: {}`                                                               |
| `type: "pie"`            | One series of `type: "pie"`, with `encode: { itemName: category, value: series[0] }` and no axes |
| `type: "metric"`         | No chart. Show `rows[0][series[0]]` as a number, under the title.                                |

This function does that mapping for every chart type:

```js title="to-echarts.mjs"
/**
 * Turns a chart spec from @askdb/client/charts into an ECharts option.
 * ECharts reads your rows from `dataset.source` and picks columns by name with `encode`,
 * so the spec's `category` and `series` go in as they are.
 * A metric is one number, not a chart: it gets no option.
 *
 * @param {import("@askdb/client/charts").ChartSpec} spec
 * @param {Record<string, unknown>[]} rows
 * @returns {import("echarts").EChartsOption | null}
 */
export function toEChartsOption(spec, rows) {
  if (spec.type === "metric") return null;
  const base = {
    title: { text: spec.title, subtext: spec.description },
    dataset: { source: rows },
    tooltip: {},
  };
  if (spec.type === "pie") {
    return { ...base, series: [{ type: "pie", encode: { itemName: spec.category, value: spec.series[0] } }] };
  }
  const horizontal = spec.type === "horizontal-bar";
  const categoryAxis = { type: "category", inverse: horizontal }; // inverse: the first row at the top
  const valueAxis = { type: "value" };
  return {
    ...base,
    legend: { show: spec.series.length > 1, bottom: 0 },
    grid: { top: 80 },
    xAxis: horizontal ? valueAxis : categoryAxis,
    yAxis: horizontal ? categoryAxis : valueAxis,
    series: spec.series.map((column) => ({
      type: spec.type === "line" || spec.type === "area" ? "line" : "bar",
      name: column,
      ...(spec.type === "area" ? { areaStyle: {} } : {}),
      encode: horizontal ? { x: column, y: spec.category } : { x: spec.category, y: column },
    })),
  };
}
```

Call it where your application shows the result. `showTable` and `showNumber` stand for your own code:

```ts
import * as echarts from "echarts";
import { toEChartsOption } from "./to-echarts.mjs";

const spec = plan.primary;
if (!spec) {
  showTable(rows); // no chart fits this result
} else if (spec.type === "metric") {
  showNumber(spec.title, rows[0][spec.series[0]]);
} else {
  echarts.init(document.getElementById("chart")).setOption(toEChartsOption(spec, rows));
}
```

**shadcn/ui (Recharts)**

Add shadcn/ui’s chart component to your project. It installs Recharts, and adds `components/ui/chart.tsx` and `components/ui/card.tsx`:

```bash
npx shadcn@latest add chart
```

Map the chart spec onto shadcn’s `ChartContainer` and the Recharts components inside it, and give the chart your rows:

| Chart spec               | shadcn/ui and Recharts                                                                                                                                      |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Your rows                | `data` on the chart, or on the `Pie`                                                                                                                        |
| `title`, `description`   | `CardTitle` and `CardDescription`, in the `Card` header                                                                                                     |
| Each name in `series`    | One key in the `ChartConfig`, with a label, and one `Bar`, `Line` or `Area` with that `dataKey` and a color                                                 |
| `type: "bar"`            | `BarChart`, with `<XAxis dataKey={category} />`                                                                                                             |
| `type: "horizontal-bar"` | `BarChart layout="vertical"`, with `<YAxis type="category" dataKey={category} />` and `<XAxis type="number" />`                                             |
| `type: "line"`           | `LineChart`, with a `Line` for each series                                                                                                                  |
| `type: "area"`           | `AreaChart`, with an `Area` for each series                                                                                                                 |
| `type: "pie"`            | `PieChart` with one `Pie` and a `ChartLegend`. Each row is a slice, with the `category` value as its name, the `series[0]` value as a number, and a `fill`. |
| `type: "metric"`         | No chart. Show `rows[0][series[0]]` as a number, under the title.                                                                                           |

This component does that mapping for every chart type. Save it next to shadcn’s components:

```tsx title="components/spec-chart.tsx"
"use client";

import type { ChartSpec } from "@askdb/client/charts";
import type { ReactNode } from "react";
import { Area, AreaChart, Bar, BarChart, CartesianGrid, Line, LineChart, Pie, PieChart, XAxis, YAxis } from "recharts";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { type ChartConfig, ChartContainer, ChartLegend, ChartLegendContent, ChartTooltip, ChartTooltipContent } from "@/components/ui/chart";

type Row = Record<string, unknown>;
/** The five theme colors, then the same five at 55% strength: enough for a pie's 8 slices. */
const color = (index: number) => {
  const theme = `var(--chart-${(index % 5) + 1})`;
  return index % 10 < 5 ? theme : `color-mix(in oklab, ${theme} 55%, transparent)`;
};

/**
 * Draws a chart spec from @askdb/client/charts with shadcn/ui's chart component, which is Recharts.
 * Recharts reads your rows as they are and picks columns by name with `dataKey`,
 * so the spec's `category` and `series` go in as they are.
 * A metric is one number, not a chart: it shows the value under the title.
 * The config holds labels only: a color in it makes shadcn write the column name, which the model chose, into a <style> element.
 */
export function SpecChart({ spec, rows }: { spec: ChartSpec; rows: Row[] }) {
  // Number(): a pie draws nothing from strings, which drivers return for bigint and numeric columns.
  const slices = rows.map((row, index) => ({ name: String(row[spec.category!]), value: Number(row[spec.series[0]]), fill: color(index) }));
  const labels = spec.type === "pie" ? slices.map((slice) => slice.name) : spec.series;
  const config: ChartConfig = Object.fromEntries(labels.map((label) => [label, { label }]));
  const value = rows[0]?.[spec.series[0]];
  return (
    <Card>
      <CardHeader>
        <CardTitle>{spec.title}</CardTitle>
        <CardDescription>{spec.description}</CardDescription>
      </CardHeader>
      <CardContent>
        {spec.type === "metric" ? (
          <p className="text-4xl font-semibold tabular-nums">{typeof value === "number" ? value.toLocaleString() : String(value)}</p>
        ) : (
          <ChartContainer config={config} className="min-h-[200px] w-full">
            {spec.type === "pie" ? (
              <PieChart accessibilityLayer>
                <ChartTooltip content={<ChartTooltipContent nameKey="name" hideLabel />} />
                <ChartLegend content={<ChartLegendContent nameKey="name" />} />
                <Pie data={slices} dataKey="value" nameKey="name" />
              </PieChart>
            ) : (
              <CartesianChart spec={spec} rows={rows} type={spec.type} />
            )}
          </ChartContainer>
        )}
      </CardContent>
    </Card>
  );
}

/** For each cartesian chart type, the Recharts chart and the line, area or bar it draws for one column. */
const cartesian: Record<Exclude<ChartSpec["type"], "pie" | "metric">, { Chart: typeof BarChart; draw: (column: string, color: string) => ReactNode }> = {
  line: { Chart: LineChart, draw: (column, color) => <Line key={column} dataKey={column} stroke={color} dot={false} /> },
  area: { Chart: AreaChart, draw: (column, color) => <Area key={column} dataKey={column} stroke={color} fill={color} fillOpacity={0.4} /> },
  bar: { Chart: BarChart, draw: (column, color) => <Bar key={column} dataKey={column} fill={color} radius={4} /> },
  "horizontal-bar": { Chart: BarChart, draw: (column, color) => <Bar key={column} dataKey={column} fill={color} radius={4} /> },
};

/** Line, area, bar and horizontal bar: one Recharts chart, with one line, area or bar for each column in `series`. */
function CartesianChart({ spec, rows, type }: { spec: ChartSpec; rows: Row[]; type: keyof typeof cartesian }) {
  const { Chart, draw } = cartesian[type];
  const horizontal = type === "horizontal-bar";
  return (
    <Chart accessibilityLayer data={rows} layout={horizontal ? "vertical" : "horizontal"}>
      <CartesianGrid horizontal={!horizontal} vertical={horizontal} />
      {horizontal ? <XAxis type="number" /> : <XAxis dataKey={spec.category} />}
      {horizontal ? <YAxis type="category" dataKey={spec.category} /> : <YAxis />}
      <ChartTooltip content={<ChartTooltipContent />} />
      {spec.series.length > 1 && <ChartLegend content={<ChartLegendContent />} />}
      {spec.series.map((column, index) => draw(column, color(index)))}
    </Chart>
  );
}
```

The title and description go in a shadcn `Card`, as in shadcn’s own chart examples. Without a card, put them in your own heading and keep the `ChartContainer`. The colors come from shadcn’s `--chart-1` to `--chart-5` CSS variables, and a pie’s sixth to eighth slices take the same colors at 55% strength. The colors go on the lines, areas, bars and slices, and the `ChartConfig` holds labels only. A color in it would put its key, a column name that the model chose, into a `<style>` element.

Use it where your application shows the result. `ResultTable` stands for your own table component:

```tsx title="components/answer.tsx"
import type { ChartPlan } from "@askdb/client/charts";
import { ResultTable } from "@/components/result-table"; // your own table
import { SpecChart } from "@/components/spec-chart";

export function Answer({ plan, rows }: { plan: ChartPlan; rows: Record<string, unknown>[] }) {
  if (!plan.primary) return <ResultTable rows={rows} />; // no chart fits this result
  return <SpecChart spec={plan.primary} rows={rows} />;
}
```

The example’s tests render both components for every chart type, with React and shadcn’s own `chart.tsx`, and no browser.

Your page then shows a chart like the one at the top of this guide. The rows reach the browser from your own API, the way they reach a table. The chart spec can go with them: it holds no row.

If you use another library, map the same five fields. Chart.js and Vega-Lite also take an array of row objects and a column name for each axis. The option that names the column:

- **Chart.js.** `parsing.xAxisKey` and `parsing.yAxisKey`.
- **Vega-Lite.** `encoding.x.field`.

## 5. Handle a fallback and a result with no chart

`planChart()` never rejects because of the model. Check three fields of the plan:

- **`plan.primary` is `null`.** No column holds a number to plot, or a result of several rows has no column to group them by. Show the table.
- **`plan.source` is `"fallback"`.** The model call failed, was aborted, took longer than `timeoutMs` (15000 by default), or returned a chart that failed the checks. `plan.primary` is then a chart picked from the classified columns by fixed rules, so draw it the same way. `plan.fallbackReason` says why, and `plan.issues` lists what the checks refused. Log both. For the result above, the fallback picks the same horizontal bar chart, with the title “Total spent by name”.
- **`plan.alternate` is set.** It’s a second chart spec that passed the checks. Offer it as another view of the same rows.

To wait less than 15 s for a chart, pass `timeoutMs`:

```ts
const plan = await planChart({ question, sql, result, model, dialect: "sqlite", timeoutMs: 5000 });
```

If you store a chart spec and draw it later from new rows, classify the new result and check the spec with [`validateChartSpec()`](https://askdb.tools/reference/client-charts-api/#validatechartspecspec-result-context) first.

## Keep sensitive columns out of the prompt

Some projects keep sensitive columns out of prompts with `modes.omitSensitiveFromPrompt`. If you do, pass that setting to `planChart()` too, as `omitSensitiveIdentifiers`, with the schema artifact as `schema`. `ask()` takes it the same way. The model then gets no SQL that mentions a sensitive column. A result column named like one is shown under a `column_<n>` label, and `planChart()` maps the label in the model’s answer back to the real name.

```ts
const plan = await planChart({ question, sql, result, model, dialect: "sqlite", schema, omitSensitiveIdentifiers: true });
```

[Keep sensitive columns out of prompts](https://askdb.tools/guides/keep-sensitive-columns-out-of-prompts/) lists every prompt that follows the setting.

## Use with your agent

To hand this task to a coding agent, copy the prompt and paste it into the agent.

> Add a chart to the place where this project shows a query result from AskDB. Follow <https://askdb.tools/guides/plan-a-chart.md>.
>
> Constraints:
>
> - AskDB returns SQL and a chart spec. This application runs the SQL and draws the chart from its own rows, with its own charting library.
> - Use the charting library this project already has. Look for one in its dependencies first, such as Recharts (shadcn/ui charts are Recharts), Chart.js, ECharts, Vega-Lite or D3. If it has none, ask which one to add. Don’t add a second library beside one that is there.
> - Write one function or component that maps the chart spec to that library’s config. `type` picks the chart, `category` and `series` name columns of the rows, and `title` and `description` are its text. Cover all six types, with `metric` as a number and not a chart.
> - Start from a ready-made mapping when one fits. Step 4 of the guide has two, one in each tab: `to-echarts.mjs` for ECharts, and `components/spec-chart.tsx` for shadcn/ui charts and Recharts. In the AskDB repo they are `examples/chart-a-result/to-echarts.mjs` and `examples/chart-a-result/shadcn/components/spec-chart.tsx`. For another library, port the closer one.
> - Pass `classifyResult()` the result’s columns, row count and `truncated` flag. Never put a row in a prompt.
> - `@askdb/client/charts` is experimental. Draw `plan.primary` when it is set, show the table when it is `null`, and log `plan.fallbackReason` and `plan.issues`.

## Read next

- [Chart planning](https://askdb.tools/concepts/chart-planning/): What the model sees, what the checks refuse, and when to skip the planner.
- [@askdb/client/charts API](https://askdb.tools/reference/client-charts-api/): Every option, type and check.
- [Cap the rows a query returns](https://askdb.tools/guides/cap-the-rows-a-query-returns/): The `truncated` flag the planner reads.
- [Bring your own model](https://askdb.tools/guides/bring-your-own-model/): Both ways to give the planner a model.

---

Source: https://askdb.tools/guides/plan-a-chart/ · Index of every page: https://askdb.tools/llms.txt · Every page has a Markdown version at its URL with the trailing slash replaced by `.md`.
