> ## 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.

# 고급 워크플로

> 분기, 반복, 재시도, 구조화된 결과, 단계별 모델 전환, 워크플로 조합을 다루며, 그대로 복사해 쓸 수 있는 전체 예제를 제공합니다.

단계를 나열하는 것만으로는 부족할 때 이 기능들을 사용하세요. 조건이 맞을 때만 단계를 실행하고, 목록의 항목마다 단계를 반복하고, 한 단계가 실패해도 실행을 이어 가고, 구조화된 결과를 받고, 한 워크플로에서 다른 워크플로를 호출할 수 있습니다. 전체 예제 워크플로는 끝부분에 있습니다. `agent-workflow/v1` 형식이 처음이라면 [워크플로 만들기](https://docs.enconvo.ai/ko/workflows/creating-workflows.md)부터 시작하세요.

예제를 실행하기 전에 셸 경로와 도구 및 공급자 사용 가능 여부가 사용 중인 Mac과 맞아야 합니다.

> [!TIP]
>
> 시각화 편집기에서는 직접 작성할 필요가 없습니다. 단계 인스펙터의 [동작](https://docs.enconvo.ai/ko/workflows/creating-workflows.md) 섹션에서 쉬운 말로 된 선택지를 고르면 `if`, `else_of`, `run_when`, `foreach`, `loop`, `retries`, `required`, `needs`, 출력 스키마가 설정됩니다.

## 분기

### 조건이 참일 때만 단계 실행하기 (`if`)

`if:`를 붙이면 조건이 참일 때만 단계가 실행됩니다. 조건이 거짓이면 해당 단계와 그 뒤에 이어지는 모든 단계를 건너뜁니다.

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

조건은 참 여부를 평가하는 템플릿 표현식입니다. 예를 들어 `inputs.score >= 60`, `steps.check.output.exitCode == 0`, 또는 단순한 불리언 입력이 있습니다.

### 다른 분기 실행하기 (`else_of`)

`else_of:`는 이름을 지정한 단계가 조건 때문에 건너뛰어졌을 때만 단계를 실행합니다. `if`의 "else" 쪽에 해당합니다.

```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"'
```

### 합류와 정리 (`run_when: always`)

`needs`가 있는 단계는 보통 의존하는 단계 중 하나라도 건너뛰어지면 건너뛰고, 필수 의존 단계가 실패하면 실행이 중단됩니다. `run_when: always`는 둘 다 무시합니다. 의존하는 단계가 성공했든, 건너뛰어졌든, 실패했든 끝나기만 하면 이 단계가 실행됩니다. 합류와 정리에 사용하세요.

```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.
```

### 단계 끄기 (`enabled: false`)

`enabled: false`를 쓰면 단계가 워크플로에 남아 있지만 모든 실행에서 건너뜁니다. 조건 때문에 건너뛰는 경우와 달리, 꺼진 단계는 뒤에 오는 단계를 건너뛰게 하지 않습니다.

* 이 단계에 의존하는 단계는 그대로 실행되며, 이 단계의 출력을 읽는 곳에는 빈 값이 전달됩니다.
* 이 단계를 `else_of`로 지정한 단계도 건너뜁니다.

키를 제거하거나 `true`로 설정하면 단계가 다시 켜집니다. 편집기에서는 인스펙터의 **단계 끄기**를 사용하세요.

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

## 반복

### 목록의 각 항목마다 반복하기 (`foreach`)

`foreach:`는 항목마다 한 번씩 단계를 실행합니다. 안에서 `{{ item }}`은 현재 요소이고 `{{ index }}`는 그 위치입니다. 뒤따르는 단계는 출력을 모은 배열을 받습니다.

```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`는 인라인 배열도 받으며 모든 종류의 단계에서 작동합니다. `tool:` 호출이나 하위 워크플로 등에도 `foreach`를 쓸 수 있습니다. 빈 목록은 빈 결과를 만들고, 뒤따르는 단계는 그대로 실행됩니다. 항목 하나가 실패하면 `required: false`로 표시되지 않은 한 그 단계는 새 항목을 시작하지 않습니다.

### 조건이 충족될 때까지 반복하기 (`loop`)

`loop:`는 단계를 반복합니다. `until:`은 매 회차가 끝난 뒤 그 회차의 결과인 `output`을 기준으로 확인합니다. `{{ round }}`는 회차 번호이고 `{{ last }}`는 이전 회차의 출력입니다. `until`이 충족되기 전에 `maxRounds`가 소진되면 단계가 실패합니다.

```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
```

`until`을 생략하면 정해진 횟수만큼 반복합니다.

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

## 안정성

| 필드 | 기능 |
| - | - |
| `retries` | 실패한 단계를 재시도합니다. 횟수(`retries: 2`) 또는 객체(`retries: { maxAttempts: 3, delayMs: 500 }`)를 사용합니다. |
| `required: false` | 이 단계가 실패해도 실행이 중단되지 않으며, 뒤따르는 단계가 계속됩니다. |
| `timeoutMs` | 너무 오래 실행되는 셸 단계를 중지합니다. |

20분 동안 아무 반응이 없는 단계는 중지되고 한 번 더 실행됩니다. 직접 중지한 실행은 실패가 아니라 **취소됨**으로 표시됩니다.

```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
```

## 출력 규약

`prompt` 또는 `agent` 단계에 `output_schema`(JSON Schema 객체)를 붙이면 답변의 형태를 강제할 수 있습니다. 프롬프트 본문에 JSON 형식을 설명할 필요가 없습니다. 요청한 형태가 모델에 전달되고, 답변은 뒤따르는 단계가 사용하기 전에 파싱되어 검증됩니다. `retries`를 설정하면 실패한 단계를 재시도하며, 그래도 검증에 실패하는 답변은 단계를 실패시킵니다.

```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 }}'
```

## 단계별 모델 재정의

`prompt` 및 `agent` 단계는 선택 사항인 `provider:`와 `model:`로 해당 단계에서만 모델을 바꿀 수 있습니다. 전환은 해당 실행 동안만 유지되며, 저장된 모델 구성은 바뀌지 않습니다. 대량 처리 단계에는 저렴한 모델을, 중요한 곳에는 더 강력한 모델을 사용하세요.

`provider`에는 설치된 공급자의 명령어 이름을, `model`에는 현재 빌드에서 그 공급자가 보여 주는 모델 ID를 설정합니다. 예를 들어 작동 중인 공급자 구성에서 두 값을 복사해 프롬프트 단계에 넣으세요. 모델 사용 가능 여부와 권한은 계정마다 다르며, 이 페이지의 예제는 구성된 기본 모델을 사용합니다.

> [!NOTE]
>
> `provider`는 공급자 명령어(예: `enconvo_ai`, `open_ai`, `ollama`)이고 `model`은 그 공급자의 모델 ID입니다. 둘 다 `prompt` 및 `agent` 단계에서만 유효합니다.

## 하위 워크플로

`uses: workflow`로 워크플로를 조합합니다. 저장된 워크플로는 `workflowId:`로, 또는 인라인 `workflow:` 블록으로 지정합니다. 단계의 출력은 하위 실행의 결과입니다. 하위 워크플로의 단계 출력은 `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 %}'
```

## 템플릿 참조

| 참조 | 사용 위치 |
| - | - |
| `{{ inputs.x }}` | 어디서나: 워크플로 입력 |
| `{{ steps.<id>.output }}` | 어디서나: 같은 작업의 이전 단계 |
| `{{ jobs.<job>.<step>.output }}` | 의존하는 작업에서 완료된 단계 |
| `{{ item }}` / `{{ index }}` | `foreach` 단계 안 |
| `{{ round }}` / `{{ last }}` | `loop` 단계 안 |
| `{{ now }}` | 현재 타임스탬프 |
| `{{ env.HOME }}` | 프로세스 환경 변수 |

템플릿은 Nunjucks 필터(`| trim`, `| int`, `| dump`, `| default(...)`, `{% for %}` 등)를 지원하며, 이를 이용해 단계 사이에서 데이터를 가공할 수 있습니다.

## 전체 예제

### 조사, 요약, 보고

웹을 검색하고, 결과를 요약하고, Markdown 보고서를 만듭니다. 단계는 한 작업 안에서 순서대로 실행되므로 `needs` 연결이 필요하지 않습니다.

```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"
```

### 조건부 라우팅

점수에 따라 승인하거나 거절한 다음, 항상 최종 보고서를 작성합니다.

```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('''')
        }}'
```

### 수렴할 때까지 반복

자체 검토에서 승인할 때까지 초안을 반복해서 다듬으며, 회차 수에 상한을 둡니다.

```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 }}'
```

## 관련 문서

> [card] [워크플로 만들기](https://docs.enconvo.ai/ko/workflows/creating-workflows.md)
>
> 편집기, 편집 어시스턴트, 모든 단계 유형을 설명합니다.

> [card] [워크플로](https://docs.enconvo.ai/ko/workflows/introduction.md)
>
> 작업, 단계, 워크플로가 실행되는 방식을 설명합니다.


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