OpenAI Tasks API 연동 및 사용

OpenAI Tasks API는 이전에 콜백 모드로 OpenAI 이미지 인터페이스에 제출한 작업의 결과를 조회하는 데 사용됩니다. 동기 HTTP 응답을 기다릴 수 없거나, 나중에 작업을 다시 조회하려는 경우 이 인터페이스를 사용하세요.

콜백 모드에서는 원래 이미지 인터페이스가 요청을 접수한 후 즉시 task_id를 반환합니다. 이 task_id를 직접 보관하고 필요할 때 이 인터페이스에서 조회하면 되며, 사용자 지정 trace_id를 추가로 전달할 필요가 없습니다(자체 비즈니스 식별자로 연관시키려는 경우에만 필요합니다).

원래 이미지 요청에 callback_url이 포함된 경우에만 작업이 영구 저장됩니다. 동기(비콜백) 방식으로 호출한 요청은 저장되지 않습니다.

신청 절차

애플리케이션 목록에 로그인하고 일반 애플리케이션을 열어 API KEY 항목 오른쪽의 복사 버튼을 클릭하세요. 아래 예제의 {token}에 사용할 수 있도록 Key를 서버에 보관하세요.

零壹AI API Key 가져오기

이미지 작업을 생성할 때 사용한 Key를 사용할 수 있으며, 해당 Key가 작업 조회도 허용하는지 확인하세요.

인터페이스 주소

POST https://api.01ai.cloud/openai/tasks

지원되는 action:

작업 설명
retrieve id 또는 trace_id로 단일 작업 조회
retrieve_batch ids / trace_ids / application_id / user_id로 일괄 조회

요청 헤더

  • accept: application/json
  • authorization: Bearer {token}
  • content-type: application/json

단일 작업 조회(retrieve)

요청 본문

필드 유형 필수 설명
action string 예 retrieve로 고정
id string 둘 중 하나 이미지 요청 제출 시 동기 응답에서 반환된 작업 ID(사용 권장)
trace_id string 둘 중 하나 원래 요청에 사용자 지정 trace_id를 명시적으로 전달한 경우에만 사용

id와 trace_id 중 적어도 하나를 전달하세요. 일반적으로 제출 응답의 id를 그대로 사용하면 되며, trace_id는 사용자 지정 비즈니스 식별자로 연관시키려는 경우에만 전달합니다.

코드 예제

CURL

curl -X POST 'https://api.01ai.cloud/openai/tasks' \
  -H 'accept: application/json' \
  -H 'authorization: Bearer {token}' \
  -H 'content-type: application/json' \
  -d '{
    "action": "retrieve",
    "id": "7489df4c-ef03-4de0-b598-e9a590793434"
  }'

Python

import requests

url = "https://api.01ai.cloud/openai/tasks"
headers = {
    "accept": "application/json",
    "authorization": "Bearer {token}",
    "content-type": "application/json",
}
payload = {
    "action": "retrieve",
    "id": "7489df4c-ef03-4de0-b598-e9a590793434",
}
response = requests.post(url, json=payload, headers=headers)
print(response.json())

반환 예제

작업이 존재할 때:

{
  "_id": "67a1b2c3d4e5f6a7b8c9d0e1",
  "id": "7489df4c-ef03-4de0-b598-e9a590793434",
  "trace_id": "my-custom-trace-001",
  "type": "images",
  "application_id": "9dec7b2a-1cad-41ff-8536-d4ddaf2525d4",
  "user_id": "5d8e7f6a-1234-4abc-9def-0123456789ab",
  "credential_id": "68253cc8-505d-47f4-97ad-0050a62e4975",
  "created_at": 1763142607.967,
  "started_at": 1763142607.97,
  "finished_at": 1763142637.404,
  "elapsed": 29.437,
  "request": {
    "model": "gpt-image-1",
    "prompt": "A cat sitting on a table",
    "size": "1024x1024",
    "callback_url": "https://your.server/callback"
  },
  "response": {
    "created": 1763142637,
    "data": [
      { "url": "https://platform.cdn.acedata.cloud/openai/...png" }
    ],
    "success": true
  }
}

일치하는 작업이 없을 때는 빈 객체를 반환합니다:

{}

필드 설명

  • id: 원래 이미지 요청을 접수할 때 생성된 작업 ID.
  • trace_id: 클라이언트 비즈니스에서 연관시키기 쉽도록 원래 요청에 전달한 사용자 지정 추적 식별자.
  • type: 작업 유형. gpt-image 계열(예: gpt-image-2)이 기록한 작업은 images이며, gpt-image-1, nano-banana 등은 images_generations / images_edits를 사용하고, 일부 채팅 인터페이스는 chat_completions_image를 사용합니다.
  • request: 원래 요청의 전체 요청 본문.
  • response: 콜백 완료 시 반환되는 최종 응답 본문.
  • created_at / started_at / finished_at: Unix 타임스탬프(초, 부동소수점).
  • elapsed: 실행 소요 시간(초, 부동소수점).
  • application_id / user_id / credential_id: 소속 애플리케이션, 최종 사용자, 자격 증명 ID.

일괄 조회(retrieve_batch)

요청 본문

필드 유형 설명
action string retrieve_batch로 고정
ids string[] 작업 ID 목록으로 조회
trace_ids string[] trace_id 목록으로 조회
application_id string 애플리케이션별로 모든 작업 조회
user_id string 최종 사용자별로 모든 작업 조회
type string 작업 유형별로 필터링(값: images, images_generations, images_edits)
offset int 페이지네이션 시작점, 기본값 0
limit int 페이지당 항목 수, 기본값 12
created_at_min float 시작 타임스탬프(Unix 초)
created_at_max float 종료 타임스탬프(Unix 초)

ids / trace_ids / application_id / user_id 또는 created_at_* 시간 범위 중 하나를 선택하여 전달하면 됩니다.

CURL 예제

curl -X POST 'https://api.01ai.cloud/openai/tasks' \
  -H 'authorization: Bearer {token}' \
  -H 'content-type: application/json' \
  -d '{
    "action": "retrieve_batch",
    "trace_ids": ["my-trace-001", "my-trace-002"]
  }'

반환 예제

{
  "items": [
    {
      "_id": "67a1b2c3d4e5f6a7b8c9d0e1",
      "id": "7489df4c-ef03-4de0-b598-e9a590793434",
      "trace_id": "my-trace-001",
      "type": "images",
      "request": {
        "model": "gpt-image-2",
        "prompt": "A cat"
      },
      "response": {
        "data": [
          {
            "url": "https://...png"
          }
        ]
      },
      "created_at": 1763142607.967,
      "started_at": 1763142608.027,
      "finished_at": 1763142637.404,
      "elapsed": 29.377
    }
  ],
  "count": 1
}

엔드투엔드 예시: 제출 및 폴링

Tasks API는 주로 콜백 모드의 비동기 흐름을 지원합니다. 콜백 모드에서는 제출 인터페이스가 task_id 하나를 즉시 동기적으로 반환하며(즉, 작업 ID), 이후에는 이 task_id를 사용해 Tasks 인터페이스를 직접 폴링하기만 하면 되므로 trace_id를 직접 생성할 필요가 없습니다.

import os, time, requests

API = "https://api.01ai.cloud"
HEADERS = {
    "authorization": f"Bearer {os.environ['ACEDATA_API_KEY']}",
    "content-type": "application/json",
}

# 1. 提交图片生成任务(callback 模式:带上 callback_url 即可立即返回 task_id)
submit = requests.post(
    f"{API}/openai/images/generations",
    headers=HEADERS,
    json={
        "model": "gpt-image-1",
        "prompt": "一只水彩风格的猫坐在桌子上",
        "callback_url": "https://webhook.site/your-uuid",
    },
).json()
print("submitted:", submit)

task_id = submit["task_id"]

# 2. 直接用提交响应中的 task_id 轮询 Tasks 接口,直到任务完成
while True:
    task = requests.post(
        f"{API}/openai/tasks",
        headers=HEADERS,
        json={"action": "retrieve", "id": task_id},
    ).json()
    if task and task.get("response"):
        print("finished:", task["response"])
        break
    time.sleep(3)

주의 사항

  • Tasks 인터페이스 자체는 요금이 부과되지 않으므로 안심하고 폴링할 수 있습니다. 원래의 이미지 생성/편집 요청에만 요금이 부과됩니다.
  • 원래 요청에 callback_url이 포함된 경우에만 작업 기록이 저장되며, 동기 호출은 조회할 수 있는 작업을 생성하지 않습니다.
  • 플랫폼의 보존 기간이 지난 작업 기록은 삭제될 수 있습니다.