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

# gpt-image-2

> 使用 OpenAI 兼容图像接口调用 AIOAGI 的 gpt-image-2 图像生成与编辑能力。

`gpt-image-2` 使用官方图像接口。你可以通过 `/images/generations` 创建图像，也可以通过 `/images/edits` 提交参考图并生成编辑结果。

<Info>
  AIOAGI 的 `gpt-image-2` 返回与官方一致，图片结果通过 `b64_json` 返回，不返回图片 URL。你需要先 Base64 解码再保存图片。
</Info>

## 官方参考

* [Images generate（OpenAI Developers）](https://developers.openai.com/api/reference/python/resources/images/methods/generate)
* [Images edit（OpenAI Developers）](https://developers.openai.com/api/reference/python/resources/images/methods/edit)

## 创建图像

**POST** `/images/generations`

你可以用这个接口根据 `prompt` 直接生成图像。常见场景包括海报草图、产品配图、插画素材和视觉创意探索。

### 常用参数

| 参数                   | 类型        | 说明                                                        |
| -------------------- | --------- | --------------------------------------------------------- |
| `prompt`             | `string`  | 必填。输入图像描述。                                                |
| `model`              | `string`  | 可选。本文示例使用 `gpt-image-2`。你也可以按控制台展示切换到其他 `GPT-Image` 系列模型。 |
| `size`               | `string`  | 可选。常用值包括 `1024x1024`、`1536x1024`、`1024x1536` 或 `auto`。    |
| `quality`            | `string`  | 可选。GPT-Image 模型常用 `low`、`medium`、`high` 或 `auto`。         |
| `background`         | `string`  | 可选。可设为 `transparent`、`opaque` 或 `auto`。                   |
| `output_format`      | `string`  | 可选。GPT-Image 模型常用 `png`、`jpeg` 或 `webp`。                  |
| `output_compression` | `number`  | 可选。`jpeg` 或 `webp` 输出时可设置压缩比例。                            |
| `partial_images`     | `number`  | 可选。流式响应中的中间图数量，取值通常为 `0` 到 `3`。                           |
| `n`                  | `number`  | 可选。生成图片数量。部分模型限制更严格，请以控制台和开发者指南为准。                        |
| `moderation`         | `string`  | 可选。GPT-Image 模型可使用 `auto` 或 `low`。                        |
| `stream`             | `boolean` | 可选。设为 `true` 后可以接收流式部分图像事件。                               |
| `user`               | `string`  | 可选。用于标识你的终端用户。                                            |

<Warning>
  `response_format` 是 `dall-e-2` 和 `dall-e-3` 的返回格式参数。GPT-Image 官方接口不支持该参数，`gpt-image-2` 返回 `b64_json`。
</Warning>

### 请求示例

```bash theme={null}
curl https://api.aiearth.dev/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-your-api-key" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "A cute baby sea otter",
    "n": 1,
    "size": "1024x1024",
    "quality": "medium",
    "background": "transparent",
    "output_format": "png"
  }'
```

### Python 示例

下面的示例会从 `b64_json` 解码图片，并保留原始响应日志，便于排查问题。

```python theme={null}
import base64
import requests

API_KEY = 'sk-your-api-key'
API_URL = 'https://api.aiearth.dev/v1/images/generations'

payload = {
    "model": "gpt-image-2",
    "prompt": "A product photo of a ceramic coffee cup on a wooden table.",
    "n": 1,
    "size": "1024x1024",
    "quality": "medium",
    "output_format": "png"
}

headers = {
    'Authorization': f'Bearer {API_KEY}',
    'Content-Type': 'application/json'
}

print("正在生成图片...")
response = requests.post(API_URL, headers=headers, json=payload)

response_text = response.text
print("\n原始响应:")
print(response_text)

log_path = "response_create.txt"
with open(log_path, "w", encoding="utf-8") as f:
    f.write(response_text)
print(f"响应已保存: {log_path}\n")

if response.status_code == 200:
    result = response.json()
    print("请求成功!")
    print(f"生成时间: {result['created']}")

    image_data = result['data'][0]
    output_path = "generated_image.png"

    image_bytes = base64.b64decode(image_data['b64_json'])
    with open(output_path, "wb") as f:
        f.write(image_bytes)
    print(f"图片已保存: {output_path}")
else:
    print(f"请求失败: {response.status_code}")
    print(f"错误信息: {response.text}")
```

### 官方返回结构

GPT-Image 官方接口通常返回 `b64_json`，并可能包含 `usage` 用量信息。常见结构如下：

```json theme={null}
{
  "created": 1713833628,
  "data": [
    {
      "b64_json": "..."
    }
  ],
  "usage": {
    "total_tokens": 100,
    "input_tokens": 50,
    "output_tokens": 50,
    "input_tokens_details": {
      "text_tokens": 10,
      "image_tokens": 40
    }
  }
}
```

### 返回说明

* `gpt-image-2` 返回 `b64_json`，你需要先 Base64 解码再保存图片。
* 如果返回结果和预期不一致，请先检查脚本生成的 `response_create.txt` 日志文件。
* `usage` 等统计字段可能随模型和请求参数略有差异，请以实际响应为准。
* 如果你开启 `stream: true`，常见事件类型为 `image_generation.partial_image` 和 `image_generation.completed`。

## 编辑图像

**POST** `/images/edits`

你可以提交一张或多张参考图，再结合提示词生成新的编辑结果。这个接口适合局部重绘、风格迁移、素材拼接和多图组合。

### 常用参数

| 参数                   | 类型        | 说明                                                        |
| -------------------- | --------- | --------------------------------------------------------- |
| `images`             | `array`   | 必填。输入图像列表。GPT-Image 模型通常最多支持 16 张。                        |
| `prompt`             | `string`  | 必填。描述你希望对输入图像做出的修改。                                       |
| `model`              | `string`  | 可选。本文示例使用 `gpt-image-2`。你也可以按控制台展示切换到其他 `GPT-Image` 系列模型。 |
| `input_fidelity`     | `string`  | 可选。可设为 `high` 或 `low`，用于控制对原图的保真程度。                       |
| `mask`               | `object`  | 可选。可通过 `file_id` 或 `image_url` 指定遮罩图。                     |
| `background`         | `string`  | 可选。可设为 `transparent`、`opaque` 或 `auto`。                   |
| `quality`            | `string`  | 可选。常用值包括 `low`、`medium`、`high` 或 `auto`。                  |
| `size`               | `string`  | 可选。常用值包括 `1024x1024`、`1536x1024`、`1024x1536` 或 `auto`。    |
| `output_format`      | `string`  | 可选。常用值包括 `png`、`jpeg` 或 `webp`。                           |
| `output_compression` | `number`  | 可选。`jpeg` 或 `webp` 输出时可设置压缩比例。                            |
| `partial_images`     | `number`  | 可选。流式响应中的中间图数量，取值通常为 `0` 到 `3`。                           |
| `n`                  | `number`  | 可选。生成图片数量。部分模型限制更严格，请以控制台和开发者指南为准。                        |
| `moderation`         | `string`  | 可选。GPT-Image 模型可使用 `auto` 或 `low`。                        |
| `stream`             | `boolean` | 可选。设为 `true` 后可以接收流式部分图像事件。                               |
| `user`               | `string`  | 可选。用于标识你的终端用户。                                            |

### 请求示例

```bash theme={null}
curl -X POST "https://api.aiearth.dev/v1/images/edits" \
  -H "Authorization: Bearer sk-your-api-key" \
  -F "model=gpt-image-2" \
  -F "image[]=@body-lotion.png" \
  -F "image[]=@bath-bomb.png" \
  -F "image[]=@incense-kit.png" \
  -F "image[]=@soap.png" \
  -F "prompt=Create a lovely gift basket with these four items in it" \
  -F "quality=high" \
  -F "size=1024x1024" \
  -F "output_format=png"
```

### Python 示例

下面的示例兼容 URL 输入和本地文件输入，并从 `b64_json` 解码保存结果图片。

```python theme={null}
import base64
from io import BytesIO

import requests

API_KEY = 'sk-your-api-key'
API_URL = 'https://api.aiearth.dev/v1/images/edits'


def download_image(url):
    """从URL下载图片并返回字节数据"""
    response = requests.get(url)
    if response.status_code == 200:
        return response.content
    raise Exception(f"下载图片失败: {response.status_code}")


images = [
    "https://example.com/source-image.webp",
    # "local_image.png",
]

prompt = "Add a watercolor effect to this image"
model = "gpt-image-2"
background = "transparent"
input_fidelity = "high"
quality = "high"
size = "1024x1024"
output_format = "png"
output_compression = 100
n = 1
moderation = "auto"

files = []
data = {}

for i, img in enumerate(images):
    if img.startswith('http://') or img.startswith('https://'):
        img_data = download_image(img)
        files.append(('image[]', (f'image_{i}.webp', BytesIO(img_data), 'image/webp')))
    else:
        files.append(('image[]', open(img, 'rb')))

data['prompt'] = prompt
data['model'] = model
data['background'] = background
data['input_fidelity'] = input_fidelity
data['quality'] = quality
data['size'] = size
data['output_format'] = output_format
data['output_compression'] = str(output_compression)
data['n'] = str(n)
data['moderation'] = moderation

headers = {
    'Authorization': f'Bearer {API_KEY}'
}

print("正在编辑图片...")
response = requests.post(API_URL, headers=headers, data=data, files=files)

response_text = response.text
print("\n原始响应:")
print(response_text)

log_path = "response_edit.txt"
with open(log_path, "w", encoding="utf-8") as f:
    f.write(response_text)
print(f"响应已保存: {log_path}\n")

if response.status_code == 200:
    result = response.json()
    print("编辑成功!")
    print(f"生成时间: {result['created']}")
    print(f"背景类型: {result.get('background', 'N/A')}")
    print(f"输出格式: {result.get('output_format', 'N/A')}")
    print(f"输出质量: {result.get('quality', 'N/A')}")
    print(f"输出尺寸: {result.get('size', 'N/A')}")

    if 'usage' in result:
        usage = result['usage']
        print(f"\nToken使用:")
        print(f"  输入tokens: {usage['input_tokens']} (图片: {usage['input_tokens_details']['image_tokens']}, 文本: {usage['input_tokens_details']['text_tokens']})")
        print(f"  输出tokens: {usage['output_tokens']}")
        print(f"  总计tokens: {usage['total_tokens']}")

    for i, img_data in enumerate(result['data']):
        image_bytes = base64.b64decode(img_data['b64_json'])
        output_path = f"edited_image_{i+1}.{result.get('output_format', 'png')}"
        with open(output_path, 'wb') as f:
            f.write(image_bytes)
        print(f"图片已保存: {output_path}")

        if 'revised_prompt' in img_data:
            print(f"修订提示词: {img_data['revised_prompt']}")
else:
    print(f"请求失败: {response.status_code}")
    print(f"错误信息: {response.text}")

for _, file_tuple in files:
    if hasattr(file_tuple, 'close'):
        file_tuple.close()
    elif isinstance(file_tuple, tuple) and len(file_tuple) > 1:
        file_obj = file_tuple[1]
        if hasattr(file_obj, 'close'):
            file_obj.close()
```

### 返回说明

* `gpt-image-2` 图像编辑请求返回 `b64_json`，你需要先 Base64 解码再保存图片。
* 如果返回结果和预期不一致，请先检查脚本生成的 `response_edit.txt` 日志文件。
* 如果你开启 `stream: true`，常见事件类型为 `image_edit.partial_image` 和 `image_edit.completed`。
