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

# 이미지 상태 조회

> 비동기 이미지 생성 작업의 상태 및 결과를 조회합니다.

## 경로 파라미터

<ParamField path="id" type="string" required>
  초기 이미지 생성 요청에서 반환된 작업 ID입니다.
</ParamField>

<Info>
  생성 응답에 `poll_url`이 포함된 경우, 폴링을 위해 해당 URL을 호출하는 것을 권장합니다. 일부 이미지 작업은 이미지 전용 상태 경로 대신 `/v1/tasks/{id}` 아래에 `poll_url`을 표시할 수 있습니다.

  `ldtask_...` 같은 공개 이미지 작업 ID는 `/v1/images/{id}`에서도 폴링할 수 있습니다. 이 호환 alias는 `/v1/images/generations/{id}`와 동일한 인증, 소유권 검사, 과금 헤더, 종료 스냅샷, 응답 형태를 사용합니다.

  작업이 더 이상 존재하지 않거나 공개 작업 기록에서 확인할 수 없는 경우 TokenLab는 `async_task_not_found`와 `Task not found or no longer available.` 메시지를 반환합니다.
</Info>

## 응답

<ResponseField name="created" type="integer">
  생성 시점의 Unix 타임스탬프입니다.
</ResponseField>

<ResponseField name="task_id" type="string">
  작업 식별자입니다.
</ResponseField>

<ResponseField name="status" type="string">
  작업 상태: `pending`, `processing`, `completed` 또는 `failed`.
</ResponseField>

<ResponseField name="data" type="array">
  생성된 이미지 배열입니다 (`status`가 `completed`인 경우 채워집니다).

  각 객체는 다음을 포함합니다:

  * `url` (string): 생성된 이미지의 URL
  * `revised_prompt` (string): 생성에 사용된 프롬프트
</ResponseField>

<ResponseField name="error" type="string">
  에러 메시지 (`status`가 `failed`인 경우에만 존재합니다).
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl "https://api.tokenlab.sh/v1/tasks/ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \
    -H "Authorization: Bearer sk-your-api-key"
  ```

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

  response = requests.get(
      "https://api.tokenlab.sh/v1/tasks/ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
      headers={"Authorization": "Bearer sk-your-api-key"}
  )

  data = response.json()
  print(f"Status: {data['status']}")

  if data["status"] == "completed":
      print(f"Image URL: {data['data'][0]['url']}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'https://api.tokenlab.sh/v1/tasks/ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
    {
      headers: {
        'Authorization': 'Bearer sk-your-api-key'
      }
    }
  );

  const data = await response.json();
  console.log(`Status: ${data.status}`);

  if (data.status === 'completed') {
    console.log(`Image URL: ${data.data[0].url}`);
  }
  ```
</RequestExample>

<ResponseExample>
  ```json 대기 중 theme={null}
  {
    "created": 1706000000,
    "id": "ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "task_id": "ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "poll_url": "/v1/tasks/ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "status": "pending",
    "data": [
      {
        "url": "",
        "revised_prompt": "a beautiful sunset over mountains"
      }
    ]
  }
  ```

  ```json 완료됨 theme={null}
  {
    "created": 1706000000,
    "id": "ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "task_id": "ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "poll_url": "/v1/tasks/ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "status": "completed",
    "data": [
      {
        "url": "https://cdn.example.com/generated/image-abc123.png",
        "revised_prompt": "a beautiful sunset over mountains with vibrant orange and purple colors"
      }
    ]
  }
  ```

  ```json 실패함 theme={null}
  {
    "created": 1706000000,
    "id": "ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "task_id": "ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "poll_url": "/v1/tasks/ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
    "status": "failed",
    "error": "Content policy violation",
    "data": []
  }
  ```
</ResponseExample>

## 폴링 권장 사항

<Tip>
  **권장 폴링 간격**: 3-5초. 대부분의 이미지 생성 작업은 모델 및 라우팅된 제공자 경로에 따라 30-120초 이내에 완료됩니다.
</Tip>

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

def poll_image_task(task_id, api_key, max_wait=300, interval=3):
    """Poll for image generation result with timeout."""
    url = f"https://api.tokenlab.sh/v1/tasks/{task_id}"
    headers = {"Authorization": f"Bearer {api_key}"}

    start_time = time.time()
    while time.time() - start_time < max_wait:
        response = requests.get(url, headers=headers)
        data = response.json()

        if data["status"] == "completed":
            return data["data"][0]["url"]
        elif data["status"] == "failed":
            raise Exception(data.get("error", "Generation failed"))

        time.sleep(interval)

    raise TimeoutError(f"Task {task_id} did not complete within {max_wait}s")

# Usage
image_url = poll_image_task("ldtask_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "sk-your-api-key")
print(f"Generated image: {image_url}")
```
