> ## Documentation Index
> Fetch the complete documentation index at: https://dripart-chore-mintlify-theme-mint.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Comfy Router 빠른 시작

> 아무것도 없는 상태에서 Python과 TypeScript로 Comfy Router를 사용해 약 5분 만에 생성된 이미지를 얻는 방법.

<div className="router-quickstart-marker" />

Comfy Router를 사용하면 하나의 Comfy API 키로 `https://api.comfy.org`를 통해 파트너 모델을 호출할 수 있습니다. 모델의 입력을 `POST /v2/models/{provider}/{model}`로 보내고 완료된 결과를 기다리면 됩니다. 이 예시에서는 `bfl/flux-2-pro`로 이미지를 생성합니다.

<Steps>
  <Step title="API 키 생성">
    [Comfy 워크스페이스](https://platform.comfy.org/profile/api-keys?onboarding=router)에서 키를 생성하세요. Bash 호환 터미널에서 다음을 설정합니다:

    ```bash theme={null}
    export COMFY_API_KEY="comfyui-..."
    ```

    API 키는 서버나 로컬 환경에 보관하세요. 이 예시는 터미널 또는 서버용이며, 브라우저 JavaScript용이 아닙니다.

    워크스페이스에 크레딧이 충전되어 있어야 합니다. Comfy Router는 호출마다 크레딧을 차감하므로, 크레딧 잔액이 없는 워크스페이스는 첫 실제 호출에서 `error_type: insufficient_credits`와 함께 `402`가 거부됩니다. 그리고 이 검사는 요청 본문이 검증되기 전에 실행되므로, 크레딧이 없는 계정은 그 외에는 잘못된 형식의 요청이라도 `402`를 받습니다. 따라서 애초에 문제가 아니었을 요청 본문을 디버깅하기보다 먼저 워크스페이스에 크레딧을 충전하세요. 예시를 실행하기 전에 [워크스페이스 결제](https://platform.comfy.org)에서 크레딧을 추가하세요.
  </Step>

  <Step title="이 요청에 사용할 키 저장">
    이 이미지에 대해 이 값을 한 번 생성하세요. 같은 요청을 다시 시도할 때는 이 값을 재사용하세요.

    ```bash theme={null}
    export COMFY_REQUEST_KEY="$(uuidgen)"
    ```

    `uuidgen`을 사용할 수 없다면 다른 UUID 생성기를 사용하세요. 새로운 이미지를 시작할 때는 새 키를 사용하세요.
  </Step>

  <Step title="이미지 생성">
    언어를 선택하고 예시를 실행하세요. 이미지 생성에는 몇 분이 걸릴 수 있습니다.

    <CodeGroup>
      ```bash cURL theme={null}
      curl --max-time 660 \
        https://api.comfy.org/v2/models/bfl/flux-2-pro \
        -H "X-API-Key: $COMFY_API_KEY" \
        -H "Idempotency-Key: $COMFY_REQUEST_KEY" \
        -H "Content-Type: application/json" \
        -d '{"prompt": "a red teapot on a windowsill, morning light"}'
      ```

      ```python Python theme={null}
      # Python 3.10+
      # 설치: python -m pip install "comfy-sdk>=0.3.0"
      # quickstart.py로 저장한 뒤 실행: python quickstart.py

      import os

      from comfy_sdk import Comfy

      # Comfy는 환경 변수에서 COMFY_API_KEY를 읽습니다.
      with Comfy() as client:
          result = client.models.run(
              "bfl/flux-2-pro",
              {"prompt": "a red teapot on a windowsill, morning light"},
              idempotency_key=os.environ["COMFY_REQUEST_KEY"],
              timeout=660.0,
          )

      print("image:", result["result"]["sample"])
      ```

      ```typescript TypeScript theme={null}
      // Node.js 22+
      // 설치: npm install "@comfyorg/sdk@>=0.4.0" --save-dev tsx
      // quickstart.mts로 저장한 뒤 실행: npx tsx quickstart.mts

      import { comfy } from "@comfyorg/sdk";

      // Comfy는 환경 변수에서 COMFY_API_KEY를 읽습니다.
      type FluxResult = { result: { sample: string } };
      const idempotencyKey = process.env.COMFY_REQUEST_KEY;
      if (!idempotencyKey) throw new Error("Set COMFY_REQUEST_KEY first.");

      const result = await comfy.models.run<FluxResult>(
        "bfl/flux-2-pro",
        { prompt: "a red teapot on a windowsill, morning light" },
        { idempotencyKey, timeoutMs: 660_000 },
      );
      // 일부 모델은 JSON 대신 생성된 파일 자체로 응답합니다.
      if (result.kind !== "json") throw new Error("expected a JSON result");

      console.log("image:", result.data.result.sample);
      ```

      ```swift Swift theme={null}
      // Swift 5.9+ (macOS 14+, iOS 17+). 이 스니펫은 명령줄 프로그램입니다.
      // iOS 앱 안에 키를 포함하지 마세요. 바이너리에서 추출될 수 있습니다.
      // 앱에서는 자체 백엔드를 호출하고 키를 그곳에 보관하세요.
      // 설치: .package(url: "https://github.com/Comfy-Org/comfy-swift-sdk.git", from: "0.5.0")를 추가
      // 타깃에 ComfySwiftSDK를 추가하고, 이 파일을 Sources/.../main.swift에 넣은 뒤 실행: swift run

      import ComfySwiftSDK
      import Foundation

      let env = ProcessInfo.processInfo.environment

      guard let apiKey = env["COMFY_API_KEY"], !apiKey.isEmpty else {
          fatalError("Set COMFY_API_KEY first.")
      }
      guard let requestKey = env["COMFY_REQUEST_KEY"], !requestKey.isEmpty else {
          fatalError("Set COMFY_REQUEST_KEY first.")
      }

      let client = ComfyCloudClient(apiKey: apiKey)

      let result = try await client.models.run(
          "bfl/flux-2-pro",
          input: ["prompt": "a red teapot on a windowsill, morning light"],
          idempotencyKey: requestKey,
          timeout: 660  // 초
      )

      // 일부 모델은 JSON 대신 생성된 파일 자체로 응답합니다.
      guard let sample = result.output["result"]["sample"].stringValue else {
          fatalError("expected a JSON result carrying result.sample")
      }

      print("image:", sample)
      ```
    </CodeGroup>

    세 예시 모두 `COMFY_API_KEY`에서 키를 가져옵니다. Python과 TypeScript
    클라이언트는 환경 변수에서 직접 읽고, Swift 예시는 읽어서
    `ComfyCloudClient(apiKey:)`에 전달합니다.
  </Step>

  <Step title="결과 읽고 저장하기">
    이 모델의 경우 이미지 URL은 응답 본문의 `result.sample`에 있습니다. 축약된 응답은 다음과 같으며, 아래 URL은 예시일 뿐입니다:

    ```json theme={null}
    {
      "status": "Ready",
      "result": { "sample": "https://example.com/generated-image.jpeg" }
    }
    ```

    반환된 URL을 열거나 다운로드하세요:

    ```bash theme={null}
    curl --fail --location "PASTE_IMAGE_URL_HERE" --output teapot.jpg
    ```

    지체 없이 다운로드하세요. Router는 BFL 에셋을 Comfy 스토리지에 다시 호스팅할 수 있지만, URL은 만료되며 재생(replay)해도 갱신되지 않습니다. 재호스팅이 실패하면 수명이 더 짧은 공급자 URL이 남을 수 있습니다. [결과 에셋](/ko/development/comfy-router/reference#결과-에셋)을 참고하세요.
  </Step>
</Steps>

## 기다리는 대신 실행 대기열에 넣기

`run`은 이미지가 준비될 때까지 연결을 유지합니다. `request_id`를 즉시 돌려받고, 이 프로세스 또는 다른 프로세스에서 나중에 결과를 수집하려면 대신 `submit`을 호출하거나(3단계에서 설치하는 SDK 버전에 포함되어 있습니다), 동일한 본문을 HTTP로 `POST /v2/models/{provider}/{model}/requests`에 전송하세요. 2단계에서 했던 것처럼 `Idempotency-Key`를 함께 보내세요. 그러면 연결이 끊긴 뒤 재시도한 submit은 두 번째 요청을 실행 대기열에 넣고 과금하는 대신 원본 요청을 반환합니다. SDK는 `submit` 호출마다 이 키를 하나씩 생성합니다. 모든 모델 페이지에는 동기식 스니펫 옆에 **Queue and collect later** 탭이 있으며, [대기 중 전송](/ko/development/comfy-router/queue)에서 상태, 취소, 수집 방법을 차례로 안내합니다.

대기 중 전송은 여러분의 키 뒤에 있는 워크스페이스를 범위로 하며, [내 Comfy 워크스페이스](https://platform.comfy.org/profile/api-keys?onboarding=router)에서 생성한 키에는 이 워크스페이스가 함께 따라옵니다.

## 모델 선택

[Comfy Router를 통해 사용할 수 있는 모델을 찾아보고](/ko/development/comfy-router/models), 각 모델의 입력을 확인한 다음, 이 예시의 모델 ID를 바꾸세요.
