> ## 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 就会在几秒内完成编辑。你也可以用它进行文生图。

<Info>
  Krea 3 API 目前处于**抢先体验**阶段，只有加入 Krea 3 测试计划的工作区才能调用。如需申请访问权限，请联系 [sales@krea.ai](mailto:sales@krea.ai)。
</Info>

## 端点

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

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

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

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

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

  <Step title="创建编辑">
    携带提示词和参考图调用 `POST /generate/image/krea/krea-3`，并保存响应中的 `job_id`。
  </Step>

  <Step title="获取结果">
    轮询 `GET /jobs/{job_id}`，直到 `status` 变为 `completed`。输出位于 `result.urls[0]`。
  </Step>
</Steps>

<CodeGroup>
  ```bash cURL theme={null}
  # Bash + curl + jq. Set KREA_API_TOKEN to your API token first.
  set -euo pipefail
  : "${KREA_API_TOKEN:?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_TOKEN" \
    -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_TOKEN" \
    -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_TOKEN")
    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={null}
  # Python 3 + requests: pip install requests
  # Set KREA_API_TOKEN to your API token first.
  import os
  import time
  import requests

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

  # 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={null}
  // Node.js 22+. Save as example.mjs.
  // Set KREA_API_TOKEN to your API token first.
  import { readFile } from "node:fs/promises";

  const token = process.env.KREA_API_TOKEN;
  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);
  ```
</CodeGroup>

<Tip>
  请将 API token 保存在你的服务器上，切勿将其放入客户端代码。
</Tip>

## 参数

| 字段 | 类型 | 说明 |
| - | - | - |
| `prompt` | string | **必填。** 编辑指令。描述哪些需要改变、哪些保持不变。 |
| `image_urls` | array of strings | 可选。输入的参考图，最多 8 张。编辑时至少包含一张；文生图时省略。支持来自 `POST /assets` 的 `image_url`、外部 URL 或 base64 data URI。 |
| `thinking_mode` | enum | 可选。`fast`（默认）或 `high`。参见[思考模式](#thinking-modes)。 |
| `resolution` | enum | `1k` 或 `2k`。除非同时提供 `width` 和 `height`，否则为必填。不要与 `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 | 可选。请求的尺寸，均为不超过 4096 的正整数。需同时提供两者，且不要同时使用 `resolution` 或 `aspect_ratio`。 |
| `seed` | integer | 可选。省略则随机选择种子。 |
| `negative_prompt` | string | 可选。需要避免的内容，最多 1,024 个字符。 |
| `regional_edit` | boolean | 可选。设为 `true` 可进行局部编辑，并让图像其余部分保持原样。`image_urls` 中至少需要一张图像。参见[区域编辑](#regional-edits)。 |

<Note>
  使用 `width` 和 `height` 时，输出会被调整到最接近的受支持宽高比以及 1k 或 2k 画布，不保证精确的像素尺寸。

  重复使用同一个 `seed` 并不能保证得到完全相同的结果，因为提示词扩展步骤在每次运行时可能有所不同。
</Note>

<h2 id="thinking-modes">
  思考模式
</h2>

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

| 模式 | 处理方式 | 适用场景 |
| - | - | - |
| `fast` | Krea 快速扩展提示词，然后生成。速度最快。**默认且推荐。** | 清晰、简单的编辑以及大多数日常请求。 |
| `high` | Krea 使用更强的推理引擎，根据提示词和参考图规划更复杂的编辑，然后生成。速度较慢。 | 复杂或多步骤的编辑、需要组合多张参考图，或 `fast` 的结果未能满足请求时。 |

如果省略 `thinking_mode`，API 会使用 `fast`。两种模式都支持 `regional_edit`。

<h2 id="regional-edits">
  区域编辑
</h2>

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

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

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

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

```json theme={null}
{
  "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={null}
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](/docs/cn/developers/zdr)。请发送 `X-Api-Zero-Data-Retention: 1` 请求头。启用 Zero Data Retention 时：

* `image_urls` 中的每张图像都必须是 base64 data URI。
* `thinking_mode` 可以是 `fast` 或 `high`。
* 单个请求最多可使用 4 张参考图。

```bash theme={null}
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_TOKEN" \
  -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"
  }'
```

## 定价

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

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

## 相关内容

<CardGroup cols={2}>
  <Card title="任务生命周期" icon="arrows-rotate" href="/docs/cn/developers/job-lifecycle">
    任务状态、轮询与结果。
  </Card>

  <Card title="Webhooks" icon="bell" href="/docs/cn/developers/webhooks">
    任务完成时接收通知，无需轮询。
  </Card>
</CardGroup>


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