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
官方参考
常用参数
| 参数 | 类型 | 说明 |
|---|
model | string | 必填。固定传入 gpt-image-2-chat。 |
messages | array | 必填。对话消息列表。图片输入放在 content 数组中。 |
messages[].content[].type | string | 可传 text 或 image_url。 |
messages[].content[].text | string | 当 type 为 text 时使用。写入生成或编辑需求。你也可以在 prompt 开头写入尺寸前缀。 |
messages[].content[].image_url.url | string | 当 type 为 image_url 时使用。支持公网图片 URL 或 data:image/...;base64,...。 |
metadata | object | 可选。示例中用来传递 size 和 quality。实际支持项请以控制台和开发者指南为准。 |
stream | boolean | 可选。设为 true 后按 Chat Completions 流式 chunk 返回。 |
max_completion_tokens | number | 可选。限制输出 token 数。新项目优先使用该参数。 |
user | string | 可选。用于标识你的终端用户。 |
官方 Chat Completions 文档中,metadata 是附加到请求对象的键值对。AIOAGI 的 gpt-image-2-chat 示例使用 metadata.size 和 metadata.quality 控制图像规格。请在 控制台 或 开发者指南 中确认当前支持的取值。
尺寸设置
gpt-image-2-chat 支持两种尺寸设置方式。你可以在 metadata.size 中设置尺寸,也可以把尺寸写在 prompt 开头。
prompt 前缀格式如下:
3840x2160 'your prompt'
auto 'your prompt'
支持的常用尺寸示例:
| 尺寸 | 说明 |
|---|
1024x1024 | 正方形 |
1536x1024 | 横版 |
1024x1536 | 竖版 |
2048x2048 | 2K 正方形 |
2048x1152 | 2K 横版 |
3840x2160 | 4K 横版 |
2160x3840 | 4K 竖版 |
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。