Guides

Charts from a model

Let a model choose the chart: it returns JSON, and one component renders it.

ChartFromSpec renders a chart from a ChartSpec: plain JSON that names the chart kind, the fields and the rows. A model writes that JSON through a tool call, so an assistant in your product can answer with a chart.

1. Ask the model for a spec

renderChartTool is the tool definition. chartGuidance is a system prompt that tells the model which chart to pick and how to shape the rows. Neither imports React, so both can run in a server route.

The sample uses the Anthropic SDK. Install it in the project that runs your server route.

bash
npm install @anthropic-ai/sdk
chartFor.ts
import Anthropic from '@anthropic-ai/sdk';
import type { ChartSpec } from 'em-kit';
import { chartGuidance, renderChartTool } from 'em-kit/ai';

const anthropic = new Anthropic(); // reads ANTHROPIC_API_KEY

// Ask a question about some rows. Returns the spec of the chart that answers
// it, or null when the model replied in text instead.
export async function chartFor(question: string, rows: object[]): Promise<ChartSpec | null> {
  const response = await anthropic.messages.create({
    model: 'claude-opus-5-5',
    max_tokens: 16000,
    system: chartGuidance, // which chart to pick and how to shape the rows
    tools: [renderChartTool], // the JSON Schema of every chart spec
    messages: [{ role: 'user', content: `${question}\n\n${JSON.stringify(rows)}` }],
  });

  for (const block of response.content) {
    if (block.type === 'tool_use' && block.name === renderChartTool.name) {
      return block.input as ChartSpec;
    }
  }
  return null;
}

With OpenAI, pass renderChartToolOpenAI as the tool and parse tool_calls[0].function.arguments.

2. Render the spec

Pass the spec to ChartFromSpec. Each click comes back as a serialisable ChartIntent, and intentToPrompt() turns it into a sentence you can send as the next message.

AnswerChart.tsx
import { useState } from 'react';
import { ChartFromSpec, intentToPrompt } from 'em-kit';
import type { ChartSpec } from 'em-kit';

// What the model's render_chart call contains: plain JSON.
const spec: ChartSpec = {
  chart: 'bar',
  title: 'Signups by channel',
  dimension: { name: 'channel', title: 'Channel' },
  measures: [{ name: 'signups', title: 'Signups' }],
  rows: [
    { channel: 'Organic search', signups: 1840 },
    { channel: 'Paid search', signups: 1210 },
    { channel: 'Referral', signups: 760 },
    { channel: 'Partner', signups: 430 },
  ],
};

export function AnswerChart() {
  const [followUp, setFollowUp] = useState('Click a bar to see the follow-up it produces.');

  return (
    <div>
      <ChartFromSpec
        spec={spec}
        chrome="plain"
        height={300}
        onIntent={(intent) => setFollowUp(intentToPrompt(intent))}
      />
      <p>{followUp}</p>
    </div>
  );
}
Result

Signups by channel

Click a bar to see the follow-up it produces.

chrome sets how much of the card is drawn: card, plain (no export menu) or bare (no header or background, for a chat bubble).

What happens to a bad spec

The renderer does not trust its input. Dates and numbers sent as text are converted, an unknown chart kind falls back to a table of the rows, and an invalid spec shows the error card instead of throwing.

What the model sees

The tool is named render_chart. Its schema is generated from the ChartSpec type, so it cannot drift from the renderer. To validate a spec on your server, import chartSpecSchema from em-kit/ai.

input_schema 18.8 KB of JSON Schema. Select to expand

The guidance is plain text, about 4 KB:

chartGuidance
Charts: call render_chart to show data. One call per chart; pick the kind from the shape of the data.

Choosing `chart`:
- bar: one measure (or a few) compared across categories.
- barHorizontal: the same, when labels are long or there are more than ~8 categories.
- barGrouped, barGroupedHorizontal: a measure split by a second category (`groupBy`), parts side by side.
- barStacked, barStackedHorizontal: the same split stacked, to show how the parts add up to a total.
- line: a trend over time or another ordered x axis; one line per entry in `measures`.
- lineGrouped: one measure drawn as a line per value of `groupBy`.
- lineWithKpiTabs: a trend with one KPI tab per measure (the tab shows the measure's total);
  good for dashboards-in-one-chart like "revenue / orders / signups over time".
- lineComparison: this period against a previous one (`rows` vs `comparisonRows`, aligned by
  position); set `comparisonLabel`, e.g. "Previous period".
- lineComparisonWithKpiTabs: the comparison plus KPI tabs; headline numbers are derived from the
  rows unless `kpiRows`/`kpiComparisonRows` are given.
- area: volume over time; add `groupBy` to stack the parts.
- barLine: bars (`barMeasures`) plus lines (`lineMeasures`) on a second axis, e.g. volume and a rate.
- pie, donut: only shares of a whole: at most 8 slices, non-negative values. Otherwise use a bar chart.
- donutLabel: a donut with a headline number in the center (`innerLabel`: { text, value } — the
  value defaults to the sum of the rows).
- scatter: the relationship between two measures, one point per `pointDimension`.
- bubble: scatter plus a third measure as point size (`bubbleSizeMeasure`).
- kpi: one headline number.
- kpiComparison: a number against another period (`value`, `comparisonValue`); set
  `options.reversePositiveNegativeColors` when lower is better.
- table: row-level detail or exact values; mixed text and number `columns`.
- heatmap: one measure across two categories as colour intensity (weekday by hour).
- pivot: the same two-way layout with numbers in the cells, several measures and optional sub-rows.

Data rules:
- `rows` is an array of flat objects in long format: one row per category and group combination.
  Never spread groups across columns; name the group field in `groupBy` instead.
- Use only values from the data you were given. Omit `rows` while data is loading (set `loading: true`),
  or set `error` to show a message instead.
- A field is a row key as a bare string ("revenue"), or { name, title?, type?, role?, format? } when it
  needs a display title or formatting. `type` ('string' | 'number' | 'time' | 'boolean') is inferred from rows.
- Time values are zone-less ISO strings: "2025-03-01T00:00:00.000" ("2025-03-01" is also accepted).
  Never add a Z or a UTC offset.
- When the category axis (`dimension` or `xAxis`) is a time field, set `granularity` on the chart,
  never on the field: second, minute, hour, day, week, month, quarter or year.
  The rows must already be bucketed at that granularity.
- Format numbers with the field's `format`: { prefix: "$", suffix: "%", decimalPlaces: 1 }.
  Also available: displayName, displayNullAs, maxCharacters.
- Options are always written in vertical orientation, including for horizontal variants:
  `options.xAxisLabel` labels the category axis; `options.yAxisLabel`, `options.yAxisRangeMin`
  and `options.yAxisRangeMax` the value axis. The renderer swaps them.
- `kpi` and `kpiComparison` accept `value` (and `comparisonValue`) instead of `rows`.
- In `table`, set a column's `role` ('dimension' | 'measure') only when it is ambiguous.
- Give every chart a short `title` that says what it shows.

Try your own specs in the AI chat example.