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

# Workflows (workflow_v3) - BETA

> [!NOTE]
>
> The `workflow_v3` interface is in BETA and may change before it becomes stable. It requires version 0.2.0 or later of the `encord` SDK, and is imported from `encord.beta.workflow_v3`.

`project.workflow_v3` gives you read access to a Project's complete Workflow graph, including its stages, pathways, and selected settings. It also lets you list tasks, assign and release manual work, and submit Annotation, Review, and External tasks.

`workflow_v3` is not available for every Project. Before you use it, check `project.has_workflow_v3`. Accessing `project.workflow_v3` on a Project that does not support it raises `EncordException`.

> [!TIP]
>
> `project.workflow` and `project.workflow_v3` are separate interfaces with different classes. A Project can support one or both, so check `project.has_workflow` and `project.has_workflow_v3` independently. For `project.workflow`, see [Workflows and Stages](https://docs.encord.com/sdk-documentation/projects-sdk/sdk-workflows-stages.md). Task classes such as `AnnotationTask` in `encord.beta.workflow_v3` are not the same as the `encord.workflow` classes of the same name.

## Key Concepts

| Concept | Description |
| - | - |
| **Stage** | A step in the Workflow, such as Start, Annotation, Review, External, a router, or a terminal stage such as Complete. |
| **Pathway** | A connection from one stage to another. Pathways define where work can move next. |
| **Task** | The work on one target (for example, one data unit) at one stage. Each time a target enters a stage, a new task is created. |
| **Snapshot** | The Workflow graph loads with the Project, as a snapshot. Reading stages, pathways, and settings makes no further requests. Listing tasks and acting on tasks makes separate requests. |

## Inspect a Workflow

The following example lists every stage in a Project's Workflow, and where each stage's pathways lead.

`get_stage()` accepts either a `name` or an `id`, but not both. Names must match exactly. If two stages have the same name, use the stage ID. Pass `type_` to check the stage's class, for example `type_=ExternalStage`.

```python Inspect a Workflow theme={"dark"}
# Import dependencies
from encord.user_client import EncordUserClient

# User input
SSH_PATH = "/Users/chris-encord/ssh-private-key.txt"  # Replace with the file path to your SSH private key
PROJECT_ID = "00000000-0000-0000-0000-000000000000"  # Replace with the unique Project ID

# Create user client using SSH key
user_client: EncordUserClient = EncordUserClient.create_with_ssh_private_key(
    ssh_private_key_path=SSH_PATH,
    # For US platform users use "https://api.us.encord.com"
    domain="https://api.encord.com",
)

# Load the Project. get_project() and list_projects() load the Workflow graph.
project = user_client.get_project(PROJECT_ID)
if not project.has_workflow_v3:
    raise ValueError("workflow_v3 is not available for this Project.")

workflow = project.workflow_v3

# List every stage and the stages its pathways lead to
for stage in workflow.stages:
    print(f"{stage.name} ({type(stage).__name__}, {stage.id})")
    for pathway in stage.pathways:
        destination = workflow.get_stage(id=pathway.destination_stage_id)
        print(f"  -> {destination.name} via '{pathway.name}' ({pathway.verdict.name})")
```

`workflow.pathways` holds every pathway in the Workflow, and `stage.pathways` holds a stage's outgoing pathways. Each pathway has a `source_stage_id`, a `destination_stage_id`, a `verdict`, and an optional `name`. Pathway names do not have to be unique.

To read the latest Workflow, call `project.refetch_data()` and read `project.workflow_v3` again. Objects you read earlier keep their original values.

### Read Stage Settings

Each stage has a `settings` object. Settings classes are in `encord.beta.workflow_v3.settings`, and each class name ends with its version, for example `ReviewStageSettingsV1`. Currently, only Percentage Router stages expose settings: `pathway_probabilities` maps each pathway ID to the fraction of tasks sent down that pathway (`0.25` means 25%). Worker restrictions and Collaborator Router rules are not available.

```python Read Percentage Router settings theme={"dark"}
# Import dependencies
from encord.beta.workflow_v3 import PercentageRouterStage
from encord.beta.workflow_v3.settings import PercentageRouterStageSettingsV1
from encord.user_client import EncordUserClient

# User input
SSH_PATH = "/Users/chris-encord/ssh-private-key.txt"  # Replace with the file path to your SSH private key
PROJECT_ID = "00000000-0000-0000-0000-000000000000"  # Replace with the unique Project ID
ROUTER_NAME = "Routing"  # Replace with the name of your Percentage Router stage

# Create user client using SSH key
user_client: EncordUserClient = EncordUserClient.create_with_ssh_private_key(
    ssh_private_key_path=SSH_PATH,
    # For US platform users use "https://api.us.encord.com"
    domain="https://api.encord.com",
)

project = user_client.get_project(PROJECT_ID)
workflow = project.workflow_v3

router = workflow.get_stage(name=ROUTER_NAME, type_=PercentageRouterStage)
if not isinstance(router.settings, PercentageRouterStageSettingsV1):
    raise ValueError("Upgrade the encord package to read this router's settings.")

for pathway in router.pathways:
    print(f"{pathway.name}: {router.settings.pathway_probabilities[pathway.id]:.0%}")
```

### Unfamiliar Stages and Values

If the Workflow contains a stage or target type that your version of the SDK does not recognize, it loads as `UnknownStage` or `UnknownTarget`, with the original type in `raw_stage_type` or `raw_target_type`. Unfamiliar settings versions load as `UnknownStageSettings`. Use `to_dict()` to inspect their configuration. Unrecognized enum values become `UNKNOWN`. Upgrade the `encord` package to use these capabilities.

## List Tasks

`stage.get_tasks()` returns the current tasks at a stage that you can see. Historical tasks are not returned. Each task has an `id`, a `target`, a `status`, a `priority`, timestamps, and an optional `assignment`.

* By default, tasks are sorted by descending priority, then by creation time. Pass `sort=TaskSort.CREATED_AT` to list the oldest tasks first.
* Pass `statuses` to list only tasks with specific statuses.
* Terminal stages, such as Complete, list the newest tasks first, and do not accept `statuses` or `sort`.
* Tasks load page by page as you iterate, so errors can occur during iteration. The queue can change between pages.

A task's target is usually a `DataUnitTarget`, which has a `data_hash` and a `dataset_hash`. Other targets represent data unit slices, Datasets, Data Group subsets, or Dataset subsets, and do not all have a `data_hash`.

```python List tasks at a stage theme={"dark"}
# Import dependencies
from encord.beta.workflow_v3 import DataUnitTarget, ExternalStage, TaskSort, TaskStatus
from encord.user_client import EncordUserClient

# User input
SSH_PATH = "/Users/chris-encord/ssh-private-key.txt"  # Replace with the file path to your SSH private key
PROJECT_ID = "00000000-0000-0000-0000-000000000000"  # Replace with the unique Project ID
STAGE_NAME = "External processing"  # Replace with the name of your stage

# Create user client using SSH key
user_client: EncordUserClient = EncordUserClient.create_with_ssh_private_key(
    ssh_private_key_path=SSH_PATH,
    # For US platform users use "https://api.us.encord.com"
    domain="https://api.encord.com",
)

project = user_client.get_project(PROJECT_ID)
workflow = project.workflow_v3
stage = workflow.get_stage(name=STAGE_NAME, type_=ExternalStage)

# List the current tasks at the stage, highest priority first
for task in stage.get_tasks():
    print(task.id, task.status.name, task.priority)
    if isinstance(task.target, DataUnitTarget):
        print(f"  Data unit {task.target.data_hash} in Dataset {task.target.dataset_hash}")

# List only the tasks that failed processing, oldest first
for task in stage.get_tasks(statuses=[TaskStatus.PROCESSING_FAILED], sort=TaskSort.CREATED_AT):
    print(task.id, task.status.name, task.created_at)

# Get the latest state of one task, current or historical
task_id = "00000000-0000-0000-0000-000000000000"  # Replace with a task ID
detail = workflow.get_task(id=task_id)
print(detail.status.name, detail.assignment)
```

## Assign and Release Tasks

You can assign and release tasks at Annotation and Review stages.

* `task.assign()` assigns the task to an eligible user, by email.
* `task.release()` releases the task's current assignment. Releasing requires Admin or Team Manager access to the Project. Releasing an unassigned task succeeds.
* `workflow.release_tasks()` releases up to 1,000 tasks in one request. If any task is unavailable, no tasks are released.

These methods do not change the task objects you already have. To see the new assignment, get the task again with `workflow.get_task(id=task.id)`. If a task has changed since you read it, the SDK raises `StaleTaskError`.

```python Assign and release tasks theme={"dark"}
# Import dependencies
from itertools import islice

from encord.beta.workflow_v3 import AnnotationStage, StaleTaskError, TaskStatus
from encord.user_client import EncordUserClient

# User input
SSH_PATH = "/Users/chris-encord/ssh-private-key.txt"  # Replace with the file path to your SSH private key
PROJECT_ID = "00000000-0000-0000-0000-000000000000"  # Replace with the unique Project ID
STAGE_NAME = "Annotate"  # Replace with the name of your Annotation stage
ASSIGNEE_EMAIL = "annotator@example.com"  # Replace with the email of a Project collaborator
MAX_TASKS = 10  # Number of tasks to assign

# Create user client using SSH key
user_client: EncordUserClient = EncordUserClient.create_with_ssh_private_key(
    ssh_private_key_path=SSH_PATH,
    # For US platform users use "https://api.us.encord.com"
    domain="https://api.encord.com",
)

project = user_client.get_project(PROJECT_ID)
workflow = project.workflow_v3
annotation = workflow.get_stage(name=STAGE_NAME, type_=AnnotationStage)

# Assign the first MAX_TASKS waiting tasks
tasks = list(islice(annotation.get_tasks(statuses=[TaskStatus.ENTERED]), MAX_TASKS))
for task in tasks:
    try:
        task.assign(ASSIGNEE_EMAIL)
    except StaleTaskError:
        print(f"Task {task.id} changed since it was listed. Skipping it.")

# Release all of them again in one request
workflow.release_tasks(tasks)
print(f"Assigned and released {len(tasks)} tasks")
```

## Submit Annotation and Review Tasks

`submit()` moves a task down one of its stage's outgoing pathways. Select the pathway with `pathway_id` or `pathway_name` (an exact, case-sensitive match), but not both. If the stage has only one outgoing pathway, you can leave out both.

* Submitting does not save labels. Save the task's labels first, by finding its label row with `project.list_label_rows_v2(data_hashes=[task.target.data_hash])`, and calling the label row's `save()`.
* Annotators and reviewers must be assigned the task before they submit it. Project Admins and Team Managers can submit without assigning themselves.
* You can add a `comment` of up to 50,000 characters, for data unit targets only.
* Submitting a Review task routes the task, but does not change the decisions on individual labels. The pathway's rules decide whether pending, rejected, or missing labels prevent submission.
* `stage.submit_tasks()` submits up to 100 tasks at the same stage down one pathway. If any task fails, none are submitted. To send tasks down different pathways, submit one batch per pathway.

```python Submit Review tasks theme={"dark"}
# Import dependencies
from itertools import islice

from encord.beta.workflow_v3 import ReviewStage, TaskStatus
from encord.exceptions import InvalidArgumentsError
from encord.user_client import EncordUserClient

# User input
SSH_PATH = "/Users/chris-encord/ssh-private-key.txt"  # Replace with the file path to your SSH private key
PROJECT_ID = "00000000-0000-0000-0000-000000000000"  # Replace with the unique Project ID
STAGE_NAME = "Review"  # Replace with the name of your Review stage
PATHWAY_NAME = "Approve"  # Replace with the name of the pathway to submit the tasks down
MAX_TASKS = 10  # Number of tasks to submit, up to 100 in one batch

# Create user client using SSH key
user_client: EncordUserClient = EncordUserClient.create_with_ssh_private_key(
    ssh_private_key_path=SSH_PATH,
    # For US platform users use "https://api.us.encord.com"
    domain="https://api.encord.com",
)

project = user_client.get_project(PROJECT_ID)
workflow = project.workflow_v3
review = workflow.get_stage(name=STAGE_NAME, type_=ReviewStage)

tasks = list(islice(review.get_tasks(statuses=[TaskStatus.ENTERED]), MAX_TASKS))
if not tasks:
    print("No tasks are waiting for review")
else:
    # Submit one task on its own
    first, rest = tasks[0], tasks[1:]
    first.submit(pathway_name=PATHWAY_NAME, comment="Review complete")

    # Submit the rest as one batch. If any task fails, none are submitted.
    if rest:
        try:
            review.submit_tasks(rest, pathway_name=PATHWAY_NAME, comment="Review complete")
        except InvalidArgumentsError as e:
            print(f"The batch was not submitted: {e}")
    print(f"Submitted {len(tasks)} tasks down '{PATHWAY_NAME}'")
```

Annotation tasks work the same way, with `AnnotationStage`, `AnnotationTask.submit()`, and `AnnotationStage.submit_tasks()`.

## Process External Tasks

Use an External stage to process data outside Encord, and then submit each task to move it on. Only tasks with the status `ENTERED` can be submitted. You need the Admin or Team Manager role on the Project.

Replace `process_data()` in the following example with your own processing.

```python Process External tasks theme={"dark"}
# Import dependencies
from encord.beta.workflow_v3 import DataUnitTarget, ExternalStage, ExternalTask, TaskStatus
from encord.user_client import EncordUserClient

# User input
SSH_PATH = "/Users/chris-encord/ssh-private-key.txt"  # Replace with the file path to your SSH private key
PROJECT_ID = "00000000-0000-0000-0000-000000000000"  # Replace with the unique Project ID
STAGE_NAME = "External processing"  # Replace with the name of your External stage
PATHWAY_NAME = "Continue"  # Replace with the pathway to submit tasks down, or None if there is only one
BATCH_SIZE = 100  # Up to 100 tasks per batch


def process_data(data_hash: str) -> None:
    """Replace with your own processing of the data unit."""
    print(f"Processing {data_hash}")


# Create user client using SSH key
user_client: EncordUserClient = EncordUserClient.create_with_ssh_private_key(
    ssh_private_key_path=SSH_PATH,
    # For US platform users use "https://api.us.encord.com"
    domain="https://api.encord.com",
)

project = user_client.get_project(PROJECT_ID)
workflow = project.workflow_v3
external = workflow.get_stage(name=STAGE_NAME, type_=ExternalStage)

# Process each waiting task, and submit the processed tasks in batches
processed: list[ExternalTask] = []
for task in external.get_tasks(statuses=[TaskStatus.ENTERED]):
    if not isinstance(task.target, DataUnitTarget):
        continue
    process_data(task.target.data_hash)
    processed.append(task)
    if len(processed) == BATCH_SIZE:
        external.submit_tasks(processed, pathway_name=PATHWAY_NAME)
        processed = []

if processed:
    external.submit_tasks(processed, pathway_name=PATHWAY_NAME)
```

To submit a single task, call `task.submit(pathway_name=PATHWAY_NAME)`. Submitting completes the task and routes it in one step.

## Errors and Retries

| Error | Cause |
| - | - |
| `StaleTaskError` | The task has changed since you read it. For example, it was already submitted or moved on. A stale task in a batch fails the whole batch. |
| `encord.exceptions.InvalidArgumentsError` | The pathway is not valid, or the stage's validation rules failed. |
| `encord.exceptions.AuthorisationError` | You do not have permission for the action. |
| `ValueError` | The arguments are not valid, for example both `pathway_id` and `pathway_name`, a malformed UUID, or a batch that is empty or holds more than 100 tasks. |

The SDK never automatically retries a request that changes a task. If a request fails because of a network or gateway error, the change may or may not have been applied. Get the task again with `workflow.get_task()` before you retry.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.