Skip to main content

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-chat 使用 OpenAI 兼容的 /chat/completions 接口。它适合把图片作为对话上下文输入,再用自然语言描述你要生成或编辑的图像。 POST /chat/completions

官方参考

常用参数

参数类型说明
modelstring必填。固定传入 gpt-image-2-chat
messagesarray必填。对话消息列表。图片输入放在 content 数组中。
messages[].content[].typestring可传 textimage_url
messages[].content[].textstringtypetext 时使用。写入生成或编辑需求。你也可以在 prompt 开头写入尺寸前缀。
messages[].content[].image_url.urlstringtypeimage_url 时使用。支持公网图片 URL 或 data:image/...;base64,...
metadataobject可选。示例中用来传递 sizequality。实际支持项请以控制台和开发者指南为准。
streamboolean可选。设为 true 后按 Chat Completions 流式 chunk 返回。
max_completion_tokensnumber可选。限制输出 token 数。新项目优先使用该参数。
userstring可选。用于标识你的终端用户。
官方 Chat Completions 文档中,metadata 是附加到请求对象的键值对。AIOAGI 的 gpt-image-2-chat 示例使用 metadata.sizemetadata.quality 控制图像规格。请在 控制台开发者指南 中确认当前支持的取值。

尺寸设置

gpt-image-2-chat 支持两种尺寸设置方式。你可以在 metadata.size 中设置尺寸,也可以把尺寸写在 prompt 开头。 prompt 前缀格式如下:
3840x2160 'your prompt'
auto 'your prompt'
支持的常用尺寸示例:
尺寸说明
1024x1024正方形
1536x1024横版
1024x1536竖版
2048x20482K 正方形
2048x11522K 横版
3840x21604K 横版
2160x38404K 竖版
auto默认尺寸
自定义尺寸需要同时满足以下条件:
  • 宽和高都能被 16 整除。
  • 像素总数不少于 655360
  • 宽高比不超过 3:1

请求示例

curl https://api.aiearth.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-your-api-key" \
  -d '{
    "model": "gpt-image-2-chat",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "3840x2160 '参考这张图片,生成一张产品海报。保留主体风格,背景换成明亮的摄影棚。'"
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "https://example.com/source-image.png"
            }
          }
        ]
      }
    ],
    "stream": false
  }'

Python 示例

下面的示例展示完整调用流程。它会把公网图片或本地图片转换成 data:image/...;base64,...,这样可以减少图片 URL 无法被服务端访问的问题。
import base64
import json
import mimetypes
from pathlib import Path
from typing import Any
from urllib.parse import urlparse
from urllib.request import Request, urlopen

from openai import OpenAI

API_KEY = "sk-your-api-key"
BASE_URL = "https://api.aiearth.dev/v1/"

IMAGE_REF = "https://example.com/source-image.png"
QUESTION = "3840x2160 '参考这张图片,生成一张产品海报。保留主体风格,背景换成明亮的摄影棚。'"
STREAM = False


def guess_image_mime(source: str, content_type: str | None = None) -> str:
    if content_type:
        mime_type = content_type.split(";", 1)[0].strip().lower()
        if mime_type.startswith("image/"):
            return mime_type

    parsed_path = urlparse(source).path or source
    mime_type, _ = mimetypes.guess_type(parsed_path)
    if mime_type and mime_type.startswith("image/"):
        return mime_type

    return "image/jpeg"


def read_image_bytes(source: str) -> tuple[bytes, str]:
    if source.startswith(("http://", "https://")):
        request = Request(source, headers={"User-Agent": "Mozilla/5.0"})
        with urlopen(request, timeout=120) as response:
            image_bytes = response.read()
            content_type = response.headers.get("Content-Type")
        return image_bytes, guess_image_mime(source, content_type)

    image_path = Path(source).expanduser()
    return image_path.read_bytes(), guess_image_mime(str(image_path))


def image_reference_to_data_url(source: str) -> str:
    if source.startswith("data:image"):
        return source

    image_bytes, mime_type = read_image_bytes(source)
    base64_image = base64.b64encode(image_bytes).decode("utf-8")
    return f"data:{mime_type};base64,{base64_image}"


def serialize_for_log(value: Any) -> Any:
    if hasattr(value, "model_dump"):
        return value.model_dump(mode="json")
    if isinstance(value, dict):
        return {str(key): serialize_for_log(item) for key, item in value.items()}
    if isinstance(value, (list, tuple)):
        return [serialize_for_log(item) for item in value]
    return value


messages = [
    {
        "role": "user",
        "content": [
            {"type": "text", "text": QUESTION},
            {
                "type": "image_url",
                "image_url": {"url": image_reference_to_data_url(IMAGE_REF)},
            },
        ],
    }
]

client = OpenAI(
    base_url=BASE_URL,
    api_key=API_KEY,
)

response = client.chat.completions.create(
    model="gpt-image-2-chat",
    messages=messages,
    stream=STREAM,
    metadata={
        "quality": "high",
    },
)

if not STREAM:
    response_data = serialize_for_log(response)
    print(json.dumps(response_data, ensure_ascii=False, indent=2))

    message = response_data["choices"][0]["message"]
    print(message.get("content", ""))
else:
    for chunk in response:
        print(chunk)

典型返回

gpt-image-2-chat 返回 Chat Completions 对象。你应先读取 choices[0].message.content,再根据实际内容提取图片 URL、Markdown 图片或文本说明。
{
  "id": "chatcmpl-example",
  "object": "chat.completion",
  "created": 1741570283,
  "model": "gpt-image-2-chat",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "已生成图片:https://example.com/generated-image.png"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1117,
    "completion_tokens": 46,
    "total_tokens": 1163
  }
}

流式调用

当你设置 stream: true 时,接口会返回一组 chat.completion.chunk。你需要逐块读取 choices[].delta.content 并拼接内容。
curl https://api.aiearth.dev/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-your-api-key" \
  -d '{
    "model": "gpt-image-2-chat",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "auto '参考这张图片,生成一张横版科技海报。'"
          },
          {
            "type": "image_url",
            "image_url": {
              "url": "https://example.com/source-image.png"
            }
          }
        ]
      }
    ],
    "stream": true
  }'

调用说明

  • 如果图片 URL 需要登录、存在防盗链或服务端无法访问,请转成 data:image/...;base64,... 后再传入。
  • 你可以通过 metadata.size 或 prompt 前缀设置尺寸。prompt 前缀示例为 3840x2160 '生成一张产品海报'auto '生成一张产品海报'
  • 如果返回内容不是图片 URL,请记录原始响应并检查 choices[0].message.content 的结构。
  • 如果你传入大图,请控制图片体积。官方 Chat Completions 文档提示,图片输入过大可能被丢弃。
  • gpt-image-2-chat/chat/completions,不要把它传到 /images/generations/images/edits