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

# 异步任务

> 创建、轮询、列表查询和接收 EggAPI 生成任务回调

当前公开 nano-banana 模型会返回异步任务。API 会立即创建任务，worker 在后台执行，之后你再读取结果。

## 生命周期

```mermaid theme={null}
sequenceDiagram
  participant App
  participant API as EggAPI API
  participant Worker
  participant Provider
  App->>API: POST /v1/generate
  API-->>App: 202 Accepted 和任务 ID
  Worker->>Provider: 启动生成
  loop 轮询上游
    Worker->>Provider: 查询状态
  end
  Worker->>API: 保存输出、用量和成本
  App->>API: GET /v1/tasks/{id}
  API-->>App: completed 或 failed 任务
```

任务状态：

| 状态 | 含义 |
| - | - |
| `pending` | 任务已创建并进入队列。 |
| `processing` | Worker 已开始执行或轮询上游。 |
| `completed` | 输出、成本和 usage 已记录。 |
| `failed` | 任务失败，响应里会有错误信息。 |

## 创建任务

```bash theme={null}
curl -X POST https://api.eggapi.ai/v1/generate \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nanobanana",
    "prompt": "A dashboard hero image with glass UI panels",
    "aspect_ratio": "16:9",
    "num_outputs": 1
  }'
```

响应：

```json theme={null}
{
  "data": {
    "id": "gen_abc123def456",
    "status": "pending",
    "model": "nanobanana",
    "type": "image_generate",
    "cost": "$0.00",
    "created_at": "2026-05-08T10:30:00Z"
  },
  "error": null
}
```

## 轮询任务

```bash theme={null}
curl https://api.eggapi.ai/v1/tasks/gen_abc123def456 \
  -H "Authorization: Bearer YOUR_API_KEY"
```

完成的图片任务：

```json theme={null}
{
  "data": {
    "id": "gen_abc123def456",
    "status": "completed",
    "model": "nanobanana",
    "type": "image_generate",
    "output": {
      "url": "https://file.eggapi.ai/images/gen_abc123def456/0.png",
      "urls": ["https://file.eggapi.ai/images/gen_abc123def456/0.png"]
    },
    "cost": "$0.0100",
    "created_at": "2026-05-08T10:30:00Z",
    "started_at": "2026-05-08T10:30:01Z",
    "completed_at": "2026-05-08T10:30:10Z"
  },
  "error": null
}
```

## 列出任务

```bash theme={null}
curl "https://api.eggapi.ai/v1/tasks?page=1&per_page=20" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

分页信息在 `data.pagination` 中返回。

## Webhook

创建任务时传入 `webhook_url`：

```json theme={null}
{
  "model": "nanobanana",
  "prompt": "A studio portrait with soft lighting",
  "webhook_url": "https://example.com/eggapi/webhook"
}
```

任务完成或失败后，EggAPI 会向该 URL POST JSON。请求头包含：

| Header | 说明 |
| - | - |
| `X-EggAPI-Timestamp` | 用于签名的 Unix 时间戳。 |
| `X-EggAPI-Signature` | `sha256=` 加上使用你的 webhook secret 对 `{timestamp}.{raw_body}` 做 HMAC-SHA256 的结果。 |

完成回调：

```json theme={null}
{
  "event": "task.completed",
  "task_id": "gen_abc123def456",
  "status": "completed",
  "model": "nanobanana",
  "output": {
    "urls": ["https://file.eggapi.ai/images/gen_abc123def456/0.png"]
  },
  "cost": "0.010000",
  "timestamp": 1778217000
}
```

失败回调：

```json theme={null}
{
  "event": "task.failed",
  "task_id": "gen_abc123def456",
  "status": "failed",
  "model": "nanobanana",
  "error": "generation failed: upstream provider unavailable",
  "cost": "0.000000",
  "timestamp": 1778217000
}
```

Webhook 请求超时为 30 秒，最多重试 5 次，并使用指数退避。

## 轮询辅助函数

```javascript theme={null}
async function waitForTask(taskId, apiKey, timeoutMs = 300000) {
  const start = Date.now();

  while (Date.now() - start < timeoutMs) {
    const response = await fetch(`https://api.eggapi.ai/v1/tasks/${taskId}`, {
      headers: { "Authorization": `Bearer ${apiKey}` }
    });
    const { data, error } = await response.json();

    if (error) throw new Error(error.message);
    if (data.status === "completed") return data;
    if (data.status === "failed") throw new Error(data.error || "Task failed");

    await new Promise((resolve) => setTimeout(resolve, 3000));
  }

  throw new Error("Task timed out");
}
```


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