# Stream Ask in JavaScript

> Read the Ask event stream with fetch in a browser, Node, Bun or Deno.

Source: https://openpipe.health/docs/guides/stream-ask/

[`POST /api/ask`](https://openpipe.health/docs/api/ask.md) responds with server-sent events by default. If you do not need tiles as they arrive, skip this guide and use [JSON mode](https://openpipe.health/docs/api/ask.md#json-mode): one `fetch`, one `await res.json()`.

For the stream: The browser's `EventSource` cannot send a `POST` or an `Authorization` header, so read the stream with `fetch`.

## A minimal reader

```js
async function* ask(question, { base, token }) {
  const res = await fetch(`${base}/api/ask`, {
    method: 'POST',
    headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', accept: 'text/event-stream' },
    body: JSON.stringify({ question }),
  });
  if (!res.ok) throw new Error((await res.json()).error);

  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
  let buffer = '';
  for (;;) {
    const { value, done } = await reader.read();
    if (done) return;
    buffer += value;
    let end;
    while ((end = buffer.indexOf('\n\n')) !== -1) {
      const block = buffer.slice(0, end);
      buffer = buffer.slice(end + 2);
      let event = 'message';
      let data = '';
      for (const line of block.split('\n')) {
        if (line.startsWith('event:')) event = line.slice(6).trim();
        else if (line.startsWith('data:')) data += line.slice(5).trim();
      }
      if (data) yield { event, data: JSON.parse(data) };
    }
  }
}
```

## Use it

```js
const tiles = [];

for await (const { event, data } of ask('Which states do the most cataract surgeries?', {
  base: process.env.OPH_API,
  token: process.env.OPH_KEY,
})) {
  if (event === 'plan') {
    console.log(data.title, '-', data.summary);
    tiles.length = data.tiles.length; // reserve a slot per planned tile
  }
  if (event === 'tile') tiles[data.index] = data;
  if (event === 'tile_error') console.warn(`Tile ${data.index} failed: ${data.error}`);
  if (event === 'error') throw new Error(data.error);
  if (event === 'done') console.log(`${data.tiles - data.failed} of ${data.tiles} tiles in ${data.ms} ms, stored as dashboard ${data.id}`);
}
```

## Rendering advice

- **Show a waiting state until `usage`.** Nothing is sent while the model plans, which takes a few seconds. `usage` arrives when the plan exists and the workspace has been charged, with `plan` right behind it.
- **Draw placeholders from `plan`.** It has every tile's `type` and `title`, so you can lay out the dashboard before any data exists.
- **Place tiles by `index`.** They arrive in the order they finish, which is rarely the planned order.
- **Show `plan.summary`.** It carries the caveat for the answer, such as Medicare-only volumes.
- **Show the receipt.** Each tile has `tile.sql`, `sources` and `engine`. A "how this was computed" link costs you nothing and is why people trust the number. It is for reading: no endpoint takes SQL back.
- **Keep `done.id`.** It is the stored dashboard. Open it again for free with [`GET /api/dashboards/:id`](https://openpipe.health/docs/api/saved.md#open-a-dashboard), retry failed tiles with a free [refresh](https://openpipe.health/docs/api/saved.md#refresh-a-dashboard), and pass it to [exports](https://openpipe.health/docs/api/exports.md#export-a-tile-of-an-answer) for every row of a tile.
- **Handle the missing `done`.** If the connection drops or an `error` event arrives, `done` never comes. Stop your loading state when the stream closes. An `error` event with `charged: false` means no plan could be made and nothing was charged.
- **Do not ask again after a dropped connection.** The server finishes, charges and stores the answer whether or not you are still listening. Look for it in [`GET /api/dashboards`](https://openpipe.health/docs/api/saved.md#list-dashboards) first.

## In a browser

The same function works unchanged. Use the signed-in user's session token as `token`, not an API key: anything you ship to a browser is visible to its user.
