API 生图
用 API 生成图片
生图走 Responses 接口:主模型读懂你的描述,把出图当成一个工具去调用,图片以 Base64 结果随事件返回。地址和密钥与文本调用完全一样,不必再单独接一套图像服务。
- 01
拼好请求体
四个要点:tools 里放 image_generation 并指定生图模型;tool_choice 填同一个类型,强制它出图而不是用文字回你;stream 打开,生图比文本慢得多,流式能边生成边收事件,也不容易被中途掐断;store 关掉,这轮对话不在服务端留存。图片描述作为一条 user 消息放进 input,instructions 只交代任务本身。下面是 bash 写法,Windows 直接看下一步的 Python 例子。
curl https://api.xylemnode.com/v1/responses \ -H "Authorization: Bearer sk-你的密钥" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5.6-sol", "instructions": "Generate the requested image.", "input": [ { "role": "user", "content": "一只穿着宇航服的橘猫站在月球上,远处是蓝色地球,电影感光影,写实风格。" } ], "tools": [{ "type": "image_generation", "model": "gpt-image-2" }], "tool_choice": { "type": "image_generation" }, "stream": true, "store": false }' - 02
从流式事件里取图
响应是 SSE:逐行读 data: 后面的 JSON,只认 type 为 response.output_item.done 的事件,从里面挑出 item.type 为 image_generation_call 的那条——它的 item.result 就是成品图的 Base64,解码后写成文件即可。result 是一长串文本而不是链接,别直接当图片地址用,也别打印到终端里。
import base64 import json import requests PROMPT = "一只穿着宇航服的橘猫站在月球上,远处是蓝色地球,电影感光影,写实风格。" payload = { "model": "gpt-5.6-sol", "instructions": "Generate the requested image.", "input": [{"role": "user", "content": PROMPT}], "tools": [{"type": "image_generation", "model": "gpt-image-2"}], "tool_choice": {"type": "image_generation"}, "stream": True, "store": False, } with requests.post( "https://api.xylemnode.com/v1/responses", headers={"Authorization": "Bearer sk-你的密钥"}, json=payload, stream=True, timeout=600, ) as response: response.raise_for_status() for raw in response.iter_lines(): if not raw: continue line = raw.decode("utf-8") if not line.startswith("data:"): continue chunk = line[5:].strip() if chunk == "[DONE]": break event = json.loads(chunk) if event.get("type") != "response.output_item.done": continue item = event.get("item") or {} if item.get("type") == "image_generation_call" and item.get("result"): with open("moon-cat.png", "wb") as file: file.write(base64.b64decode(item["result"])) print("已保存 moon-cat.png") - 03
换模型、调出图参数
生图模型按需要换:gpt-image-2.5-flare 更快,gpt-image-2.5-sunburst 更精细但更慢,以后台可用列表为准。出图选项写在 tools 里同一个对象上:size 定画幅、quality 定精细度、background 可以要透明底(透明只支持 png / webp)、output_format 定文件格式;再加 partial_images(1–3),出图过程中会先收到几张草图预览,事件类型是 response.image_generation_call.partial_image。
"tools": [{ "type": "image_generation", "model": "gpt-image-2.5-flare", "size": "1024x1536", "quality": "high", "background": "transparent", "output_format": "png", "partial_images": 2 }]
- 接口地址
https://api.xylemnode.com/v1/responses- 请求方式
POST(Bearer 鉴权)- 主模型
gpt-5.6-sol- 生图工具
image_generation- 生图模型
gpt-image-2- 取图字段
image_generation_call.result(Base64)
两个容易踩的点
其一,主模型只负责读懂描述并触发工具,得选一个支持 image_generation 的模型;如果返回工具不可用一类的错误,按后台可用列表换个主模型再试。 其二,一次请求只出一张成品图。想在同一张图上接着改,需要把 store 打开,并在下一次请求里用 previous_response_id 指向上一次的响应——store 关掉时这轮对话不留存,也就没法这样往下接。