# 生成与编辑图像 (/docs/cloud/services/model/guides/images)



使用 OpenAI Images API 的 `gpt-image-2` 生成和编辑图片。调用前查 `GET /openai/v1/models?api=images`；原生模型目录分别声明 `openai.images.generations` 和 `openai.images.edits`。

## 1. 准备终端 [#1-准备终端]

准备 Python 3.10+ 和 [uv](https://docs.astral.sh/uv/getting-started/installation/)。将 [Praxis 云 API Key](/docs/cloud/account/api-keys) 放入环境变量 `PRAXIS_API_KEY`，不要写入代码或日志。

```bash
test -n "$PRAXIS_API_KEY"
```

期望：退出码为 0。退出码 1 表示变量未设置，先设置再继续。示例默认使用 `https://api.deepraxis.ai`。切换环境时，将 `PRAXIS_API_BASE` 设为相应 API 域名，不带末尾斜杠或 API 路径。

## 2. 生成并编辑 [#2-生成并编辑]

在可写目录运行。示例会产生两次图像调用费用：生成一次、编辑一次，并保存 `circle.png` 与 `circle-edited.png`；使用新目录避免覆盖同名文件。示例关闭自动重试。

保存为 `images.py`，运行 `uv run -q --no-project --with openai --with anthropic --with google-genai python images.py`。

```python
import base64
import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(api_key=os.environ['PRAXIS_API_KEY'],
    base_url=os.environ.get('PRAXIS_API_BASE', 'https://api.deepraxis.ai') + '/openai/v1',
    timeout=180, max_retries=0)
models = client.models.list(extra_query={'api': 'images'})
print('X-Request-Id:', models._request_id)
assert 'gpt-image-2' in [model.id for model in models]

def save(response, filename):
    print('X-Request-Id:', response._request_id)
    assert len(response.data) == 1 and response.data[0].b64_json
    image = base64.b64decode(response.data[0].b64_json, validate=True)
    assert image.startswith(b'\x89PNG\r\n\x1a\n'), 'Expected PNG output'
    Path(filename).write_bytes(image)
    assert response.usage is not None, 'Usage was not reported'
    print(filename, len(image), 'bytes; usage:', response.usage.model_dump())

save(client.images.generate(model='gpt-image-2',
    prompt='A single blue circle centered on a plain white background.',
    n=1, size='1024x1024', quality='low'), 'circle.png')
with open('circle.png', 'rb') as image:
    save(client.images.edit(model='gpt-image-2', image=image,
        prompt='Change the blue circle to a red circle. Keep the white background.',
        n=1, size='1024x1024', quality='low'), 'circle-edited.png')
```

期望：两个文件都是非空 PNG，每次响应包含一张图片和 token 用量，退出码 0。打开图片：第一张应为白底蓝圆，第二张应为白底红圆。文件签名检查验证格式，不代替画面检查。

## 3. 查看图像费用 [#3-查看图像费用]

`gpt-image-2` 按 token 计价，不是每张固定价。文本输入、图像输入、图像输出分别计价；编辑还会产生输入图像 token。查看响应中的用量，以及[模型目录](https://console.deepraxis.ai/models/gpt-image-2)中的实时价格；账户汇总见[用量与费用](/docs/cloud/account/billing)。

若目录断言失败，先停止生成，选择当前可用的图像模型。若输出断言失败，保留请求 ID 和响应错误，不要为排查文件问题反复生成。

操作细节：[生成](/docs/api/compatible/openai/createImage)与[编辑](/docs/api/compatible/openai)。

[API 参考 →](/docs/api/compatible/openai) · [Cookbook →](/docs/cookbook)
