Skip to main content
AIOAGI 提供多类图像生成模型。本页只介绍 GPT-Image 系列的 OpenAI 兼容接口调用方式。你可以直接复用 OpenAI 风格的请求格式,并将基础地址设置为 https://api.aiearth.dev/v1https://api.aiearth.vip/v1
站内还提供 banana 等其他图像模型系列。模型名称、价格、输出格式和支持策略可能调整。请在 控制台开发者指南 中确认当前可用模型,再上线生产调用。

接口概览

接口方法说明
/images/generationsPOST根据提示词生成新图像。
/images/editsPOST基于一张或多张输入图像生成编辑结果。

创建图像

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

常用参数

参数类型说明
promptstring必填。输入图像描述。
modelstring可选。本文示例使用 gpt-image-2。你也可以按控制台展示切换到其他 GPT-Image 系列模型。
sizestring可选。常用值包括 1024x10241536x10241024x1536auto
qualitystring可选。GPT-Image 模型常用 lowmediumhighauto
backgroundstring可选。可设为 transparentopaqueauto
output_formatstring可选。GPT-Image 模型常用 pngjpegwebp
output_compressionnumber可选。jpegwebp 输出时可设置压缩比例。
nnumber可选。生成图片数量。部分模型限制更严格,请以控制台和开发者指南为准。
moderationstring可选。GPT-Image 模型可使用 autolow
streamboolean可选。设为 true 后可以接收流式部分图像事件。
userstring可选。用于标识你的终端用户。

请求示例

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": "1024x1536"
  }'

Python 示例

下面的示例基于你提供的最新本地脚本整理,保留了直接配置 API_KEYAPI_URL 的使用方式、原始响应日志输出和图片下载流程。
import requests
import json

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

payload = {
    "size": "1024x1536",
    "prompt": "A picture of a chinese dance scene.",
    "model": "gpt-image-2",
    "n": 1
}

headers = {
    'Accept': 'application/json',
    '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_url = result['data'][0]['url']
    print(f"图片URL: {image_url}")

    img_response = requests.get(image_url)
    if img_response.status_code == 200:
        output_path = "generated_image.webp"
        with open(output_path, "wb") as f:
            f.write(img_response.content)
        print(f"图片已保存: {output_path}")
    else:
        print(f"下载图片失败: {img_response.status_code}")
else:
    print(f"请求失败: {response.status_code}")
    print(f"错误信息: {response.text}")

典型返回

AIOAGI 站内这类调用通常直接返回图片 URL。常见结构如下:
{
  "created": 1776795032,
  "data": [
    {
      "revised_prompt": "",
      "url": "https://filesystem.site/cdn/20260422/8685cef269d5bfa5a284f67b0d9571.webp"
    }
  ]
}

生成效果示意

GPT-Image 系列图像生成效果示意

返回说明

  • 本站这类图像生成请求通常优先返回 url,你可以直接下载结果图。
  • 如果返回结果和预期不一致,请先检查脚本生成的 response_create.txt 日志文件。
  • 不同模型的返回结构可能略有差异,请以实际响应为准。
  • 如果你开启 stream: true,常见事件类型为 image_generation.partial_imageimage_generation.completed
公开文档不能写入真实 API Key。如果你需要给读者展示直写配置形式,请使用 sk-your-api-key 这类占位值,不要把生产密钥提交到仓库。

编辑图像

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

常用参数

参数类型说明
imagesarray必填。输入图像列表。GPT-Image 模型通常最多支持 16 张。
promptstring必填。描述你希望对输入图像做出的修改。
modelstring可选。本文示例使用 gpt-image-2。你也可以按控制台展示切换到其他 GPT-Image 系列模型。
input_fidelitystring可选。可设为 highlow,用于控制对原图的保真程度。
maskobject可选。可通过 file_idimage_url 指定遮罩图。
backgroundstring可选。可设为 transparentopaqueauto
qualitystring可选。常用值包括 lowmediumhighauto
sizestring可选。常用值包括 1024x10241536x10241024x1536auto
output_formatstring可选。常用值包括 pngjpegwebp
output_compressionnumber可选。jpegwebp 输出时可设置压缩比例。
streamboolean可选。设为 true 后可以接收流式部分图像事件。
userstring可选。用于标识你的终端用户。

请求示例

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 输入、本地文件输入、原始响应日志保存和结果图片落盘逻辑。
import requests
import base64
from io import BytesIO

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://filesystem.site/cdn/20260422/e15276c9f0f1ff1a4a0deb61273886.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']):
        if 'b64_json' in img_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}")
        elif 'url' in img_data:
            img_response = requests.get(img_data['url'])
            if img_response.status_code == 200:
                output_path = f"edited_image_{i+1}.png"
                with open(output_path, 'wb') as f:
                    f.write(img_response.content)
                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 系列图像编辑效果示意

返回说明

  • 本站这类图像编辑请求既可能返回 b64_json,也可能直接返回 url
  • 如果返回结果和预期不一致,请先检查脚本生成的 response_edit.txt 日志文件。
  • 示例代码已经兼容两种结果处理方式。
  • 如果你开启 stream: true,常见事件类型为 image_edit.partial_imageimage_edit.completed

调用建议

  • 为图像任务单独创建 Token 组,这样更容易做额度控制和账单追踪。
  • 在服务端记录请求 ID、模型名、耗时和错误信息,便于排查失败请求。
  • 如果你需要透明背景,请同时确认 backgroundoutput_format 是否匹配。
  • 在生产环境上线前,请先在 控制台开发者指南 中核对当前支持的模型名称、价格和额度策略。