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

# Advanced Workflows

> Branch, loop, retry, get structured results, switch models per step, and compose workflows, with complete examples to copy.

Use these features when a straight list of steps isn't enough: run a step only when a condition holds, repeat a step over a list, keep a run going when one step fails, get structured results, and call one workflow from another. Complete example workflows are at the end. If you're new to the `agent-workflow/v1` format, start with [Creating Workflows](https://docs.enconvo.ai/workflows/creating-workflows.md).

Shell paths and tool or provider availability must match your Mac before you run these examples.

> [!TIP]
>
> In the Visual editor you don't need to write these by hand: the step inspector's [Behavior](https://docs.enconvo.ai/workflows/creating-workflows.md#step-behavior) section sets `if`, `else_of`, `run_when`, `foreach`, `loop`, `retries`, `required`, `needs`, and the output schema from plain-language choices.

## Branching

### Run a step only if a condition is true (`if`)

Attach `if:` to run a step only when a condition is true. When the condition is false, the step and everything downstream of it skip:

```yaml theme={null}
jobs:
  main:
    steps:
    - id: deploy
      if: inputs.ready
      command: ./deploy.sh
```

Conditions are template expressions evaluated for truthiness, for example `inputs.score >= 60`, `steps.check.output.exitCode == 0`, or a plain boolean input.

### Run the other branch (`else_of`)

`else_of:` runs a step only when the step it names was skipped by its condition. It's the "else" side of an `if`:

```yaml theme={null}
jobs:
  main:
    steps:
    - id: deploy
      if: inputs.ready
      command: ./deploy.sh
    - id: notify_skip
      else_of: deploy
      command: osascript -e 'display notification "deploy skipped"'
```

### Join and clean up (`run_when: always`)

A step with `needs` normally skips if any dependency skipped, and the run stops if a required dependency fails. `run_when: always` overrides both: the step runs as long as its dependencies have finished, whether they succeeded, skipped, or failed. Use it for joins and cleanup:

```yaml theme={null}
jobs:
  main:
    steps:
    - id: build
      command: ./build.sh
    - id: cleanup
      needs:
      - build
      run_when: always
      uses: transform
      value: Build finished; inspect its status in Runs.
```

### Turn a step off (`enabled: false`)

`enabled: false` keeps a step in the workflow but skips it on every run. Unlike a skipped condition, a step that is off doesn't skip what comes after it:

* Its dependents still run, and anything that reads its output gets an empty value.
* Its `else_of` step skips too.

Remove the key (or set it to `true`) to turn the step back on. In the editor, use **Turn off step** in the inspector.

```yaml theme={null}
jobs:
  main:
    steps:
    - id: draft
      command: ./draft.sh
    - id: notify
      enabled: false
      command: ./notify.sh
    - id: publish
      command: ./publish.sh
```

## Loops

### Repeat for each item in a list (`foreach`)

`foreach:` runs the step once per item. Inside, `{{ item }}` is the current element and `{{ index }}` is its position. Downstream steps receive the collected array of outputs:

```yaml theme={null}
inputs:
  questions:
    type: array
    default:
    - What is it?
    - Why does it matter?
jobs:
  main:
    steps:
    - id: answer
      foreach: '{{ inputs.questions }}'
      prompt: 'Answer in one sentence: {{ item }}'
    - id: digest
      uses: transform
      value: '{% for a in steps.answer.output %}- {{ a }}

        {% endfor %}'
```

`foreach` also accepts an inline array, and it works with every kind of step: a `foreach` of `tool:` calls, of subworkflows, and so on. An empty list produces an empty result, and downstream steps still run.

### Repeat until a condition holds (`loop`)

`loop:` repeats a step. `until:` is checked after each round against `output`, that round's result. `{{ round }}` is the round number and `{{ last }}` is the previous round's output. If `maxRounds` runs out before `until` is met, the step fails.

```yaml theme={null}
jobs:
  main:
    steps:
    - id: poll
      run: curl -s -o /dev/null -w '%{http_code}' https://example.com/status
      loop:
        until: output.stdout | trim == '200'
        maxRounds: 10
```

Leave out `until` to loop a fixed number of times:

```yaml theme={null}
jobs:
  main:
    steps:
    - id: retry_build
      command: ./build.sh
      loop:
        maxRounds: 3
```

## Reliability

| Field | What it does |
| - | - |
| `retries` | Retries a failed step. Use a count (`retries: 2`) or an object (`retries: { maxAttempts: 3, delayMs: 500 }`). |
| `required: false` | A failure of this step doesn't abort the run; downstream steps continue. |
| `timeoutMs` | Stops a shell step that runs too long. |

```yaml theme={null}
jobs:
  main:
    steps:
    - id: flaky_fetch
      tool: web_fetch/web_fetch
      params:
        link_url: '{{ inputs.url }}'
      retries:
        maxAttempts: 3
        delayMs: 1000
    - id: optional_enrich
      run: ./enrich.sh || exit 1
      required: false
```

## Output contracts

Attach an `output_schema` (a JSON Schema object) to a `prompt` or `agent` step to enforce the shape of the reply. You don't need to describe the JSON format in the prompt text: the requested shape is given to the model, and the reply is parsed and validated before downstream steps use it. Set `retries` to retry a failed step; a reply that still fails validation fails the step.

```yaml theme={null}
jobs:
  main:
    steps:
    - id: extract
      prompt: 'Extract the invoice details from: {{ inputs.text }}'
      output_schema:
        type: object
        required:
        - payer
        - amount
        - date
        properties:
          payer:
            type: string
          amount:
            type: number
          date:
            type: string
    - id: record
      uses: transform
      value: '{{ steps.extract.output.payer }} paid {{ steps.extract.output.amount }}'
```

## Per-step model overrides

`prompt` and `agent` steps accept optional `provider:` and `model:` to switch the model for that step only. The switch lasts for the run; your saved model configuration is untouched. Use a cheap model for bulk steps and a stronger one where it matters.

Set `provider` to the installed provider command name and `model` to a model ID shown by that provider in your current build. For example, copy both values from your working provider configuration into the prompt step. Model availability and permissions are account-specific; the examples on this page use your configured default model.

> [!NOTE]
>
> `provider` is a provider command (for example `enconvo_ai`, `open_ai`, or `ollama`) and `model` is a model ID for that provider. Both are valid only on `prompt` and `agent` steps.

## Subworkflows

Compose workflows with `uses: workflow`, either by `workflowId:` (a saved workflow) or with an inline `workflow:` block. The step's output is the child run result. Reference the child's step outputs with `output.outputs['job.step']`:

```yaml theme={null}
jobs:
  main:
    steps:
    - id: build_each
      foreach: '{{ inputs.targets }}'
      uses: workflow
      inputs:
        target: '{{ item }}'
      workflow:
        version: agent-workflow/v1
        title: Build target
        description: Build and package one target.
        jobs:
          main:
            steps:
            - id: compile
              run: make {{ inputs.target }}
            - id: package
              run: tar czf {{ inputs.target }}.tgz build/
    - id: summary
      uses: transform
      value: '{% for r in steps.build_each.output %}{{ r.status }} {% endfor %}'
```

## Templates reference

| Reference | Where |
| - | - |
| `{{ inputs.x }}` | Anywhere: workflow inputs |
| `{{ steps.<id>.output }}` | Anywhere: a previous step in the same job |
| `{{ jobs.<job>.<step>.output }}` | A completed step in a dependency job |
| `{{ item }}` / `{{ index }}` | Inside a `foreach` step |
| `{{ round }}` / `{{ last }}` | Inside a `loop` step |
| `{{ now }}` | Current timestamp |
| `{{ env.HOME }}` | Process environment variables |

Templates support Nunjucks filters (`| trim`, `| int`, `| dump`, `| default(...)`, `{% for %}`, and others), which is how you reshape data between steps.

## Complete examples

### Research, summarize, and report

Search the web, summarize the findings, and assemble a Markdown report. The steps run in order within one job, so no `needs` wiring is required:

```yaml theme={null}
version: agent-workflow/v1
title: Research Brief
description: Search the web on a topic and produce a short Markdown brief.
inputs:
  topic:
    type: string
    default: coffee brewing
jobs:
  main:
    steps:
    - id: search
      tool: web_search/web_search
      params:
        search_query: '{{ inputs.topic }} latest'
        limit: 5
    - id: summarize
      prompt: 'Summarize the key points from these results in 4 bullets.

        Results: {{ steps.search.output }}

        '
    - id: report
      uses: transform
      value: "# {{ inputs.topic }} \u2014 brief ({{ now }})\n{{ steps.summarize.output }}\n"
```

### Conditional routing

Approve or reject based on a score, then always write a final report:

```yaml theme={null}
version: agent-workflow/v1
title: Lead Router
description: Route a lead by score, reporting the outcome either way.
inputs:
  score:
    type: number
    default: 42
jobs:
  main:
    steps:
    - id: approve
      if: inputs.score >= 60
      uses: transform
      value: approved
    - id: reject
      else_of: approve
      uses: transform
      value: rejected
    - id: report
      needs:
      - approve
      - reject
      run_when: always
      uses: transform
      value: 'outcome: {{ steps.approve.output | default('''') }}{{ steps.reject.output | default('''')
        }}'
```

### Loop until converged

Refine a draft repeatedly until a self-check approves it, capping the rounds:

```yaml theme={null}
version: agent-workflow/v1
title: Refine Until Good
description: Improve a draft until a self-check approves it.
inputs:
  brief:
    type: string
    default: A tweet announcing our new feature.
jobs:
  main:
    steps:
    - id: refine
      prompt: 'Improve this draft. Return the improved draft and whether it is ready.

        Previous attempt: {{ last | default(inputs.brief) }}

        '
      output_schema:
        type: object
        required:
        - draft
        - approved
        properties:
          draft:
            type: string
          approved:
            type: boolean
      loop:
        until: output.approved == true
        maxRounds: 4
    - id: publish
      uses: transform
      value: '{{ steps.refine.output.draft }}'
```

## Related

> [card] [Creating Workflows](https://docs.enconvo.ai/workflows/creating-workflows.md)
>
> The editor, the editing assistant, and every step type.

> [card] [Workflows](https://docs.enconvo.ai/workflows/introduction.md)
>
> Jobs, steps, and how workflows are run.


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