> ## Documentation Index
> Fetch the complete documentation index at: https://docs.camb.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# How Tasks & Runs Work

> Understand the asynchronous task pattern used across CAMB.AI APIs

Most CAMB.AI APIs use an **asynchronous task pattern** that allows your application to submit requests and continue working while processing happens in the background. This guide explains how tasks and runs work.

## The Task Lifecycle

<Steps>
  <Step title="Submit a Request">
    Send your data (text, audio, video) to a creation endpoint. The API immediately returns a `task_id`.
  </Step>

  <Step title="Poll for Status">
    Use the `task_id` to check progress. The task moves through states: `PENDING` → `SUCCESS` (or `ERROR`).
  </Step>

  <Step title="Get the Result">
    Once the status is `SUCCESS`, you receive a `run_id`. Use this to download your result.
  </Step>
</Steps>

```mermaid theme={null}
sequenceDiagram
    participant App as Your App
    participant API as CAMB.AI API

    App->>API: POST /tts (submit text)
    API-->>App: { task_id: "abc123" }

    loop Until SUCCESS
        App->>API: GET /tts/{task_id}
        API-->>App: { status: "PENDING" }
    end

    App->>API: GET /tts/{task_id}
    API-->>App: { status: "SUCCESS", run_id: "xyz789" }

    App->>API: GET /tts-result/{run_id}
    API-->>App: [audio data]
```

## Task vs Run

| Concept  | Description                    | ID        |
| -------- | ------------------------------ | --------- |
| **Task** | A job submitted for processing | `task_id` |
| **Run**  | The completed result of a task | `run_id`  |

A task represents your request being processed. Once complete, the result becomes a run that you can download or reference.

## Task Status Types

| Status             | Meaning                        | Action                         |
| ------------------ | ------------------------------ | ------------------------------ |
| `PENDING`          | Processing in progress         | Continue polling               |
| `SUCCESS`          | Completed successfully         | Retrieve result using `run_id` |
| `ERROR`            | Processing failed              | Check error message, retry     |
| `TIMEOUT`          | Processing exceeded time limit | Break into smaller requests    |
| `PAYMENT_REQUIRED` | Insufficient credits           | Add credits to account         |

## Example: Complete Workflow

Here's a complete example showing the task pattern for text-to-speech:

```python theme={null}
import requests
import time

API_KEY = "your-api-key"
BASE_URL = "https://client.camb.ai/apis"

headers = {
    "x-api-key": API_KEY,
    "Content-Type": "application/json"
}

# Step 1: Submit the task
response = requests.post(
    f"{BASE_URL}/tts",
    headers=headers,
    json={
        "text": "Hello, this is a test of the task system.",
        "voice_id": 147320,
        "language": "en-us"  # Locale tag. Numeric IDs (e.g. 1) still work but are deprecated.
    }
)
task_id = response.json()["task_id"]
print(f"Task submitted: {task_id}")

# Step 2: Poll for completion
while True:
    status_response = requests.get(
        f"{BASE_URL}/tts/{task_id}",
        headers=headers
    )
    status_data = status_response.json()
    status = status_data["status"]

    print(f"Status: {status}")

    if status == "SUCCESS":
        run_id = status_data["run_id"]
        break
    elif status in ["ERROR", "TIMEOUT", "PAYMENT_REQUIRED"]:
        print(f"Task failed: {status}")
        exit(1)

    time.sleep(2)  # Wait before polling again

# Step 3: Download the result
result_response = requests.get(
    f"{BASE_URL}/tts-result/{run_id}",
    headers=headers,
    stream=True
)

with open("output.wav", "wb") as f:
    for chunk in result_response.iter_content(chunk_size=1024):
        if chunk:
            f.write(chunk)

print(f"Audio saved! Run ID: {run_id}")
```

## Polling Best Practices

<AccordionGroup>
  <Accordion title="Use appropriate intervals">
    Start with 2-5 second intervals. Shorter tasks (TTS) complete faster than longer ones (dubbing).
  </Accordion>

  <Accordion title="Implement exponential backoff">
    For longer tasks, increase the polling interval over time to reduce API calls.
  </Accordion>

  <Accordion title="Set a maximum timeout">
    Don't poll forever. Set a maximum wait time and handle timeouts gracefully.
  </Accordion>

  <Accordion title="Handle all status types">
    Always handle `ERROR`, `TIMEOUT`, and `PAYMENT_REQUIRED` statuses in your code.
  </Accordion>
</AccordionGroup>

## Bulk Operations

For processing multiple items, use the bulk fetch endpoints:

```python theme={null}
# Fetch multiple results at once
response = requests.post(
    f"{BASE_URL}/fetch-tts-results",
    headers=headers,
    json={
        "run_ids": [123, 456, 789]
    }
)
results = response.json()
```

## APIs Using This Pattern

Most CAMB.AI APIs follow the task pattern:

| API            | Create                     | Status                              | Result                               |
| -------------- | -------------------------- | ----------------------------------- | ------------------------------------ |
| Text-to-Speech | `POST /tts`                | `GET /tts/{task_id}`                | `GET /tts-result/{run_id}`           |
| Translation    | `POST /translation`        | `GET /translation/{task_id}`        | `GET /translation-result/{run_id}`   |
| Transcription  | `POST /transcription`      | `GET /transcription/{task_id}`      | `GET /transcription-result/{run_id}` |
| Dubbing        | `POST /end-to-end-dubbing` | `GET /end-to-end-dubbing/{task_id}` | `GET /dubbed-run-info/{run_id}`      |
| Stories        | `POST /create-story`       | `GET /story/{task_id}`              | `GET /story-run/{run_id}`            |

## Streaming Alternative

For real-time applications, some APIs offer streaming endpoints that return data immediately without the task pattern:

* `POST /tts-stream` - Streaming text-to-speech
* `POST /translation/stream` - Deprecated streaming translation. Use `POST /translation` for new integrations.

Use streaming when you need immediate response and can process audio chunks as they arrive.

## Next Steps

<CardGroup cols={2}>
  <Card title="SDK Guide" icon="code" href="/sdk-guides/general-guide">
    SDKs handle polling automatically
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/endpoint/create-tts">
    Explore all endpoints
  </Card>
</CardGroup>
