> 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/run-workflows-end-to-end.md).

# Run workflows end to end

#### Pick the execution interface

Use `/v2/runs` for persisted asynchronous run creation, list/detail reads, cancellation, and ask-human resume. Use `/inference/v0/run/{org_id}/{flow_id}` when your integration needs the legacy inline JSON or SSE response contract. These interfaces have different bodies, states, and version selectors.

| Selection         | v2 run body `project_version` | IO schema query `version`                  | Eval experiment `project_version_id` |
| ----------------- | ----------------------------- | ------------------------------------------ | ------------------------------------ |
| Current published | Omit or null                  | Inspect the known published version number | Use the selected saved number        |
| Draft             | `-1`                          | `draft`                                    | `draft`                              |
| Saved snapshot    | Nonnegative integer           | Nonnegative integer                        | Nonnegative integer                  |
| Newest saved      | No `latest` literal           | `latest` (default)                         | No `latest` literal                  |

Do not confuse newest saved with published. Draft access is permission-dependent and unsuitable for a reproducible production integration. The legacy inference query uses an integer `version`: omission or `-1` selects the latest published version. In v2, `-1` selects the draft instead. Do not copy that value between the two interfaces.

#### A bounded polling client

This Python example assumes `httpx` is installed. It starts exactly one run and never retries the POST automatically. Replace the example input key with the discovered contract.

```python
import os
import time
import httpx

base = os.environ.get("STACKAI_BASE_URL", "https://api.stack-ai.com").rstrip("/")
headers = {"Authorization": f"Bearer {os.environ['STACKAI_API_KEY']}"}
with httpx.Client(base_url=base, headers=headers, timeout=30) as client:
    response = client.post("/v2/runs", json={
        "project_id": os.environ["PROJECT_ID"],
        "input": {"in-0": "Summarize our refund policy"},
        "project_version": int(os.environ["PROJECT_VERSION"]),
    })
    response.raise_for_status()
    run_id = response.json()["data"]["run_id"]
    print("Save this run ID:", run_id)
    deadline = time.monotonic() + 300
    while time.monotonic() < deadline:
        response = client.get(f"/v2/runs/{run_id}")
        response.raise_for_status()
        run = response.json()["data"]
        if run["status"] == "succeeded":
            print(run["output"])
            break
        if run["status"] in {"failed", "cancelled"}:
            raise RuntimeError(f"Run {run_id}: {run['status']}; {run.get('error')}")
        if run["status"] == "paused":
            print("Human input required; retain the run ID and render the prompt securely.")
            break
        time.sleep(2)
    else:
        raise TimeoutError(f"Polling deadline reached; inspect existing run {run_id}")
```

A client timeout does not cancel the run. Add bounded retry logic for safe GETs in production. Store the run ID before polling so a process restart can resume observing the same execution.

#### Human-in-the-loop

GET the run. When paused, `data.pending_input` contains the question, expected response type, optional choices, resume token, and token expiry if the caller can both read and resume. A null `pending_input` does not prove the run has no pause; the caller may lack `projects.run`.

Submit the actual human answer:

```json
{
  "resume_token": "TOKEN_FROM_PENDING_INPUT",
  "response": "THE_HUMAN_ANSWER",
  "response_type": "text"
}
```

POST this body to `/v2/runs/{run_id}/resume`, then poll the Location URL. The 202 acknowledges resume acceptance. Match `response_type` to the prompt (`text`, `approval`, or `choice`); do not invent choices. Keep the token secret, do not log it, and do not reuse it for a later pause. Token expiry is distinct from the pause timeout. Only supported ask-human pauses/backends can be resumed here; 409 means the current state is incompatible.

#### Cancellation

POST `/v2/runs/{run_id}/cancel` using the actor type and identity that started the run. Being an administrator or using a session for the same person is not automatically equivalent to the originating personal-key actor. A 404 can conceal inaccessible or non-owned runs. A 202 acknowledges the request; poll until terminal. Cancellation cannot undo side effects already performed by tools.


---

# 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/run-workflows-end-to-end.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.
