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

# Krea 3 API 概览

> Krea 3 API 指南：一款快速且精准遵循指令的图像编辑模型。涵盖端点、参数、思考模式、区域编辑和代码示例。

Krea 3 是一款快速的图像编辑模型。它能遵循自然语言指令：你只需说明哪些需要改变、哪些保持不变，Krea 3 就会在几秒内完成编辑。你也可以用它进行文生图。如需先在应用中试用，请参阅 [Krea 3 ↗](https://www.krea.ai/krea-3) 或 [Krea 3 模型页面 ↗](https://www.krea.ai/models/krea-3)。

> [!NOTE]
>
> Krea 3 API 对所有工作区开放。`ultra` 思考模式需要 Max 及以上套餐。

## 端点

| 模型 | 端点 |
| - | - |
| **Krea 3** | `POST /generate/image/krea/krea-3` |

该端点遵循标准的[任务生命周期](https://www.krea.ai/docs/cn/developers/job-lifecycle.md)：它会返回一个 `job_id`，你可以轮询 `GET /jobs/{job_id}`（或使用 [webhook](https://www.krea.ai/docs/cn/developers/webhooks.md)），直到任务完成。输出图像位于 `result.urls[0]`。

## 快速开始：你的第一次图像编辑

所有请求都需要 Bearer token。如果你还没有，请参见 [API Keys 与计费](https://www.krea.ai/docs/cn/developers/api-keys-and-billing.md)。

**1. 上传参考图**

使用 `POST /assets` 上传你的输入图像，响应中会返回 `image_url`。你也可以直接在 `image_urls` 中传入外部图像 URL 或 base64 data URI。

**2. 创建编辑**

携带提示词和参考图调用 `POST /generate/image/krea/krea-3`，并保存响应中的 `job_id`。

**3. 获取结果**

轮询 `GET /jobs/{job_id}`，直到 `status` 变为 `completed`。输出位于 `result.urls[0]`。

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
# Bash + curl + jq. Set KREA_API_KEY to your API token first.
set -euo pipefail
: "${KREA_API_KEY:?Set your Krea API token}"

# 1. Upload a reference
ASSET=$(curl --fail-with-body --silent --show-error --max-time 60 \
  https://api.krea.ai/assets \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -F "file=@reference.png")

IMAGE_URL=$(printf '%s' "$ASSET" | jq -er '.image_url')

# 2. Create an edit
PAYLOAD=$(jq -n --arg image "$IMAGE_URL" '{
  prompt: "Place the product on a clean studio background",
  thinking_mode: "fast",
  image_urls: [$image],
  resolution: "2K"
}')

JOB=$(curl --fail-with-body --silent --show-error --max-time 60 \
  https://api.krea.ai/generate/image/krea/krea-3 \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$PAYLOAD")

JOB_ID=$(printf '%s' "$JOB" | jq -er '.job_id')

# 3. Get the result
for attempt in $(seq 1 150); do
  JOB=$(curl --fail-with-body --silent --show-error --max-time 30 \
    "https://api.krea.ai/jobs/$JOB_ID" \
    -H "Authorization: Bearer $KREA_API_KEY")
  STATUS=$(printf '%s' "$JOB" | jq -er '.status')
  case "$STATUS" in
    completed)
      printf '%s' "$JOB" | jq -er '.result.urls[0]'
      exit 0 ;;
    failed|cancelled)
      printf 'Job ended: %s\n' "$STATUS" >&2; exit 1 ;;
    scheduled|processing|queued|backlogged|sampling|intermediate-complete)
      sleep 2 ;;
    *) printf 'Unexpected status: %s\n' "$STATUS" >&2; exit 1 ;;
  esac
done
printf 'Polling timed out\n' >&2
exit 1
```

```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
# Python 3 + requests: pip install requests
# Set KREA_API_KEY to your API token first.
import os
import time
import requests

api = "https://api.krea.ai"
headers = {"Authorization": f"Bearer {os.environ['KREA_API_KEY']}"}

# 1. Upload a reference
with open("reference.png", "rb") as image:
    response = requests.post(
        f"{api}/assets", headers=headers,
        files={"file": image}, timeout=60,
    )
response.raise_for_status()
image_url = response.json()["image_url"]

# 2. Create an edit
response = requests.post(
    f"{api}/generate/image/krea/krea-3",
    headers=headers,
    json={
        "prompt": "Place the product on a clean studio background",
        "thinking_mode": "fast",
        "image_urls": [image_url],
        "resolution": "2K",
    },
    timeout=60,
)
response.raise_for_status()
job_id = response.json()["job_id"]

# 3. Get the result
pending = {"scheduled", "processing", "queued", "backlogged",
           "sampling", "intermediate-complete"}
deadline = time.monotonic() + 300

while time.monotonic() < deadline:
    response = requests.get(
        f"{api}/jobs/{job_id}", headers=headers, timeout=30,
    )
    response.raise_for_status()
    job = response.json()
    if job["status"] == "completed":
        print(job["result"]["urls"][0])
        break
    if job["status"] not in pending:
        raise RuntimeError(f"Job ended: {job['status']}")
    time.sleep(2)
else:
    raise TimeoutError("Polling timed out")
```

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
// Node.js 22+. Save as example.mjs.
// Set KREA_API_KEY to your API token first.
import { readFile } from "node:fs/promises";

const token = process.env.KREA_API_KEY;
if (!token) throw new Error("Set your Krea API token");
const api = "https://api.krea.ai";
const headers = { Authorization: `Bearer ${token}` };

async function request(path, options = {}) {
  const response = await fetch(`${api}${path}`, {
    ...options,
    headers: { ...headers, ...options.headers },
    signal: AbortSignal.timeout(60_000),
  });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

// 1. Upload a reference
const form = new FormData();
form.append("file", new Blob([await readFile("reference.png")]), "reference.png");
const asset = await request("/assets", { method: "POST", body: form });

// 2. Create an edit
const job = await request("/generate/image/krea/krea-3", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    prompt: "Place the product on a clean studio background",
    thinking_mode: "fast",
    image_urls: [asset.image_url],
    resolution: "2K",
  }),
});

// 3. Get the result
const pending = new Set([
  "scheduled", "processing", "queued", "backlogged",
  "sampling", "intermediate-complete",
]);
const deadline = Date.now() + 300_000;
let imageUrl;

while (Date.now() < deadline) {
  const result = await request(`/jobs/${job.job_id}`);
  if (result.status === "completed") {
    imageUrl = result.result.urls[0];
    break;
  }
  if (!pending.has(result.status)) {
    throw new Error(`Job ended: ${result.status}`);
  }
  await new Promise((resolve) => setTimeout(resolve, 2_000));
}
if (!imageUrl) throw new Error("Polling timed out");
console.log(imageUrl);
```

```javascript Node.js (SDK) theme={"theme":{"light":"github-light-default","dark":"vesper"}}
// npm install @krea-ai/sdk
import { openAsBlob } from "node:fs";
import { Krea } from "@krea-ai/sdk";

const krea = new Krea({ apiKey: process.env.KREA_API_KEY });

// 1. Upload a reference
const file = await openAsBlob("./reference.png", { type: "image/png" });
const asset = await krea.assets.upload(file, {
  filename: "reference.png",
});

// 2. Create an edit and wait for the result
const result = await krea.subscribe("image/krea/krea-3", {
  input: {
    prompt: "Place the product on a clean studio background",
    image_urls: [asset.image_url],
    thinking_mode: "fast",
    resolution: "2K",
  },
});

console.log(result.data?.urls[0]);
```

> [!TIP]
>
> 请将 API token 保存在你的服务器上，切勿将其放入客户端代码。

## 参数

| 字段 | 类型 | 说明 |
| - | - | - |
| `prompt` | string | 编辑指令。描述哪些需要改变、哪些保持不变。如果至少一个区域包含 `note`，则可以省略。 |
| `image_urls` | array of strings | 可选。输入的参考图，最多 8 张。编辑时至少包含一张；文生图时省略。支持来自 `POST /assets` 的 `image_url`、外部 URL 或 base64 data URI。 |
| `thinking_mode` | enum | 可选。`fast`（默认）、`high` 或 `ultra`。参见[思考模式](#thinking-modes)。 |
| `priority` | enum | 可选。仅接受 `normal`（默认值）。 |
| `resolution` | enum | 除非设置了 `width` 和 `height`，否则必填。`1K`、`2K` 或 `4K`。也接受小写。不要与 `width` 和 `height` 一起使用。 |
| `aspect_ratio` | enum | 可选。取值为 `1:1`、`4:5`、`3:4`、`2:3`、`9:16`、`5:4`、`4:3`、`3:2`、`16:9`、`21:9` 之一。与 `resolution` 搭配使用。省略则自动构图。 |
| `width` / `height` | integers | 除非设置了 `resolution`，否则必须同时设置。请求的尺寸，均为不超过 4096 的正整数。不能与 `aspect_ratio` 或 `resolution` 一起使用。 |
| `seed` | integer | 可选。省略则随机选择种子。 |
| `negative_prompt` | string | 可选。需要避免的内容，最多 1,024 个字符。 |
| `regions` | array of regions | 可选。提供后，可以使用边界框进行区域编辑。参见[边界框](#bounding-boxes)。 |
| `regional_edit` | boolean | 可选。设为 `true` 可进行局部编辑，并让图像其余部分保持原样。`image_urls` 中至少需要一张图像。参见[区域编辑](#regional-edits)。 |

请设置 `resolution`，或同时设置 `width` 和 `height`。API 会返回：

* `Provide resolution or width and height.`
* `width and height must be set together.`
* `aspect_ratio cannot be used with width/height.`
* `resolution cannot be used with width/height.`

> [!NOTE]
>
> 使用 `width` 和 `height` 时，输出会被调整到最接近的受支持宽高比以及 1K 或 2K 画布，不保证精确的像素尺寸。
>
> 重复使用同一个 `seed` 并不能保证得到完全相同的结果，因为提示词扩展步骤在每次运行时可能有所不同。

## 思考模式

在生成之前，Krea 3 会先理解你的提示词。`thinking_mode` 决定它进行多少规划。

| 模式 | 处理方式 | 适用场景 |
| - | - | - |
| `fast` | Krea 快速扩展提示词，然后生成。速度最快。**默认且推荐。** | 清晰、简单的编辑以及大多数日常请求。 |
| `high` | Krea 使用更强的推理引擎，根据提示词和参考图规划更复杂的编辑，然后生成。速度较慢。 | 复杂或多步骤的编辑、需要组合多张参考图，或 `fast` 的结果未能满足请求时。 |
| `ultra` | Krea 使用智能体框架（agentic harness）。始终为 2K。速度最慢：单个任务可能需要几分钟。 | 质量比速度或成本更重要的最终、高要求编辑。 |

如果省略 `thinking_mode`，API 会使用 `fast`。

### Ultra

`ultra` 面向 Max 及以上套餐的工作区开放。其他工作区会收到 `402` 和 `K3_ULTRA_ACCESS_REQUIRED`。

* `image_urls` 中至少包含一张图像。使用 `ultra` 的纯文本请求会以 `fast` 运行，并按 `fast` 计费。
* 输出始终为 2K。将 `resolution` 设为 `2K`；不支持 `1K` 和 `4K`。
* 使用 `aspect_ratio` 设置画面比例。不支持 `width` 和 `height`。
* 不支持 `negative_prompt`、`loras` 和 `style_urls`。
* 不支持 [Zero Data Retention](#zero-data-retention)。
* 每个请求生成一张图像。一次运行可能需要几分钟。请使用 [webhook](https://www.krea.ai/docs/cn/developers/webhooks.md)，或以较长的超时时间进行轮询。

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "prompt": "Put the sneaker from the second image on the person in the first image",
  "image_urls": ["PERSON_IMAGE_URL", "SNEAKER_IMAGE_URL"],
  "thinking_mode": "ultra",
  "resolution": "2K",
  "aspect_ratio": "4:5"
}
```

## 边界框

`regions` 可在 `image_urls` 中的任意图像上指定边界框。每个框都可以带一个可选的 `note`。必须提供 `prompt`，或者至少一个 `note`。坐标是相对图像宽度和高度的 0 到 1 的比例，`x` 和 `y` 为左上角。最多支持 24 个区域。

### 参数

| 字段 | 类型 | 说明 |
| - | - | - |
| `image_idx` | integer | **必填。** `image_urls` 中绘制该边界框的图像的索引。 |
| `x`, `y` | floats | **必填。** 边界框的左上角。取值是相对图像宽度和高度的 0 到 1 的比例。 |
| `width`, `height` | floats | **必填。** 边界框的宽度和高度，分别向右和向下延伸。取值是相对图像宽度和高度的 0 到 1 的比例。 |
| `label` | string | 可选。该边界框的标签，不能包含空白字符。在提示词或其他框的 `note` 中，用 `@label` 引用它。省略时，第一个框为 `@1`，第二个为 `@2`，依此类推。 |
| `note` | string | 可选。该边界框的提示词。可以通过 `@label` 引用其他边界框。 |

## 区域编辑

设置 `regional_edit: true` 后，Krea 3 只会重新生成图像中需要改变的部分，其余部分完全保持原样。因此你可以反复编辑同一张图像而不损失画质。

**将它用于局部编辑**，即图像其余部分必须逐像素保持不变的情况：为物体换色或替换物体、添加或移除元素、修正细节，或更改招牌上的文字。在最新输出上连续编辑时，这是最稳妥的方式。

**对于需要重新渲染整张图像的全局编辑，请不要使用它**：例如更换风格、调整光照、改变季节或时间、重新构图，或将多张图像合成为新场景。常规编辑会重新渲染整张图像，因此如果你不断在最新输出上继续编辑，瑕疵可能会逐渐累积。

区域编辑要求 `image_urls` 中至少有一张图像。

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "prompt": "Change the mug to red, keeping everything else the same",
  "image_urls": ["IMAGE_URL"],
  "thinking_mode": "fast",
  "resolution": "2K",
  "regional_edit": true
}
```

## 提示词编写

Krea 3 是一款遵循指令的编辑器。请用自然语言描述你的编辑：

* 先写要做的改动，只补充有助于执行改动的细节。
* 如果图像其余部分需要保持不变，在结尾加一句保留说明即可。不要逐一列出所有需要保持不变的内容。
* 当提示词涉及多张图像时，用每张图像所展示的内容来指代它。例如："Put the sneaker from the second image on the person in the first image."

```text theme={"theme":{"light":"github-light-default","dark":"vesper"}}
Change the mug to red, keeping everything else the same.
```

## 参考图

* Krea 3 会按上传时的分辨率使用每张参考图。超过 4 MP 的参考图会被缩放到 4 MP。
* 大多数编辑使用约 1 MP 的图像就足够了。发送前不要对参考图进行放大。
* 当细节很重要时（小字、标志、面料、远景中的人脸），请发送你手头分辨率最高的图像版本。
* 单个请求中有五张或更多参考图时，每张参考图的长边会被缩放到最多 1536 px。如需保留完整细节，请发送四张或更少。

## Zero Data Retention

Krea 3 为企业工作区支持 [Zero Data Retention](https://www.krea.ai/docs/cn/developers/zdr.md)。请发送 `X-Api-Zero-Data-Retention: 1` 请求头。启用 Zero Data Retention 时：

* `image_urls` 中的每张图像都必须是 base64 data URI。
* `thinking_mode` 可以是 `fast` 或 `high`。带图像的 `ultra` 请求会返回 `422`。
* `resolution` 可以是 `1K` 或 `2K`。`4K` 会返回 `422`。
* 单个请求最多可使用 8 张参考图。
* 支持[边界框](#bounding-boxes)。

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
IMAGE_DATA_URI="data:image/png;base64,$(base64 < ./reference.png | tr -d '\n')"

curl -X POST https://api.krea.ai/generate/image/krea/krea-3 \
  -H "Authorization: Bearer $KREA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "X-Api-Zero-Data-Retention: 1" \
  -d '{
    "prompt": "Change the mug to red, keeping everything else the same",
    "image_urls": ["'"$IMAGE_DATA_URI"'"],
    "thinking_mode": "fast",
    "resolution": "2K"
  }'
```

```javascript Node.js (SDK) theme={"theme":{"light":"github-light-default","dark":"vesper"}}
// npm install @krea-ai/sdk
import { readFile } from "node:fs/promises";
import { Krea } from "@krea-ai/sdk";

const krea = new Krea({ apiKey: process.env.KREA_API_KEY });

const bytes = await readFile("reference.png");
const imageDataUri = `data:image/png;base64,${bytes.toString("base64")}`;

const result = await krea.subscribe("image/krea/krea-3", {
  headers: { "X-Api-Zero-Data-Retention": "1" },
  input: {
    prompt: "Change the mug to red, keeping everything else the same",
    image_urls: [imageDataUri],
    thinking_mode: "fast",
    resolution: "2K",
  },
});

console.log(result.data?.urls[0]);
```

## 错误

| 状态 | 消息 |
| - | - |
| `400` | `Invalid JSON: …` |
| `400` | `Select a workspace before generating.` |
| `401` | `Unauthorized` |
| `422` | `Validation failed` |

校验错误会在 `details` 中列出每个问题：

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "error": "Validation failed",
  "details": [
    {
      "field": "resolution",
      "message": "Invalid enum value. Expected '1K' | '2K' | '4K'",
      "code": "invalid_value"
    }
  ]
}
```

以下字段暂不可用。发送其中任一字段会返回 `422`，消息如下：

| 字段 | 消息 |
| - | - |
| `loras` | `LoRAs are coming soon to the API.` |
| `style_urls` | `Style references are coming soon to the API.` |

## 定价

每张图像的价格取决于输出分辨率、思考模式和参考图。

| 计费项 | 1K 输出 | 2K 输出 |
| - | - | - |
| 基础价格 | \$0.03 | \$0.06 |
| 每张 1K 参考图 | +\$0.02 | +\$0.02 |
| 每张 2K 参考图 | +\$0.07 | +\$0.07 |
| `high` 思考模式 | 每次生成 +\$0.02 | 每次生成 +\$0.02 |
| `ultra` 思考模式 | 不可用 | 每次生成 +\$0.20 |

`4K` 图像按 2K 图像加上 2 倍放大的费用计费。

使用 `ultra` 时，前四张参考图每张按 $0.07 计费，其余每张按 $0.02 计费，与尺寸无关。

在 [API 定价页面 ↗](https://www.krea.ai/app/api/pricing) 比较所有模型的价格，或在 [Krea API 页面 ↗](https://www.krea.ai/features/api) 了解你可以构建什么。

## 相关内容

> [card] [任务生命周期](https://www.krea.ai/docs/cn/developers/job-lifecycle.md)
>
> 任务状态、轮询与结果。

> [card] [Webhooks](https://www.krea.ai/docs/cn/developers/webhooks.md)
>
> 任务完成时接收通知，无需轮询。


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