# Ask (instant)

> The endpoints behind the app's Ask page. A question is answered from a ready-made recipe for 5 credits when one fits, and by the planner for 25 when none does, as a stream of UI patches.

Source: https://openpipe.health/docs/api/ask2/

## Which Ask to call

There are two ways to ask a question over REST. Both store the answer as a [dashboard](https://openpipe.health/docs/api/saved.md) in the same place.

| | [`POST /api/ask`](https://openpipe.health/docs/api/ask.md) | `POST /api/ask2/ask` (this page) |
|---|---|---|
| How it answers | Always the planner: a model writes the SQL | A ready-made recipe when one fits the question. The planner when none does. |
| Credits | 25 | 5 for a recipe, 25 for the planner |
| Response | One JSON document, or an event stream of finished tiles | Always an event stream of JSON Patch operations that build a UI spec |
| Follow-ups | Ask a new question | [`/edit`](#change-a-dashboard) patches the dashboard. [`/predict`](#predict-the-next-dashboards) and [`/open`](#open-a-predicted-dashboard) prepare the next one. |
| Used by | The MCP [`ask` tool](https://openpipe.health/docs/mcp.md#tools) | The app's Ask page |

- **Simpler for a server-to-server integration: `POST /api/ask`.** In [JSON mode](https://openpipe.health/docs/api/ask.md#json-mode) it is one request and one document with every tile's rows. `/api/ask2/ask` has no JSON mode. You read server-sent events and apply each patch to a spec yourself, or you wait for `done` and fetch the rows with [`GET /api/dashboards/:id`](https://openpipe.health/docs/api/saved.md#open-a-dashboard).
- **Cheaper for common questions: `/api/ask2/ask`.** Top clinicians for a procedure, top prescribers of a drug, a hospital, group or clinician profile and a market by state are recipes. They cost 5 credits and need no text model. [`GET /api/ask2/about`](#recipes-prices-and-limits) lists all of them, and the free [preview](#preview-a-question) says which tier a question would get before you ask it.
- **It never costs more than 25.** When no recipe fits, `/api/ask2/ask` runs the same pipeline as `POST /api/ask`: the same table selection, the same SQL checks, the same withheld tiles, the same charge after the plan. See [how the planner works](https://openpipe.health/docs/api/ask.md#when-you-are-charged-and-what-is-stored). Only the events differ.

Every endpoint here takes an [API key or a session token](https://openpipe.health/docs/authentication.md). Nothing here accepts SQL.

| Endpoint | Credits |
|---|---|
| [`GET /api/ask2/preview`](#preview-a-question) | Free |
| [`POST /api/ask2/ask`](#ask-a-question) | 5 or 25 |
| [`POST /api/ask2/edit`](#change-a-dashboard) | 5 or 25 |
| [`POST /api/ask2/predict`](#predict-the-next-dashboards) | Free |
| [`POST /api/ask2/open`](#open-a-predicted-dashboard) | 5 |
| [`GET /api/ask2/d/:id`](#read-a-stored-answer) | Free |
| [`GET /api/ask2/about`](#recipes-prices-and-limits) | Free |

## Preview a question

```http
GET /api/ask2/preview
```

Says what would be built for these words: the tier, the recipe, what was recognised and the tile layout. Free. No query runs and no rows are returned.

| Parameter | Meaning |
|---|---|
| `q` | The question so far. 3 to 200 characters after trimming. |
| `as` | Optional role to lay the answer out for: `rep`, `leader`, `marketing`, `analyst`, `bizdev` or `founder`. Any other value is ignored. |

```sh
curl -G "$OPH_API/api/ask2/preview" \
  -H "Authorization: Bearer $OPH_KEY" \
  --data-urlencode "q=top TAVR operators in Florida"
```

```json
{
  "tier": "instant",
  "recipe": { "id": "proc_top_clinicians", "label": "Top clinicians for a procedure", "flow": "list" },
  "confidence": 0.94,
  "probabilities": [
    { "id": "proc_top_clinicians", "label": "Top clinicians for a procedure", "p": 0.94 },
    { "id": "proc_market_by_state", "label": "Procedure market by state", "p": 0.01 },
    { "id": "none", "label": "None of these (use the planner)", "p": 0.05 }
  ],
  "decidedBy": "jev",
  "unsure": false,
  "threshold": 0.5,
  "chips": [
    { "kind": "procedure", "label": "TAVR", "sub": "HCPCS 33361" },
    { "kind": "state", "label": "Florida", "sub": "FL" }
  ],
  "alternatives": [
    { "id": "proc_market_by_state", "label": "Procedure market by state" },
    { "id": "proc_top_groups", "label": "Group practices for a procedure" },
    { "id": "proc_share_by_specialty", "label": "Procedure share by specialty" }
  ],
  "territoryDefault": null,
  "ms": { "match": 309.85, "decide": 229, "decideCached": false },
  "q": "top TAVR operators in Florida",
  "title": "Top clinicians for tAVR in Florida",
  "layout": [
    { "id": "top", "type": "Leaderboard", "title": "Top clinicians for tAVR" },
    { "id": "stats", "type": "Stat", "title": "TAVR, Medicare volume" },
    { "id": "map", "type": "StateMap", "title": "TAVR by state", "highlight": ["FL"] },
    { "id": "split", "type": "Bar", "title": "Which specialties perform it" }
  ]
}
```

| Field | Meaning |
|---|---|
| `tier` | `instant` when a recipe was chosen (5 credits to ask), `planned` when the question would go to the planner (25) |
| `recipe` | The chosen recipe, or `null` |
| `confidence`, `probabilities` | What the decision model gave the top recipe, and its spread over the candidates and `none`. `confidence` is `null` and `probabilities` is empty when rules decided. |
| `decidedBy` | `jev` (the decision model), `rules` (the recipes' cue words), `pinned` (you passed `pin`) or `none` (no recipe) |
| `unsure` | `true` when the pick is a guess. Offer `alternatives`. |
| `threshold` | The probability a recipe needs: 0.5. See [how a recipe is chosen](#how-a-recipe-is-chosen). |
| `chips` | What was recognised in the words: `kind` is `procedure`, `drug`, `specialty`, `company`, `state`, `city`, `hospital`, `group`, `clinician` or `filter` |
| `alternatives` | Up to three other recipes that could answer the same words. Pass one's `id` as `pin` to [`/ask`](#ask-a-question). |
| `territoryDefault` | Set when no place was named and the signed-in person's territory was used |
| `ms` | Time spent matching entities and deciding. `decideCached` is `true` when the decision was already held from an earlier call. |
| `title` | The dashboard title, or `null` when no recipe was chosen |
| `layout` | Up to four tiles in display order: `id`, `type`, `title` and, on a map, `highlight`. When no recipe was chosen it is the closest recipe's shape with empty titles, or three generic tiles. |

The response is sent with `Cache-Control: no-store`. `/ask` makes its own decision. It is normally the same one, because decisions made by the model are held for 10 minutes.

### Limits

300 previews a minute per person (per workspace for an API key). After the first 150 in a minute the decision model is no longer called and rules alone decide, so answers can differ. These sit on top of the [general limits](https://openpipe.health/docs/api/errors.md#rate-limits).

### Errors

| Status | Body |
|---|---|
| `400` | `{ "error": "Type at least 3 characters.", "code": "TOO_SHORT" }` |
| `400` | `{ "error": "A preview reads at most 200 characters.", "code": "TOO_LONG" }` |
| `429` | `{ "error": "Too many previews. Try again in 23s.", "code": "RATE_LIMITED" }` |

## Ask a question

```http
POST /api/ask2/ask
```

Answers a question from a recipe or, when none fits, with the planner. Costs 5 credits when a recipe answers. Costs 25 credits when the planner does. The response is a `text/event-stream`.

### Body

```json
{ "question": "top TAVR operators in Florida", "rid": "docs-ask2-0001" }
```

| Field | Meaning |
|---|---|
| `question` | Required. At least 5 characters after trimming (the preview accepts 3). Anything past 500 characters is cut off. |
| `as` | Optional role, as for [preview](#preview-a-question). It sets the board's `lens` and can change which recipe a short question gets. |
| `pin` | Optional recipe `id`. If that recipe can be built from the question, it is used without asking the decision model. Otherwise `pin` is ignored. Anything past 60 characters is cut off. |
| `planner` | Optional. `true` skips the recipes and sends the question to the planner, at 25 credits. |
| `rid` | Optional request id for safe retries: 8 to 64 letters, digits or hyphens. Any other value is ignored. See [retrying with `rid`](#retrying-with-rid). |

```sh
curl -N "$OPH_API/api/ask2/ask" \
  -H "Authorization: Bearer $OPH_KEY" -H "Content-Type: application/json" \
  -d '{"question": "top TAVR operators in Florida", "rid": "docs-ask2-0001"}'
```

### Events of an instant answer

| Event | Count | Data |
|---|---|---|
| `decision` | 1 | The same fields as a [preview](#preview-a-question), without `q`, `title` and `layout` |
| `patch` | 1 per element | The spec, before any query has finished: `/root`, then the board, then each tile with its SQL |
| `say` | 0 or more | `{ "text": "…" }`, a line of narration |
| `usage` | 1 | The [usage object](https://openpipe.health/docs/credits.md#the-usage-object). Sent when the first tile has a result and the workspace has been charged. No row is sent before it. |
| `patch` | 1 per tile | `add /state/<tile id>`: the tile's result, in completion order |
| `say` | 0 or 1 | One line computed from the rows |
| `done` | 1 | `id` (the stored dashboard, `null` only if it could not be stored), `tier`, `meta` and `ms` (total) |
| `error` | 0 or 1 | Sent when the answer cannot finish. The stream ends without `done`. See [errors inside the stream](#errors-inside-the-stream). |

The example above produced this, trimmed:

```
event: decision
data: {"tier":"instant","recipe":{"id":"proc_top_clinicians","label":"Top clinicians for a procedure","flow":"list"},"confidence":0.94,"decidedBy":"jev","unsure":false,"threshold":0.5,"chips":[{"kind":"procedure","label":"TAVR","sub":"HCPCS 33361"},{"kind":"state","label":"Florida","sub":"FL"}], ...}

event: patch
data: {"op":"add","path":"/root","value":"board"}

event: patch
data: {"op":"add","path":"/elements/board","value":{"type":"Board","props":{"title":"Top clinicians for tAVR in Florida","summary":"Medicare fee-for-service claims for HCPCS 33361, data year 2024. A clinician with fewer than 11 patients for the code is hidden by CMS, so small volumes do not appear.","lens":null,"layouts":{"rep":["top","groups","map","stats"], ...}},"children":["top","stats","map","split","groups"]}}

event: patch
data: {"op":"add","path":"/elements/stats","value":{"type":"Stat","props":{"title":"TAVR, Medicare volume","sql":"SELECT round(sum(services)) AS services, sum(providers) AS clinicians, round(sum(payment)) AS medicare_payment\nFROM rollup_hcpcs_state\nWHERE hcpcs_code = '33361' AND state IN ('FL')","x":null,"y":"services","format":"number","tag":"market","engine":"postgres"},"children":[]}}

event: say
data: {"text":"Matched TAVR (33361)"}

event: say
data: {"text":"Chose \"Top clinicians for a procedure\" at 94% in 369 ms"}

event: usage
data: {"credits":5,"creditsUsed":1989,"creditsLimit":5000,"txid":"12296"}

event: patch
data: {"op":"add","path":"/state/stats","value":{"columns":["services","clinicians","medicare_payment"],"rows":[{"services":6800,"clinicians":"214","medicare_payment":4206559}],"ms":202,"engine":"postgres","sources":["rollup_hcpcs_state"]}}

event: patch
data: {"op":"add","path":"/state/top","value":{"columns":["npi","name","specialty","city","state","services","patients"],"rows":[{"npi":"1234567893","name":"Jane Example","specialty":"Thoracic Surgery","city":"Melbourne","state":"FL","services":152,"patients":"152"}, ...],"ms":212,"engine":"postgres","sources":["medicare_provider","medicare_service"]}}

event: say
data: {"text":"Ranked the top 25 of 214 clinicians in FL"}

event: done
data: {"id":"f4b85ea7-00bd-4622-831d-aac31a7d22b3","tier":"instant","meta":{"v":2,"tier":"instant","kind":"ask","recipe":"proc_top_clinicians", ...},"ms":1373}
```

That answer had five tiles: twelve `patch` events, three `say` events and one each of `decision`, `usage` and `done`.

### Events of a planned answer

When no recipe is chosen, or `planner` is `true`, the planner answers.

| Event | Count | Data |
|---|---|---|
| `decision` | 1 | As above, with `tier: "planned"` and `recipe: null` |
| `say` | 1 | `No ready-made dashboard fits, so the planner is writing one` |
| `usage` | 1 | The [usage object](https://openpipe.health/docs/credits.md#the-usage-object), 25 credits. Sent once the model has a plan, so it can take several seconds. |
| `patch` | 1 per element | `/root`, the board, then tiles `t0`, `t1` and so on. Each tile's `sql` is an empty string at this point. |
| `say` | 1 | `Planned 3 tiles in 6.2 s` |
| `patch` | 2 per tile | `replace /elements/t0/props` with the tile's SQL filled in, then `add /state/t0` with its result or its error |
| `done` | 1 | `id`, `tier: "planned"`, `meta`, `ms` and `model` |
| `error` | 0 or 1 | As for an instant answer |

A planned tile that fails or is [withheld](https://openpipe.health/docs/api/ask.md#when-you-are-charged-and-what-is-stored) arrives as a state patch holding `error`. There is no separate `tile_error` event.

### Building the spec from patches

Start with `{ "root": "", "elements": {}, "state": {} }` and apply each `patch` in order. A patch is one [RFC 6902](https://www.rfc-editor.org/rfc/rfc6902) operation with `op` (`add`, `replace` or `remove`), `path` and, except for `remove`, `value`.

| Path | Holds |
|---|---|
| `/root` | The id of the board element |
| `/elements/<id>` | The board (`type: "Board"`) or one tile |
| `/state/<tile id>` | That tile's result |

The board's `props` are `title`, `summary`, `lens` and `layouts`. Its `children` are the tile ids in default order. `layouts` gives the tile order for each role, most important first.

A tile's `type` is `Stat`, `Leaderboard`, `StateMap`, `Bar`, `Line` or `Table`. They are drawn like the [tile types](https://openpipe.health/docs/api/ask.md#tile-types) of `POST /api/ask` (`StateMap` is `map` there). A dashboard holds at most 8 tiles. Tile `props`:

| Prop | Meaning |
|---|---|
| `title` | The tile's title |
| `sql` | The statement that computes the tile. A [receipt](https://openpipe.health/docs/receipts.md). Nothing accepts it back. |
| `x`, `y` | The label column and the numeric column. Both `null` on a `Table`. |
| `format` | `number`, `usd`, `percent` or `null`: how to display `y` |
| `tag` | Optional. What the tile is for: `people`, `accounts`, `market`, `segment`, `breakdown` or `intel` |
| `highlight` | Optional. State codes to mark on a map. |
| `engine` | Optional. The engine the recipe chose for the statement: `postgres` or `duckdb` |

A tile's state is one of two shapes:

```json
{ "columns": ["services", "clinicians"], "rows": [{ "services": 6800, "clinicians": "214" }], "ms": 202, "engine": "postgres", "sources": ["rollup_hcpcs_state"] }
```

```json
{ "error": "The query failed to run.", "sources": ["medicare_service"] }
```

A `Table` tile carries at most 50 rows and any other tile at most 100.

### The done event

| Field | Meaning |
|---|---|
| `id` | The stored dashboard. Pass it to [`/edit`](#change-a-dashboard), [`/predict`](#predict-the-next-dashboards), [`GET /api/ask2/d/:id`](#read-a-stored-answer), [`GET /api/dashboards/:id`](https://openpipe.health/docs/api/saved.md#open-a-dashboard) or an [export](https://openpipe.health/docs/api/exports.md#export-a-tile-of-an-answer). |
| `tier` | `instant` or `planned` |
| `ms` | Total time in milliseconds |
| `model` | Planned answers only: the model that wrote the plan |
| `meta.kind` | `ask`, `edit` or `predicted` |
| `meta.recipe`, `meta.params` | The recipe id and the parameters it was built with. Both `null` on a planned answer. |
| `meta.lens` | The role the board was laid out for, or `null` |
| `meta.parent` | The dashboard this one followed from, or `null` |
| `meta.decision` | The `decision` event again |
| `meta.timings` | `match`, `decide`, `decideCached`, `queries` (per tile: `id`, `title`, `ms`, `engine`, `rows`), `firstTile` and `total`. Also `ledger` on an instant answer and `plan` on a planned one. |
| `meta.narration` | Every `say` line, in order |
| `meta.followups` | Suggested next steps: `{ "text": "…", "kind": "edit" }` to send to [`/edit`](#change-a-dashboard), `{ "text": "…", "kind": "ask" }` to send to `/ask` |

### How a recipe is chosen

1. Entities are matched in the question: a procedure, drug, specialty, company, hospital, group, clinician, states, a city.
2. The recipes that can be built from those entities are the candidates. With no candidate, the question goes to the planner.
3. A short question is decided by rule, from the role: it names a subject, has at most 7 words, leaves no word unmatched, matches no recipe's cue words and is not phrased as a question ("which", "how", "compare" and similar). With no role, or as `rep` or `bizdev`, it gets the ranked list. Other roles get a market view. `unsure` is `true` for these.
4. Otherwise the decision model gives each candidate, and `none`, a probability. The top recipe is used at 0.5 or more. It is also used at 0.3 or more when the cue words pick the same recipe and `none` is under 0.4. When words in the question matched nothing (three or more with a subject, any without one), the top recipe needs 0.8.
5. If the decision model does not answer within 900 ms, the recipes' cue words decide.

After a model decision, `unsure` is `true` when no recipe was chosen, when the top probability is under 0.55, or when it is under 0.7 with a lead of less than 0.3 over the runner-up.

### Retrying with `rid`

Send the same `rid` when you retry a request. If an answer with that `rid` finished in the last 5 minutes, the response is plain JSON and nothing runs:

```json
{ "id": "f4b85ea7-00bd-4622-831d-aac31a7d22b3", "replay": true, "charged": false }
```

Things to know:

- **A replay is free and is not rate limited** by the 60 a minute below.
- **Only a finished, stored answer is replayed.**
- **A retry that arrives while the first request is still running gets `409` with `code: "IN_PROGRESS"`** and is not charged. The same applies to `/edit`.
- **`rid` is matched per workspace, and nothing else about the request is compared.** `/ask` and `/edit` share the same ids, so use a new `rid` for each new request.
- **The record is kept in the server's memory.** It does not survive a restart.

### When you are charged, and what is stored

For an instant answer:

1. **Checks before any work.** The `rid` replay, then the rate limit (`429`), then the balance must cover 5 credits (`402`).
2. **The spec is sent and every tile's statement starts at once.** Nothing is charged yet.
3. **The workspace is charged 5 credits, once, when the first tile has a result.** The `usage` event follows, then the rows.
4. **One dashboard is stored** and `done` carries its `id`.

Things to know:

- **Nothing is charged if you disconnect before the charge.** Nothing is stored either. After the charge the answer is finished and stored whether or not you are still connected.
- **Nothing is charged if every tile fails.** The stream sends each tile's error, then an `error` event with `code: "ALL_TILES_FAILED"`. Nothing is stored.
- **One failed tile among others is still charged.** Its state holds `error`.
- **If the balance was spent between the check and the charge**, the stream ends with an `error` event carrying `status: 402`. No row is sent and nothing is stored.

For a planned answer the rules are those of [`POST /api/ask`](https://openpipe.health/docs/api/ask.md#when-you-are-charged-and-what-is-stored): 25 credits, charged once when the model has a plan and before any tile runs, and nothing if no plan can be made. One difference: if you have disconnected by the time the plan is ready, nothing is charged, no tile runs and nothing is stored.

### Asking with an API key

A key has no [onboarding profile](https://openpipe.health/docs/api/profile.md), so there is no role and no territory. Pass `as` to get a role's layout. Name the states in the question to get a territory.

### Limits

| Applies to | Limit | Counted per |
|---|---|---|
| `/api/ask2/ask` and `/api/ask2/edit` together | 60 per minute | Workspace |
| Questions that reach the planner, together with `POST /api/ask` and the MCP `ask` tool | 10 per minute | Workspace |

A question that reaches the planner counts against both. These sit on top of the [general limits](https://openpipe.health/docs/api/errors.md#rate-limits).

### Errors

These arrive as an ordinary JSON error, before the stream starts:

| Status | Message |
|---|---|
| `400` | `Body must be {"question": "..."} with at least 5 characters.` |
| `409` | `{ "error": "This request is still being answered. …", "code": "IN_PROGRESS", "charged": false }` when the same `rid` is sent again before its answer has finished. Nothing runs and nothing is charged; retry in a few seconds to get the stored answer. |
| `402` | `Out of credits: …` The check is for 5 credits when a recipe was chosen and 25 when the planner will answer. |
| `429` | `Too many questions. Try again in 23s.` (the 60) or `Too many planned questions. Try again in 23s.` (the 10). `code` is `RATE_LIMITED`. |

### Errors inside the stream

Once the stream has started, the HTTP status is already `200`. A failure arrives as one `error` event and the stream ends:

| Data | Meaning |
|---|---|
| `{ "error": "None of the tiles could be computed, so nothing was charged.", "code": "ALL_TILES_FAILED" }` | Instant answers. Nothing was charged or stored. |
| `{ "error": "The model could not plan …", "code": "ASK_FAILED", "charged": false }` | Planned answers. No plan could be made. Nothing was charged or stored. |
| `{ "error": "Out of credits: …", "status": 402 }` | The balance was spent between the first check and the charge. Nothing was charged. |
| `{ "error": "The answer could not be finished." }` | An unexpected failure |

## Change a dashboard

```http
POST /api/ask2/edit
```

A follow-up on a stored dashboard: change a filter, drop a tile, switch the view. Costs 5 credits when it can be done from a recipe. Costs 25 credits when the planner has to answer. The response is a `text/event-stream` with the same events as [`/ask`](#ask-a-question).

### Body

```json
{ "dashboard": "f4b85ea7-00bd-4622-831d-aac31a7d22b3", "text": "only Texas", "rid": "docs-ask2-0002" }
```

| Field | Meaning |
|---|---|
| `dashboard` | Required. The `id` of a dashboard in this workspace. |
| `text` | Required. At least 2 characters after trimming. Anything past 300 characters is cut off. |
| `as` | Optional role, as for [preview](#preview-a-question) |
| `rid` | Optional request id. See [retrying with `rid`](#retrying-with-rid). |

```sh
curl -N "$OPH_API/api/ask2/edit" \
  -H "Authorization: Bearer $OPH_KEY" -H "Content-Type: application/json" \
  -d '{"dashboard": "f4b85ea7-00bd-4622-831d-aac31a7d22b3", "text": "only Texas"}'
```

```
event: decision
data: {"tier":"instant","recipe":{"id":"proc_top_clinicians","label":"Top clinicians for a procedure","flow":"list"},"confidence":null,"probabilities":[],"decidedBy":"rules","unsure":false, ...}

event: patch
data: {"op":"replace","path":"/elements/board/props/title","value":"Top clinicians for tAVR in Texas"}

event: patch
data: {"op":"replace","path":"/elements/stats/props/sql","value":"SELECT round(sum(services)) AS services, sum(providers) AS clinicians, round(sum(payment)) AS medicare_payment\nFROM rollup_hcpcs_state\nWHERE hcpcs_code = '33361' AND state IN ('TX')"}

event: patch
data: {"op":"replace","path":"/elements/map/props/highlight","value":["TX"]}

event: say
data: {"text":"Changed states: TX"}

event: say
data: {"text":"Kept 1 tile as they were, recomputing 4"}

event: usage
data: {"credits":5,"creditsUsed":2003,"creditsLimit":5000,"txid":"12355"}

event: patch
data: {"op":"add","path":"/state/stats","value":{"columns":["services","clinicians","medicare_payment"],"rows":[{"services":5297,"clinicians":"185","medicare_payment":3058738}],"ms":63,"engine":"postgres","sources":["rollup_hcpcs_state"]}}

event: done
data: {"id":"585dee73-f554-4cc4-8457-79395e4b6756","tier":"instant","meta":{"v":2,"tier":"instant","kind":"edit","recipe":"proc_top_clinicians","parent":"f4b85ea7-00bd-4622-831d-aac31a7d22b3", ...},"ms":446}
```

### What an edit does

The follow-up is read in one of four ways:

| Read as | When | Credits | `meta.kind` |
|---|---|---|---|
| An edit | The dashboard came from a recipe and the words change a filter, drop a tile or ask for a sibling view | 5 | `edit` |
| A new instant question | The text does not open with an edit word, names its own subject, and a recipe is a sure pick: a hospital, group or clinician profile, or 0.8 or more from the decision model | 5 | `ask` |
| A new planned question | The text does not open with an edit word, names its own subject, and three or more of its words matched nothing | 25 | `ask` |
| A planned follow-up | Anything else. The planner gets the first 300 characters of the dashboard's question together with the follow-up. | 25 | `edit` |

The edit words are `only`, `just`, `now`, `add`, `remove`, `also`, `without`, `same`, `but`, `and`, `exclude`, `filter`, `hide`, `drop`, `show the`, `rank by`, `sort by`, `in`, `for`, `with`, `not`, and `top` with a number alone.

Things to know:

- **An edit's patches apply to the spec you already hold.** They are the difference from the stored dashboard: `replace`, `add` and `remove` under `/elements`, and `remove /state/<id>` for a tile that is gone. Read the spec with [`GET /api/ask2/d/:id`](#read-a-stored-answer) if you do not hold it.
- **Only tiles whose SQL changed run again.** A kept tile gets no state patch. Keep the state you have for it.
- **A dashboard that did not come from a recipe always costs 25 to follow up.** That includes every answer from `POST /api/ask` and every planned answer. There is nothing to patch, so the planner writes a new one.
- **A new dashboard is stored each time.** The one you passed is left unchanged, and the new one's `meta.parent` points to it.
- **Charging follows [`/ask`](#when-you-are-charged-and-what-is-stored)**, by tier.

### Limits

The same counters as [`/ask`](#limits-1): 60 a minute per workspace shared with `/ask`, and 10 a minute for follow-ups that reach the planner.

### Errors

Before the stream starts:

| Status | Message |
|---|---|
| `400` | `Body must be {"dashboard": "<id>", "text": "..."}.` |
| `404` | `No answer with that id in this workspace.` A dashboard in another workspace answers the same. |
| `402` | `Out of credits: …` |
| `429` | `Too many questions. …` or `Too many planned questions. …` |

Inside the stream, the [same `error` events](#errors-inside-the-stream) as `/ask`.

## Predict the next dashboards

```http
POST /api/ask2/predict
```

Computes up to three likely next dashboards for a stored instant answer and holds them on the server. Free. It returns a token for each. No rows and no SQL are returned.

### Body

```json
{ "dashboard": "f4b85ea7-00bd-4622-831d-aac31a7d22b3" }
```

| Field | Meaning |
|---|---|
| `dashboard` | Required. The `id` of a dashboard in this workspace. |
| `as` | Optional role, as for [preview](#preview-a-question). It can change the order the candidates are ranked in. |

```sh
curl "$OPH_API/api/ask2/predict" \
  -H "Authorization: Bearer $OPH_KEY" -H "Content-Type: application/json" \
  -d '{"dashboard": "f4b85ea7-00bd-4622-831d-aac31a7d22b3"}'
```

```json
{
  "predictions": [
    {
      "token": "80a5d43d-…",
      "question": "Which group practices have the most clinicians performing tAVR in Florida?",
      "label": "Group practices for a procedure",
      "readyAt": "2026-12-05T13:19:18.801Z",
      "ms": 96,
      "expiresInSeconds": 300
    }
  ]
}
```

| Field | Meaning |
|---|---|
| `token` | Pass it to [`/open`](#open-a-predicted-dashboard). 68 characters. |
| `question` | The question the prediction answers |
| `label` | The recipe's label |
| `readyAt`, `ms` | When it finished computing, and how long that took |
| `expiresInSeconds` | Time left before the token stops working |

Things to know:

- **Only instant answers are predicted from.** For a planned answer, or one from `POST /api/ask`, the response is `{ "predictions": [] }`.
- **Predictions are recipes only.** They are the neighbours of the dashboard's recipe that can be built from the same entities. One whose lead tile came back empty or failed is left out.
- **A token lives for 5 minutes** from `readyAt`. Predictions are kept in the server's memory, at most 12 per workspace; the oldest are dropped first.
- **Asking again within 5 minutes returns the same tokens** and computes nothing. Predictions you have already opened are left out of the list.
- **A token belongs to the workspace and the signed-in person it was computed for.** With API keys, any key of the workspace can open it.
- **The call waits** until every prediction is computed. They run one after another.

### Limits

20 a minute per workspace.

### Errors

| Status | Message |
|---|---|
| `404` | `No answer with that id in this workspace.` |
| `429` | `Too many prediction requests. Try again in 23s.` |

## Open a predicted dashboard

```http
POST /api/ask2/open
```

Opens a prediction. Costs 5 credits. The workspace is charged, the dashboard is stored, and the rows computed earlier are returned as one JSON document. No query runs.

### Body

```json
{ "token": "80a5d43d-…" }
```

```sh
curl "$OPH_API/api/ask2/open" \
  -H "Authorization: Bearer $OPH_KEY" -H "Content-Type: application/json" \
  -d "{\"token\": \"$TOKEN\"}"
```

```json
{
  "id": "cbb5cc78-4f1c-463e-bcc0-a106715cac77",
  "question": "Which group practices have the most clinicians performing tAVR in Florida?",
  "spec": {
    "root": "board",
    "elements": { "board": { "type": "Board", "props": { "title": "Group practices performing tAVR in Florida" }, "children": ["groups", "top", "stats", "map", "split"] }, "groups": { "type": "Leaderboard", "props": { "title": "Group practices with the most clinicians performing it", "sql": "SELECT …" }, "children": [] } }
  },
  "state": {
    "stats": { "columns": ["services", "clinicians", "medicare_payment"], "rows": [{ "services": 6800, "clinicians": "214", "medicare_payment": 4206559 }], "ms": 64, "engine": "postgres", "sources": ["rollup_hcpcs_state"] }
  },
  "meta": {
    "v": 2, "tier": "instant", "kind": "predicted", "recipe": "proc_top_groups",
    "parent": "f4b85ea7-00bd-4622-831d-aac31a7d22b3",
    "narration": ["Predicted from your last question and computed ahead of time in 96 ms"],
    "followups": [{ "text": "Only orthopedic surgeons", "kind": "edit" }],
    "predictedReadyAt": "2026-12-05T13:19:18.801Z"
  },
  "usage": { "credits": 5, "creditsUsed": 2019, "creditsLimit": 5000, "txid": "12423" },
  "readyAt": "2026-12-05T13:19:18.801Z",
  "openMs": 178
}
```

| Field | Meaning |
|---|---|
| `id` | The stored dashboard |
| `spec` | The finished spec: `root` and `elements`, as [built from patches](#building-the-spec-from-patches) |
| `state` | Every tile's result, keyed by tile id |
| `meta` | As in the [done event](#the-done-event), with `kind: "predicted"` and `predictedReadyAt` |
| `usage` | The [usage object](https://openpipe.health/docs/credits.md#the-usage-object) for this call |
| `readyAt` | When the rows were computed. They are not recomputed on open. |
| `openMs` | Time this call took |

Opening the same token again is free and returns only a pointer to the stored dashboard:

```json
{ "id": "cbb5cc78-4f1c-463e-bcc0-a106715cac77", "replay": true, "charged": false }
```

Two opens of one token at the same moment share one charge and one stored dashboard.

### Errors

| Status | Message |
|---|---|
| `404` | `That prediction has expired. Ask the question instead.` Also the answer for an unknown token, a token longer than 100 characters, and a token computed for another workspace or person. |
| `402` | `Out of credits: …` Nothing was charged. The token can be opened again until it expires. |

## Read a stored answer

```http
GET /api/ask2/d/:id
```

Returns the UI spec and the build record of a stored dashboard. Free. It returns no rows: get those from [`GET /api/dashboards/:id`](https://openpipe.health/docs/api/saved.md#open-a-dashboard).

```sh
curl "$OPH_API/api/ask2/d/f4b85ea7-00bd-4622-831d-aac31a7d22b3" \
  -H "Authorization: Bearer $OPH_KEY"
```

```json
{
  "id": "f4b85ea7-00bd-4622-831d-aac31a7d22b3",
  "question": "top TAVR operators in Florida",
  "ui": { "root": "board", "elements": { "board": { "type": "Board", "props": { "title": "Top clinicians for tAVR in Florida" }, "children": ["top", "stats", "map", "split", "groups"] } } },
  "meta": { "v": 2, "tier": "instant", "kind": "ask", "recipe": "proc_top_clinicians", "parent": null }
}
```

| Field | Meaning |
|---|---|
| `ui` | The spec: `root` and `elements`, with every tile's SQL |
| `meta` | As in the [done event](#the-done-event). `null` for a dashboard that was not made through `/api/ask2`. |

A dashboard made by `POST /api/ask` has no stored spec. One is laid out from its first 8 tiles, with tile ids `t0`, `t1` and so on.

### Errors

| Status | Message |
|---|---|
| `404` | `No answer with that id in this workspace.` Also the answer for an id that is not a UUID and for a dashboard in another workspace. |

## Recipes, prices and limits

```http
GET /api/ask2/about
```

Lists the recipes and the numbers on this page, read from the running server. Free.

```sh
curl "$OPH_API/api/ask2/about" -H "Authorization: Bearer $OPH_KEY"
```

```json
{
  "recipes": [
    { "id": "proc_top_clinicians", "label": "Top clinicians for a procedure", "flow": "list" },
    { "id": "hospital_profile", "label": "Hospital profile", "flow": "account" },
    { "id": "proc_market_by_state", "label": "Procedure market by state", "flow": "market" }
  ],
  "thresholds": { "instant": 0.5, "unsureBelow": 0.7 },
  "credits": { "instant": 5, "planned": 25, "preview": 0, "predict": 0, "openPredicted": 5 },
  "limits": { "previewPerMinute": 300, "previewModelPerMinute": 150, "instantPerMinute": 60, "plannedPerMinute": 10, "predictPerMinute": 20 }
}
```

`recipes` is trimmed here. `flow` is `list` (a ranking of people or accounts), `account` (one hospital, group or clinician) or `market` (size and spread). Pass a recipe's `id` as `pin` to [`/ask`](#ask-a-question).
