# Predictions

Understanding async generation tasks — submit, poll, and retrieve results

Source: https://atlascloud.ai/docs/en/predictions

## What are Predictions?

When you submit an image or video generation request to Atlas Cloud, the task doesn't complete immediately. Instead, you receive a **prediction ID** that you can use to track the task's progress and retrieve the result when it's ready.

This asynchronous pattern is used for all non-LLM generation tasks (images, videos, etc.) because these tasks can take anywhere from a few seconds to several minutes to complete.

## Prediction Lifecycle

```
┌─────────┐     ┌────────────┐     ┌───────────┐
│ Submit   │ ──→ │ Processing │ ──→ │ Completed │
│ Task     │     │            │     │           │
└─────────┘     └────────────┘     └───────────┘
                      │
                      ▼
                ┌───────────┐
                │  Failed   │
                └───────────┘
```

**Status values:**
- `processing` — The task is being processed by the model
- `completed` — Generation is done, output is available
- `failed` — Generation failed, error details are available

## Submit a Task

### Image Generation

```python
import requests

response = requests.post(
    "https://api.atlascloud.ai/api/v1/model/generateImage",
    headers={
        "Authorization": "Bearer your-api-key",
        "Content-Type": "application/json"
    },
    json={
        "model": "google/nano-banana-2/text-to-image",
        "prompt": "A beautiful mountain landscape at golden hour"
    }
)

data = response.json()
prediction_id = data["data"]["id"]
print(f"Task submitted: {prediction_id}")
```

### Video Generation

```python
response = requests.post(
    "https://api.atlascloud.ai/api/v1/model/generateVideo",
    headers={
        "Authorization": "Bearer your-api-key",
        "Content-Type": "application/json"
    },
    json={
        "model": "kling-v2.0",
        "prompt": "Ocean waves crashing on a rocky shore at sunset"
    }
)

data = response.json()
prediction_id = data["data"]["id"]
```

## Poll for Results

Use the prediction ID to check the task status and retrieve the output:

```python
import requests
import time

def wait_for_result(prediction_id, api_key, interval=5, timeout=300):
    """Poll for generation result with timeout."""
    url = f"https://api.atlascloud.ai/api/v1/model/prediction/{prediction_id}"
    elapsed = 0
    while elapsed < timeout:
        response = requests.get(
            url,
            headers={"Authorization": f"Bearer {api_key}"}
        )
        result = response.json()
        status = result["data"]["status"]

        if status == "completed":
            return result["data"]["outputs"][0]
        elif status == "failed":
            raise Exception(f"Generation failed: {result['data'].get('error')}")

        print(f"Status: {status} ({elapsed}s elapsed)")
        time.sleep(interval)
        elapsed += interval

    raise TimeoutError(f"Task did not complete within {timeout}s")

# Usage
output = wait_for_result("your-prediction-id", "your-api-key")
print(f"Result: {output}")
```

### Node.js Example

```javascript
async function waitForResult(predictionId, apiKey, interval = 5000, timeout = 300000) {
  const startTime = Date.now();

  while (Date.now() - startTime < timeout) {
    const response = await fetch(
      `https://api.atlascloud.ai/api/v1/model/prediction/${predictionId}`,
      { headers: { Authorization: `Bearer ${apiKey}` } }
    );
    const result = await response.json();
    const status = result.data.status;

    if (status === "completed") return result.data.outputs[0];
    if (status === "failed") throw new Error(`Failed: ${result.data.error}`);

    console.log(`Status: ${status}`);
    await new Promise((r) => setTimeout(r, interval));
  }

  throw new Error("Timeout");
}

const output = await waitForResult("your-prediction-id", "your-api-key");
console.log(`Result: ${output}`);
```

### cURL Example

```bash
curl "https://api.atlascloud.ai/api/v1/model/prediction/your-prediction-id" \
  -H "Authorization: Bearer your-api-key"
```

## Response Format

```json
{
  "data": {
    "id": "prediction-id",
    "status": "completed",
    "outputs": ["https://...output-url..."],
    "error": null
  }
}
```

## Query Task Statuses in Bulk

`GET /public/v1/tasks` lists recorded generation tasks, including Enterprise model tasks. You can browse tasks with pagination and filters, or pass prediction IDs to query a known set. Completed tasks include available `outputs`. See the [complete API reference](/public-api/tasks).

### Pagination and filters

Use an ordinary model API key (`apikey-...`) in the `Authorization` header. Management keys (`mgmt-...`) cannot call this endpoint. The API key fixes the account; only tasks you can currently read are listed and counted.

```bash
curl --get "https://api.atlascloud.ai/public/v1/tasks" \
  -H "Authorization: Bearer apikey-..." \
  --data-urlencode "page_num=1" \
  --data-urlencode "page_size=20" \
  --data-urlencode "filter.model=bytedance/seedance-2.0/text-to-video" \
  --data-urlencode "filter.status=completed"
```

| Parameter | Meaning |
| --- | --- |
| `page_num` | Page number, default `1`; range `1`–`500`. |
| `page_size` | Tasks per page, default `20`; range `1`–`500`. |
| `filter.model` | Optional exact Atlas Cloud model ID, not a provider endpoint ID; at most 256 UTF-8 bytes. |
| `filter.status` | Optional status from the table below. |
| `filter.task_ids` | Optional task IDs, repeated once per ID; at most 100 entries before deduplication. |

All filters are combined with AND. Omit task IDs to browse your visible tasks. Results are ordered by creation time, newest first, with stable ties. `total` counts all visible tasks matching the filters, before pagination. Task creation, deletion and status changes can affect later pages; pages are not a fixed snapshot across requests.

### Query specific IDs

```bash
curl --get "https://api.atlascloud.ai/public/v1/tasks" \
  -H "Authorization: Bearer apikey-..." \
  --data-urlencode "filter.task_ids=task-1" \
  --data-urlencode "filter.task_ids=task-2" \
  --data-urlencode "filter.task_ids=task-3"
```

Use the prediction IDs returned when submitting generation requests. Each ID must contain 1–128 ASCII letters, digits, dots, underscores, colons or hyphens. IDs are deduplicated case-insensitively; split sets larger than 100 into separate requests. Empty values and comma-separated IDs are rejected.

**Existing `task_ids[]` requests remain supported.** If repeated `task_ids[]` is the only parameter, all requested visible tasks are returned in first-requested order, with `page_num: 1` and `page_size: 100`. Adding pagination or filter parameters uses normal list pagination and ordering. Do not combine `task_ids[]` with `filter.task_ids`.

The raw query string is limited to 48 KiB. Unknown parameters, `scope`, service-tier filters, and duplicate scalar parameters return HTTP 400.

### Response

Example for the ID query above:

```json
{
  "object": "list",
  "total": 2,
  "page_num": 1,
  "page_size": 20,
  "items": [
    {
      "id": "task-1",
      "model": "bytedance/seedance-2.0/text-to-video",
      "status": "completed",
      "created_at": 1794898800000,
      "updated_at": 1794898860000,
      "error": null,
      "outputs": ["https://example.com/generated-video.mp4"]
    },
    {
      "id": "task-2",
      "model": "bytedance/seedance-2.0/text-to-video",
      "status": "timeout",
      "created_at": 1794898700000,
      "updated_at": 1794899100000,
      "error": {"code": 0, "message": "Task timed out"},
      "outputs": []
    }
  ],
  "not_found": ["task-3"],
  "request_id": "req_example"
}
```

`not_found` contains supplied IDs that are missing, inaccessible, cross-account or deleted. IDs excluded only by model/status filters or pagination are **not** in `not_found`. Without an ID filter, this array is empty. Missing IDs keep their first requested spelling and order; returned `items[].id` uses the stored spelling. A successful query returns HTTP 200 even if some or all requested IDs are missing. Empty arrays are `[]`.

`created_at` and `updated_at` are **Unix milliseconds**. `updated_at` is the latest stored update associated with the task, not necessarily a status change or the time of this query.

### Results and expiry

`outputs` contains available results of completed tasks. It is empty while results are not ready, when content or files have expired, or when no results are retained. A private output whose link cannot currently be resolved is an empty string at its original array index. Download results before their URLs expire.

Naturally expired tasks may retain queryable status metadata, but this never restores their prompts or outputs. User-deleted tasks are not listed. This endpoint does not return prompts or raw provider errors.

### Statuses and polling

| Status | Meaning | Continue polling? |
| --- | --- | --- |
| `created` | Task created | Yes |
| `queued` | Waiting to run | Yes |
| `processing` | Running | Yes |
| `completed` | Generation recorded as completed | Check `outputs` availability |
| `failed` | Failed | No; inspect `error` |
| `timeout` | The platform timed out waiting for the task | No; inspect `error` |
| `unknown` | Status cannot yet be determined | Yes |

`error` contains a public numeric `code` and `message` for failed or timed-out tasks; it is `null` for other statuses. A code of `0` means no code was recorded. Task failure is returned inside a successful HTTP 200 query. Request failures use `{ "error": { "type": "...", "code": "...", "message": "..." }, "request_id": "..." }`; HTTP 429 may include `Retry-After`.

This endpoint reads recorded state without refreshing the provider, advancing generation or settling billing. State can lag, and a recorded `completed` task may still have unavailable outputs. Use [`GET /api/v1/model/prediction/{id}`](#poll-for-results) for the individual prediction result and its delivery readiness. Set a polling interval and client timeout; more frequent list queries do not force a refresh.

## Polling Best Practices

- **Start with longer intervals**: Use 5-second intervals for video generation, 2-second intervals for image generation
- **Set a timeout**: Always set a maximum wait time to avoid infinite polling
- **Handle failures gracefully**: Check for `failed` status and handle errors appropriately
- **Log progress**: Print status updates so users know the task is still running

## Typical Generation Times

| Task Type | Typical Time |
| --- | --- |
| Image generation | 2–10 seconds |
| Video generation | 30 seconds – 3 minutes |
| Image-to-video | 30 seconds – 3 minutes |
| Image tools (upscale, etc.) | 5–15 seconds |

Actual times vary depending on the model, parameters (resolution, duration), and current load.

## Error Handling

When a prediction fails, the result includes an error message:

```json
{
  "data": {
    "id": "prediction-id",
    "status": "failed",
    "error": "Invalid parameter: resolution not supported by this model",
    "outputs": []
  }
}
```

Common failure reasons:
- Invalid model parameters
- Input image URL is inaccessible
- Prompt contains disallowed content
- Insufficient account balance

See the [API Reference](/openapi-index) for full error code documentation.
