# 图片

`POST /v1/images/generations` 是统一的 OpenAI 风格图片接口，nano、gemini、flux、qwen / 万相、gpt-image 与腾讯系图片模型都用它。默认同步：等图片生成完再返回；加 `async` 则先返回任务，再用 `GET /v1/images/generations/{id}` 轮询。

## 请求

`POST /v1/images/generations`，JSON，Bearer 密钥。`model` 和 `prompt` 必填；`model` 填下面「模型系列」里的 id。常用字段：`n`、`size`、`aspect_ratio`、`resolution`、`images`（参考图 URL）。

不在「模型系列」里的模型 id 仍由原处理器原样转发，见「gpt-image 与其他模型」。

```bash
curl https://api.novapi.ai/v1/images/generations \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nano-banana",
    "prompt": "A cozy wooden cabin in a snowy forest at dusk, warm window light",
    "n": 1,
    "size": "1536x1024"
  }'
```

Python（OpenAI SDK）：`model`、`prompt`、`n`、`size` 是 SDK 自带参数，其余统一字段放 `extra_body`。

```python
from openai import OpenAI

client = OpenAI(base_url="https://api.novapi.ai/v1", api_key="sk-...")

img = client.images.generate(
    model="nano-banana",
    prompt="A cozy wooden cabin in a snowy forest at dusk, warm window light",
    n=1,
    extra_body={"aspect_ratio": "3:2", "resolution": "1K"},
)
print(img.data[0].url)
```

TypeScript（OpenAI SDK）：

```python
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.novapi.ai/v1", apiKey: process.env.API_KEY });

const img = await client.images.generate({
  model: "nano-banana",
  prompt: "A cozy wooden cabin in a snowy forest at dusk, warm window light",
  n: 1,
  aspect_ratio: "3:2",
  resolution: "1K",
} as OpenAI.ImageGenerateParams);
console.log(img.data?.[0]?.url);
```

## 同步响应

默认同步：服务端等图片生成完，返回 200 和 OpenAI 形状的结果（`created` + `data[].url`），并带上任务字段 `id`、`status` 等。

同步最长等待 110 秒。超时则返回 202 和任务对象，响应头带 `Location: /v1/images/generations/{id}`。任务会继续运行，不要重新提交（重新提交会再次计费），改用 GET 取结果。

任务失败时，同步请求返回 502，`error.code` 为 `image_generation_failed`，预扣的积分自动退回。

```json
{
  "id": "img_<task-id>",
  "object": "image.generation",
  "model": "nano-banana",
  "status": "completed",
  "created": <unix-seconds>,
  "completed_at": <unix-seconds>,
  "error": null,
  "data": [
    { "url": "https://..." }
  ]
}
```

## 异步与轮询

请求体加 `"async": true`（或请求头 `Prefer: respond-async`），立即返回 202 和任务对象（`status: queued`），响应头带 `Location` 与 `Retry-After: 3`。

```bash
curl -i https://api.novapi.ai/v1/images/generations \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "nano-banana",
    "prompt": "A cozy wooden cabin in a snowy forest at dusk, warm window light",
    "async": true
  }'

# HTTP/1.1 202 Accepted
# Location: /v1/images/generations/img_<task-id>
# Retry-After: 3
```

```json
{
  "id": "img_<task-id>",
  "object": "image.generation",
  "model": "nano-banana",
  "status": "queued",
  "created": <unix-seconds>,
  "completed_at": null,
  "error": null,
  "data": []
}
```

用 `GET /v1/images/generations/{id}` 轮询，建议每 3 秒一次。任务只能由创建它的密钥所属账号读取，其他 id 返回 404。

| status | 含义 |
| --- | --- |
| `queued` | 已接收，尚未开始。 |
| `in_progress` | 生成中。 |
| `completed` | 完成，`data[].url` 是图片地址（`n` 大于 1 时有多个）。 |
| `failed` | `error.code` 为 `image_generation_failed`，`error.message` 为原因；预扣的积分已退回。 |

```bash
curl https://api.novapi.ai/v1/images/generations/img_<task-id> \
  -H "Authorization: Bearer $API_KEY"

# status: queued | in_progress | completed | failed
# completed: data[].url holds the image URL(s); failed: error.code and error.message
```

Python（requests）完整的创建加轮询：

```python
import os, time, requests

BASE = "https://api.novapi.ai/v1"
HEAD = {"Authorization": "Bearer " + os.environ["API_KEY"]}

task = requests.post(
    BASE + "/images/generations",
    headers=HEAD,
    json={
        "model": "nano-banana",
        "prompt": "A cozy wooden cabin in a snowy forest at dusk, warm window light",
        "async": True,
    },
).json()

while task["status"] in ("queued", "in_progress"):
    time.sleep(3)
    task = requests.get(BASE + "/images/generations/" + task["id"], headers=HEAD).json()

if task["status"] == "completed":
    print([d["url"] for d in task["data"]])
else:
    print(task["error"])
```

TypeScript（fetch）完整的创建加轮询：

```
const base = "https://api.novapi.ai/v1";
const headers = { Authorization: "Bearer " + process.env.API_KEY, "Content-Type": "application/json" };

let task = await (
  await fetch(base + "/images/generations", {
    method: "POST",
    headers,
    body: JSON.stringify({
      model: "nano-banana",
      prompt: "A cozy wooden cabin in a snowy forest at dusk, warm window light",
      async: true,
    }),
  })
).json();

while (task.status === "queued" || task.status === "in_progress") {
  await new Promise((r) => setTimeout(r, 3000));
  task = await (await fetch(base + "/images/generations/" + task.id, { headers })).json();
}

console.log(task.status === "completed" ? task.data.map((d) => d.url) : task.error);
```

## 请求字段

| 字段 | 说明 |
| --- | --- |
| `model` | 必填，见下面「模型系列」。 |
| `prompt` | 必填，图片描述。 |
| `n` | 出图张数，默认 1，上限随模型系列而定（见下表），超出返回 400。 |
| `size` | `宽x高`，例如 `1024x1024`，换算成该渠道接受的最接近的宽高比；nano / gemini 还接受 `auto`。格式不对返回 400。gpt-image 的异步模式（sora 渠道）把 `size` 原样转给渠道。 |
| `aspect_ratio` | 直接指定宽高比，例如 `16:9`；和 `size` 同时给出时以它为准。 |
| `resolution` | `1K` / `2K` / `4K`，用于 nano、gemini 与腾讯系模型；可选的档位随模型而定。 |
| `images` | 参考图 URL，字符串或数组，也可以写成 `image` 或 `image_urls`。只接受 http(s) URL，不接受 base64。 |
| `output_format` | `png`、`jpeg` 等，仅 nano、gemini、flux。 |
| `negative_prompt`、`prompt_extend` | `negative_prompt` 用于 qwen / 万相与腾讯系模型；`prompt_extend`（布尔值）仅用于 qwen / 万相。 |
| `quality` | `low` / `medium` / `high` / `auto`，仅 gpt-image 的异步模式，原样传给渠道。 |
| `async` | `true`：立即返回 202 和任务对象，再用 GET 轮询；也可以用请求头 `Prefer: respond-async`。缺省为同步。 |
| `response_format` | 图片门面里的模型只能是 `url`，其他值返回 400。 |
| 渠道原生字段 | `filesUrl`、`imageUrls`、`aspectRatio`、`numImages`、`outputFormat` 等原生字段会原样透传；和上面的统一字段同时出现时，以原生字段为准。 |

## 模型系列

下面这些模型都走上面的同一个端点，差别在 `n` 的上限、尺寸 / 比例的处理和参考图字段。每个模型的专属参数、可选分辨率与参考图张数见各模型参考页，单价见 `/pricing`。

| 系列 | `model` | `n` | `size` / 比例 | 参考图 | 其他字段 |
| --- | --- | --- | --- | --- | --- |
| Nano Banana | `nano-banana`、`nano-banana-pro`、`nano-banana-2`、`nano-banana-2.1` | 1–4 | 换算成最接近的 21:9、16:9、3:2、4:3、5:4、1:1、4:5、3:4、2:3、9:16；也可用 `auto` | `images` | `resolution`、`output_format` |
| Gemini 图片 | `gemini-3-pro-image-preview`、`gemini-3.1-flash-image-preview` | 1–4 | 同 Nano Banana | `images` | `resolution`、`output_format` |
| FLUX Kontext | `flux-kontext-pro`、`flux-kontext-max` | 只能 1 | 21:9、16:9、3:2、4:3、1:1、3:4、2:3、9:16 里最接近的；缺省 1:1 | `images` | `output_format`。上架状态以模型广场为准 |
| Qwen / 万相 | `qwen-image*`、`qwen-image-edit*`，`wan2.5` / `wan2.6` / `wan2.7` 的图片与 i2i 模型，`wanx*`（共 24 个 id，完整名单见模型广场） | 1–4 | 16:9、4:3、1:1、3:4、9:16 里最接近的；缺省 1:1 | `images`；edit / i2i 模型必填 | `negative_prompt`、`prompt_extend` |
| GPT-Image | `gpt-image-1`、`gpt-image-1.5`、`gpt-image-2`、`gpt-image-2-pro`、`gpt-image-2-vip`、`gpt-image-2.5-flare`、`gpt-image-2.5-sunburst` | 默认同步，由原处理器处理；`async: true` 时只能 1 | `size`、`quality` 原样传给渠道 | 异步模式用 `images` | 见「gpt-image 与其他模型」 |
| 即梦 Seedream | `seedream-5.0-pro`、`seedream-5.0-lite`、`seedream-4.5`、`seedream-4.0` | 最多 4 | 16:9、3:2、4:3、1:1、3:4、2:3、9:16 里最接近的；`aspect_ratio` 由渠道校验 | `images` | `resolution`、`negative_prompt` |
| 可灵生图 | `kling-image-3.0`、`kling-image-3.0-omni`、`kling-image-o1`、`kling-image-2.1` | 最多 9 | 同 Seedream | `images` | `resolution`、`negative_prompt` |
| Vidu、混元、明眸生图 | `vidu-image-q2`、`hunyuan-image-3.5-preview`、`hunyuan-image-3.0`、`mingmou-image-1.0` | 只能 1 | 同 Seedream | `images`，张数上限见各模型页 | `resolution`、`negative_prompt` |
| Midjourney | `mj-v8.2`、`mj-v8.1`、`mj-v7`、`mj-niji7` | 固定 4 张，不用传 `n`，`data` 里有 4 个 URL | 同 Seedream | 暂不支持 | `resolution`、`negative_prompt` |

- [Nano Banana](https://www.novapi.ai/zh/docs/nano)
- [Qwen 图片](https://www.novapi.ai/zh/docs/qwen)
- [GPT-Image](https://www.novapi.ai/zh/docs/sora)
- [Seedream](https://www.novapi.ai/zh/docs/seedream)
- [可灵生图](https://www.novapi.ai/zh/docs/kling-image)
- [Midjourney](https://www.novapi.ai/zh/docs/mj)

## 编辑与图生图

名称里带 `edit` 或 `i2i` 的模型（例如 `qwen-image-edit-plus`、`wan2.6-i2i`）只能编辑已有的图片，必须带 `images`；缺少时请求在提交前就被拒绝（400），不会扣费。其他模型带上 `images` 即为图生图 / 参考图生图。

```bash
curl https://api.novapi.ai/v1/images/generations \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen-image-edit-plus",
    "prompt": "Replace the background with a snowy mountain at sunrise",
    "images": ["https://example.com/input.jpg"]
  }'
```

## gpt-image 与其他模型

gpt-image-* 默认仍走原来的同步处理器，行为不变：兼容 OpenAI，`n`、`size` 等字段转发给上游，返回 `data[].url` 或 `b64_json`（没有 `id` 与 `status`）。

请求体加 `"async": true`（或 `Prefer: respond-async`）时，gpt-image-* 变成 sora 渠道上的异步任务：每次 1 张，`size` 与 `quality` 原样传给渠道，参考图用 `images`，返回上面的任务对象，用 GET 轮询。

其他不在「模型系列」里的模型 id 仍由原处理器原样转发：不传 `model` 时服务端使用 `dall-e-2`，核心字段是 `model` 和 `prompt`，其余字段转发给上游，返回上游的 OpenAI 风格结果，通常是带 `url` 或 `b64_json` 的 `data[]`，URL 可能已转存到我们的 CDN。

```bash
curl https://api.novapi.ai/v1/images/generations \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "A watercolor illustration of a quiet seaside town",
    "size": "1536x1024",
    "quality": "high",
    "async": true
  }'

# without "async": true this request goes to the synchronous OpenAI Images route
# and answers { "created": <unix-seconds>, "data": [{ "url": "https://..." }] }
```

## 计费与失败

计费与旧的 `/api/cqt/generator/{渠道}` 完全相同：提交前按单价乘以 `n` 检查余额并预扣，任务失败时自动退回。单价见「模型与价格」。

同步请求超时后变成 202，只是改为轮询取结果：任务不会重复提交，也不会重复计费。

## 错误

错误为 OpenAI 格式：`{ "error": { "message", "type", "param", "code" } }`，请按状态码与 `error.code` 判断。

| 状态码 | code | 何时出现 |
| --- | --- | --- |
| 400 | `invalid_request` | 参数校验未通过：`n` 超出该模型上限、缺少 `prompt`、`size` 格式不对、`images` 不是 http(s) URL、edit / i2i 模型没带参考图、`response_format` 不是 `url` 等。原因在 `message` 里，提交前被拒绝，不扣费。 |
| 400 | `content_policy_violation` | 提示词或素材被内容规则拦截。 |
| 401 | `invalid_api_key` | 密钥缺失或无效。 |
| 402 | `insufficient_quota` | 余额不足。 |
| 403 | `model_not_allowed` | 模型不在密钥的白名单内。 |
| 404 | `model_not_found`、`not_found` | 不是受支持的模型；或任务 id 不存在、属于其他账号。 |
| 429 | `task_limit_reached` | 同时进行的任务数达到上限。 |
| 502 | `image_generation_failed` | 同步请求里任务失败；异步任务失败时 GET 返回 `status: failed` 和同样的 `error.code`。 |

## 相关链接
- [图片模型参考](https://www.novapi.ai/zh/docs/nano)
