> For the complete documentation index, see [llms.txt](https://docs.stackai.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.stackai.com/stackai-api/stackai-api-developer-guide/legacy-inference-streaming-and-analytics.md).

# Legacy inference, streaming, and analytics

#### Inline JSON

The legacy inference body is the input map itself, not the v2 `{project_id, input}` wrapper.

```bash
curl --fail-with-body -sS \
  "$STACKAI_BASE_URL/inference/v0/run/$ORG_ID/$PROJECT_ID" \
  -H "Authorization: Bearer $STACKAI_API_KEY" \
  -H 'Content-Type: application/json' \
  --data '{"in-0":"Summarize our refund policy"}'
```

`ORG_ID` must identify the key's organization. The project must be published for this public inference route. Inputs and outputs depend on the deployed flow; use its exported API example or IO contract. Inspect the result state instead of treating every HTTP 200 as completion.

#### Server-sent events

```bash
curl --fail-with-body -N -sS \
  "$STACKAI_BASE_URL/inference/v0/run/$ORG_ID/$PROJECT_ID?delta=false&prefix=true&verbose=true" \
  -H "Authorization: Bearer $STACKAI_API_KEY" \
  -H 'Accept: text/event-stream' \
  -H 'Content-Type: application/json' \
  --data '{"in-0":"Summarize our refund policy"}'
```

Parse SSE frames across arbitrary network chunks; a network read is not necessarily an entire JSON event. Inspect the response Content-Type before parsing, because errors may be JSON. Preserve the run identifier when available and handle terminal and paused states. A dropped stream does not prove the run failed. Avoid starting another execution just to reconnect. Disable buffering in your own reverse proxy as needed.

For background legacy execution, pass `execution_mode=remote` and omit the SSE Accept header. The 202 response supplies a run ID and WebSocket handle; use the returned handle, not a guessed URL. Poll `/inference/v0/runs/{org_id}/{run_id}` when streaming is unavailable.

#### Consume a stream in your application

For a standard SSE parser, request `prefix=true`. Request `verbose=true` to receive the run ID, state, and pause information. With `delta=false`, each output frame contains the latest complete output values: replace the displayed value rather than appending it. For example:

```bash
curl --fail-with-body -N -sS \
  "$STACKAI_BASE_URL/inference/v0/run/$ORG_ID/$PROJECT_ID?prefix=true&verbose=true&delta=false" \
  -H "Authorization: Bearer $STACKAI_API_KEY" \
  -H 'Accept: text/event-stream' \
  -H 'Content-Type: application/json' \
  --data '{"in-0":"Summarize our refund policy"}'
```

These illustrative frames show a growing answer followed by the completion marker. Optional progress and citation fields are omitted here:

```
data: {"outputs":{"out-0":"Eligible purchases"},"run_id":"5f4c3b2a-1111-4111-8111-123456789abc","metadata":{},"state":null}

data: {"outputs":{"out-0":"Eligible purchases can be returned within 30 days."},"run_id":"5f4c3b2a-1111-4111-8111-123456789abc","metadata":{},"state":"COMPLETED","error":null}

data: {"outputs":{"type":"stream_complete","message":"Stream completed successfully"},"run_id":"5f4c3b2a-1111-4111-8111-123456789abc","metadata":{"done":true},"state":"COMPLETED","error":null}

```

Read `state` and `error`, not the marker's message, to decide whether execution succeeded. A completion marker means that the stream ended; its state can also be `FAILED`, `CANCELLED`, or `PAUSED`. Do not display `outputs.type` or the marker's message as an answer. Save the last answer frame separately. For a pause, preserve `pause` securely on your backend and obtain the person's response before using the resume endpoint.

The following server-side generator parses frames across arbitrary network chunks. Call it from your application's authenticated backend route. Verify that the signed-in user may run the configured project before calling it; keep the API key and any resume token on the backend.

```python
import json
import os
import httpx

async def stream_answer(question, save_run, save_pause):
    base = os.environ["STACKAI_BASE_URL"].rstrip("/")
    path = f"/inference/v0/run/{os.environ['ORG_ID']}/{os.environ['PROJECT_ID']}"
    headers = {"Authorization": f"Bearer {os.environ['STACKAI_API_KEY']}",
               "Accept": "text/event-stream"}
    async with httpx.AsyncClient(base_url=base, timeout=60) as client:
        async with client.stream("POST", path, headers=headers,
                params={"prefix": "true", "verbose": "true", "delta": "false"},
                json={"in-0": question}) as response:
            response.raise_for_status()
            if "text/event-stream" not in response.headers.get("content-type", ""):
                raise RuntimeError("Expected a streaming response")
            data_lines = []
            completed = False
            async for line in response.aiter_lines():
                if line.startswith("data:"):
                    data_lines.append(line[5:].lstrip(" "))
                elif line == "" and data_lines:
                    event = json.loads("\n".join(data_lines))
                    data_lines = []
                    if event.get("run_id"):
                        await save_run(event["run_id"])
                    if (event.get("metadata") or {}).get("done"):
                        completed = True
                        yield {"type": "finished", "run_id": event.get("run_id"),
                               "state": event.get("state")}
                        break
                    if event.get("pause"):
                        await save_pause(event["run_id"], event["pause"])
                        # Keep its resume token out of browser events and logs.
                        yield {"type": "needs_input", "run_id": event.get("run_id")}
                    elif event.get("state") in {"FAILED", "CANCELLED"}:
                        yield {"type": "failed", "run_id": event.get("run_id")}
                    elif "out-0" in event.get("outputs", {}):
                        yield {"type": "answer", "text": event["outputs"]["out-0"],
                               "run_id": event.get("run_id")}
            if not completed:
                raise RuntimeError("Stream disconnected; inspect the saved run ID")
```

Implement `save_run` and `save_pause` using your application’s durable, access-controlled storage. The output ID and input key above must match your project. Send these normalized events to the browser through your application's own stream. The browser only needs to replace answer text for `answer`, show a waiting state for `needs_input`, and check the final state for `finished`. Render answer text as text, or sanitize any supported rich content; do not inject arbitrary HTML.

If your authenticated backend exposes these normalized events as newline-delimited JSON at `/api/answer`, a browser client can consume them as follows. The route must authenticate the user, authorize the configured project, call `stream_answer`, and send one JSON object followed by a newline for each yielded event. Do not pass arbitrary project IDs or API keys through from the browser.

```javascript
async function showAnswer(question, answerElement, statusElement) {
  const response = await fetch("/api/answer", {
    method: "POST",
    headers: {"Content-Type": "application/json"},
    body: JSON.stringify({question}),
    credentials: "same-origin",
  });
  if (!response.ok || !response.body) throw new Error("Could not start the answer");
  const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
  let pending = "";
  let finished = false;
  while (true) {
    const {value, done} = await reader.read();
    if (done) break;
    pending += value;
    let boundary;
    while ((boundary = pending.indexOf("\n")) !== -1) {
      const line = pending.slice(0, boundary);
      pending = pending.slice(boundary + 1);
      if (!line.trim()) continue;
      const event = JSON.parse(line);
      if (event.type === "answer") answerElement.textContent = event.text;
      if (event.type === "needs_input") statusElement.textContent = "Your response is needed";
      if (event.type === "failed") statusElement.textContent = "The request could not finish";
      if (event.type === "finished") {
        finished = true;
        statusElement.textContent = event.state === "COMPLETED" ? "Complete"
          : event.state === "PAUSED" ? "Your response is needed" : "The request did not complete";
      }
    }
  }
  if (!finished) statusElement.textContent = "Connection lost; check this request's saved status";
}
```

A disconnect is not a request to execute again. Retain the run ID and query `/inference/v0/runs/{org_id}/{run_id}` for its state. This API does not document replay from an SSE `Last-Event-ID`; do not rely on automatic browser reconnection to resume at the last token.

#### Legacy resume

POST the resume token and human response to `/inference/v0/runs/{org_id}/{run_id}/resume`. Inline JSON, SSE, and remote resume have different backend support. Trigger-backed runs reject SSE with 406; retry the resume interface without SSE only after checking the response/state, then poll. In-process runs reject `execution_mode=remote` with 409. An out-of-band response can say `RESUMED` with no outputs while execution continues. The legacy state vocabulary includes `COMPLETED`; v2 exposes `succeeded`.

#### Analytics exports

GET `/analytics/org/{org_id}/flows/{flow_id}` with a personal key or supported legacy private organization key. It returns a list, using zero-based `page` and optional `page_size`, `start_date`, `end_date`, `user_id`, and comma-separated `state`. Use timezone-qualified timestamps and ensure start is not after end. State values are `PENDING`, `RUNNING`, `PAUSED`, `RESUMED`, `COMPLETED`, `FAILED`, and `CANCELLED`.

For new run-history integrations, `/v2/runs` provides cursor pagination and lowercase statuses. A workflow result and a run-history record serve different purposes; logging controls can make run history unavailable.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.stackai.com/stackai-api/stackai-api-developer-guide/legacy-inference-streaming-and-analytics.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
