# Grok Imagine

使用此模型提交图片生成任务，再通过返回的任务 ID 查询结果。

模型 ID `grok-imagine`

## 快速开始

创建 [API 密钥](/me?section=api-keys)并设置 `I2V_API_KEY`。每个新任务设置一个 `IDEMPOTENCY_KEY`，重试同一次提交时复用原幂等键和请求体。

### 提交任务

`POST https://api.i2v.ai/api/v1/jobs/createTask`

```bash
curl "https://api.i2v.ai/api/v1/jobs/createTask" \
  -H "Authorization: Bearer $I2V_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  -d '{
  "model": "grok-imagine",
  "inputs": {
    "prompt": "A calm lake at sunrise",
    "aspectRatio": "1:1"
  }
}'
```

HTTP 200 表示任务已受理。保存返回的 `taskId`。

```json
{"taskId":"YOUR_TASK_ID"}
```

### 查询结果

```bash
curl "https://api.i2v.ai/api/v1/jobs/recordInfo?taskId=YOUR_TASK_ID" \
  -H "Authorization: Bearer $I2V_API_KEY"
```

将 `YOUR_TASK_ID` 替换为返回的任务 ID。状态为 `waiting` 或 `generating` 时退避轮询。`success` 时读取 `output[].url`，`fail` 时检查 `error`。

## 请求参数

模型输入放在 `inputs` 对象中。素材 URL 需要可公开访问。必需素材及参数组合取决于具体生成模式。

| 字段 | 类型 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- | --- |
| `inputs.prompt` | string | 是 | — | 画面描述或编辑指令，写清主体、地点、光线与镜头。 上限 5000 字符. |
| `inputs.aspectRatio` | string | 否 | 1:1 | 1:1、2:3、3:2、16:9、9:16；图生图模式下会被忽略。 可选值 `1:1`, `2:3`, `3:2`, `16:9`, `9:16`. |
| `inputs.imageUrls` | string[] | 否 | — | 一张参考图，多传的部分会被丢弃。 上限 1 个 URL. |

### 请求顶层字段

| 字段 | 类型 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- | --- |
| `model` | string | 是 | `grok-imagine` | 公开模型 ID，使用本页显示的准确值。 |
| `maxCostUsd` | string | 否 | — | 可选的美元费用上限，以最多八位小数的字符串传入。报价超出上限时会在生成前返回 HTTP 409。 |
| `callBackUrl` | string | 否 | — | 可选的公共 HTTPS 回调地址。签名配置见[任务回调](/docs/webhooks)。 |
| `expectedRevision` | number | 否 | — | 可选的模型发布版本，用于乐观并发校验。 |

## 响应结构

以下为成功响应示例，结果链接为占位值。实际美元费用由提交参数决定。任务待完成时，部分字段可能为 null。

```json
{
  "taskId": "YOUR_TASK_ID",
  "model": "grok-imagine",
  "status": "success",
  "billing": null,
  "output": [
    {
      "url": "https://example.com/result.png"
    }
  ],
  "error": null,
  "createTime": 1760000000000,
  "completeTime": 1760000060000
}
```

| 状态 | 含义 |
| --- | --- |
| `waiting` | 排队中 |
| `generating` | 生成中 |
| `success` | 已完成，读取 output[].url。 |
| `fail` | 生成失败，查看 error.code 和 error.message。 |

## 代码示例

### Node.js

```javascript
const baseUrl = "https://api.i2v.ai";
if (!process.env.I2V_API_KEY || !process.env.IDEMPOTENCY_KEY) {
  throw new Error('Set I2V_API_KEY and a stable IDEMPOTENCY_KEY before submitting.');
}
const headers = {
  Authorization: `Bearer ${process.env.I2V_API_KEY}`,
  'Content-Type': 'application/json',
  'Idempotency-Key': process.env.IDEMPOTENCY_KEY,
};
const response = await fetch(baseUrl + '/api/v1/jobs/createTask', {
  method: 'POST', headers,
  body: JSON.stringify({
  "model": "grok-imagine",
  "inputs": {
    "prompt": "A calm lake at sunrise",
    "aspectRatio": "1:1"
  }
}),
});
const created = await response.json();
if (!response.ok) throw new Error(JSON.stringify(created));

const deadline = Date.now() + 30 * 60_000;
let delayMs = 2_000;
let output;
while (Date.now() < deadline) {
  const result = await fetch(baseUrl + '/api/v1/jobs/recordInfo?taskId=' + encodeURIComponent(created.taskId), { headers });
  const task = await result.json();
  if (!result.ok || task.status === 'fail') throw new Error(JSON.stringify(task));
  if (task.status === 'success') {
    output = task.output;
    break;
  }
  await new Promise(resolve => setTimeout(resolve, delayMs));
  delayMs = Math.min(delayMs * 1.5, 30_000);
}
if (!output) throw new Error('Polling timed out. Resume with taskId ' + created.taskId);
console.log(output.map(item => item.url));
```

### Python

```python
import json
import os
import time
import urllib.parse
import urllib.request

base_url = "https://api.i2v.ai"
headers = {
    'Authorization': 'Bearer ' + os.environ['I2V_API_KEY'],
    'Content-Type': 'application/json',
    'Idempotency-Key': os.environ['IDEMPOTENCY_KEY'],
}
payload = json.loads("{\"model\":\"grok-imagine\",\"inputs\":{\"prompt\":\"A calm lake at sunrise\",\"aspectRatio\":\"1:1\"}}")
request = urllib.request.Request(
    base_url + '/api/v1/jobs/createTask',
    data=json.dumps(payload).encode(), headers=headers, method='POST',
)
with urllib.request.urlopen(request, timeout=60) as response:
    created = json.load(response)

deadline = time.monotonic() + 30 * 60
delay = 2
while time.monotonic() < deadline:
    query = urllib.parse.urlencode({'taskId': created['taskId']})
    request = urllib.request.Request(base_url + '/api/v1/jobs/recordInfo?' + query, headers=headers)
    with urllib.request.urlopen(request, timeout=60) as response:
        task = json.load(response)
    if task['status'] == 'fail':
        raise RuntimeError(task['error'])
    if task['status'] == 'success':
        print([item['url'] for item in task['output']])
        break
    time.sleep(delay)
    delay = min(delay * 1.5, 30)
else:
    raise TimeoutError('Polling timed out. Resume with taskId ' + created['taskId'])
```

### 参考图调用

```json
{
  "model": "grok-imagine",
  "inputs": {
    "prompt": "A calm lake at sunrise",
    "aspectRatio": "1:1",
    "imageUrls": [
      "https://example.com/reference.png"
    ]
  }
}
```

## 美元价格

以下价格来自已发布模型目录，请核对对应配置和计费单位。

| 模式 | 分辨率 | 时长 | USD | 计费单位 |
| --- | --- | --- | --- | --- |
| text-to-image | — | — | 0.04578755 USD | request |
| image-to-image | — | — | 0.04578755 USD | request |

## 错误与重试

常见提交错误包括 `400 invalid_params`、`401 unauthorized`、`402 insufficient_balance`、`409 conflict`、`429 concurrency_limit` / `rate_limit`。恢复流程见[错误与重试](/docs/errors)，签名完成通知见[任务回调](/docs/webhooks)。