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

# OpenAI Tasks API 接入與使用

> OpenAI generation 整合指南 - Ace Data Cloud

OpenAI Tasks API 用於查詢此前以 **回調模式** 提交到 OpenAI 圖片接口的任務結果。當您無法等待同步 HTTP 回應、或希望事後再次查詢任務時，請使用本接口。

回調模式下，**原始的圖片接口在受理請求後會立即返回一個 `task_id`**，您直接持有這個 `task_id`、並在需要時拿它到本接口查詢即可，無需額外傳遞自定義 `trace_id`（僅當您希望用自有業務標識做關聯時才需要）。

> 僅當原始圖片請求中帶有 `callback_url` 時，任務才會被持久化。同步（非回調）方式調用的請求不會被存儲。

## 申請流程

OpenAI Tasks API 與現有 OpenAI 服務共用授權。如果您已經申請了 OpenAI Images Generations，可直接使用相同的 token 調用本接口，無需額外申請。

新用戶首次申請均有免費額度。

## 接口地址

```
POST https://api.acedata.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

```bash theme={null}
curl -X POST 'https://api.acedata.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

```python theme={null}
import requests

url = "https://api.acedata.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())
```

### 返回示例

任務存在時：

```json theme={null}
{
  "_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
  }
}
```

未匹配到任何任務時返回空對象：

```json theme={null}
{}
```

### 欄位說明

* `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 示例

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

### 返回示例

```json theme={null}
{
  "items": [
    {
      "_id": "67a1b2c3d4e5f6a7b8c9d0e1",
      "id": "7489df4c-ef03-4de0-b598-e9a590793434",
      "trace_id": "my-trace-001",
      "type": "images",
      "request": {
        "model": "gpt-image-2",
        "prompt": "一隻貓"
      },
      "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`。

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

API = "https://api.acedata.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` 時，才會寫入任務記錄；同步調用不會產生可查詢的任務。
* 超過平台保留期的任務記錄可能被清理。


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