JunFeiAI 图片接口文档:Responses API 方案

适用对象:需要通过 junfeiai.com 中转站调用图片生成模型的客户。

最后更新:2026-05-17

1. 推荐方案

当前推荐使用 Responses API + image_generation 工具 调用图片模型:

POST https://junfeiai.com/v1/responses

不再建议新接入客户优先使用 /v1/images/generations。Images API 属于兼容路径,适合已经按 OpenAI Images API 对接好的旧客户端继续使用;新项目建议直接走 /v1/responses,因为它能更直接暴露图片工具的流式事件,便于观察 generatingpartial_imagecompleted 等阶段。

项目
Base URLhttps://junfeiai.com/v1
推荐文生图接口POST /responses
鉴权方式Authorization: Bearer <你的 API Key>
外层模型推荐 gpt-5.5
推理强度推荐 reasoning.effort = xhigh
图片工具模型推荐 gpt-image-2
返回方式SSE 流式事件,最终图片在 image_generation_call.result 或图片事件字段中

完整请求地址:

https://junfeiai.com/v1/responses

2. 准备 API Key

  1. 登录 https://junfeiai.com
  2. 进入控制台的 API Keys 页面
  3. 创建或复制一个 API Key
  4. 请求时放入 HTTP Header:
Authorization: Bearer sk-xxxx
Content-Type: application/json

注意:API Key 属于敏感凭证,不要放在前端网页、App 客户端、公开仓库或聊天截图里。建议由你的服务端调用君飞 AI 接口,再把生成结果返回给自己的前端。

3. Responses API 文生图

请求

POST https://junfeiai.com/v1/responses
Authorization: Bearer <你的 API Key>
Content-Type: application/json
Accept: text/event-stream

推荐请求体

{
  "model": "gpt-5.5",
  "input": [
    {
      "type": "message",
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": "请生成一张简洁高级的科技产品宣传图,白色背景,主体是一台银色智能音箱,柔和棚拍光线,商业摄影风格"
        }
      ]
    }
  ],
  "stream": true,
  "store": false,
  "parallel_tool_calls": true,
  "tool_choice": {
    "type": "image_generation"
  },
  "reasoning": {
    "effort": "xhigh",
    "summary": "auto"
  },
  "tools": [
    {
      "type": "image_generation",
      "model": "gpt-image-2",
      "size": "1024x1024",
      "quality": "medium",
      "output_format": "png",
      "partial_images": 1
    }
  ]
}

常用参数

参数位置类型必填示例说明
modelstringgpt-5.5外层 Responses 模型,负责调用图片工具
input[].content[].textstring一张电商主图...图片生成提示词
streamboolean建议true开启 SSE 流式返回,便于看到生成阶段
tool_choice.typestringimage_generation强制本次响应调用图片生成工具
reasoning.effortstringxhigh外层模型推理强度,推荐 xhigh
tools[].typestringimage_generation工具类型
tools[].modelstringgpt-image-2图片模型
tools[].sizestring1024x1024图片尺寸,常用 1024x10241536x10241024x15362048x1152
tools[].qualitystringmedium质量:lowmediumhighauto
tools[].output_formatstringpng输出格式:pngjpegwebp
tools[].partial_imagesinteger1中间预览图数量,常用 1-3

4. curl 示例

curl -N -X POST "https://junfeiai.com/v1/responses" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "model": "gpt-5.5",
    "input": [
      {
        "type": "message",
        "role": "user",
        "content": [
          {
            "type": "input_text",
            "text": "Create a premium product poster for a silver smart speaker on a clean white studio background, soft commercial lighting, realistic photography style, no text, no watermark."
          }
        ]
      }
    ],
    "stream": true,
    "store": false,
    "parallel_tool_calls": true,
    "tool_choice": { "type": "image_generation" },
    "reasoning": { "effort": "xhigh", "summary": "auto" },
    "tools": [
      {
        "type": "image_generation",
        "model": "gpt-image-2",
        "size": "1024x1024",
        "quality": "medium",
        "output_format": "png",
        "partial_images": 1
      }
    ]
  }'

curl -N 用于关闭 curl 的输出缓冲,便于实时看到 SSE 事件。

5. SSE 事件解析

开启 stream: true 后,接口返回 text/event-stream。正常情况下会看到类似事件:

event: response.created
data: {"type":"response.created","response":{...}}

event: response.image_generation_call.in_progress
data: {"type":"response.image_generation_call.in_progress","item_id":"..."}

event: response.image_generation_call.generating
data: {"type":"response.image_generation_call.generating","item_id":"..."}

event: response.image_generation_call.partial_image
data: {"type":"response.image_generation_call.partial_image","partial_image_index":0,"partial_image":"..."}

event: response.output_item.done
data: {"type":"response.output_item.done","item":{"type":"image_generation_call","result":"..."}}

event: response.completed
data: {"type":"response.completed","response":{...}}

客户端处理建议:

  1. 按 SSE 协议逐段读取 event:data:
  2. 对每段 data: 做 JSON 解析
  3. 遇到 response.image_generation_call.partial_image 时,可把 partial_image 或同类图片字段作为预览图
  4. 遇到 response.output_item.doneresponse.completed 时,从 item.resultresponse.output[].result 里读取最终图片
  5. 图片字段通常是 Base64 字符串,需要解码后保存为 .png.jpeg.webp

不同上游版本的图片字段名可能略有差异,建议客户端兼容以下字段:

result
b64_json
image
image_b64
partial_image
partial_image_b64

6. Node.js 流式示例

下面示例使用原生 fetch 读取 SSE。生产环境建议加上超时、重试和日志记录。

import fs from "node:fs";

const response = await fetch("https://junfeiai.com/v1/responses", {
  method: "POST",
  headers: {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
    "Accept": "text/event-stream"
  },
  body: JSON.stringify({
    model: "gpt-5.5",
    input: [
      {
        type: "message",
        role: "user",
        content: [
          {
            type: "input_text",
            text: "请生成一张简洁高级的科技产品宣传图,白色背景,主体是一台银色智能音箱,柔和棚拍光线,商业摄影风格"
          }
        ]
      }
    ],
    stream: true,
    store: false,
    parallel_tool_calls: true,
    tool_choice: { type: "image_generation" },
    reasoning: { effort: "xhigh", summary: "auto" },
    tools: [
      {
        type: "image_generation",
        model: "gpt-image-2",
        size: "1024x1024",
        quality: "medium",
        output_format: "png",
        partial_images: 1
      }
    ]
  })
});

if (!response.ok || !response.body) {
  throw new Error(`HTTP ${response.status}: ${await response.text()}`);
}

const decoder = new TextDecoder();
const reader = response.body.getReader();
let buffer = "";
let eventName = "message";
let dataLines = [];
let finalImage = "";

function findImage(value) {
  if (!value || typeof value !== "object") return "";
  if (Array.isArray(value)) {
    for (const item of value) {
      const found = findImage(item);
      if (found) return found;
    }
    return "";
  }
  for (const [key, item] of Object.entries(value)) {
    if (["result", "b64_json", "image", "image_b64", "partial_image", "partial_image_b64"].includes(key)) {
      if (typeof item === "string" && item.length > 1000) return item;
    }
    if (item && typeof item === "object") {
      const found = findImage(item);
      if (found) return found;
    }
  }
  return "";
}

function flushEvent() {
  if (!dataLines.length) {
    eventName = "message";
    return;
  }
  const raw = dataLines.join("\n");
  dataLines = [];
  const payload = JSON.parse(raw);
  const image = findImage(payload);
  if (image) {
    finalImage = image;
    console.log("image event:", payload.type || eventName);
  } else {
    console.log("event:", payload.type || eventName);
  }
  eventName = "message";
}

while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split(/\r?\n/);
  buffer = lines.pop() || "";
  for (const line of lines) {
    if (line === "") {
      flushEvent();
    } else if (line.startsWith("event:")) {
      eventName = line.slice(6).trim();
    } else if (line.startsWith("data:")) {
      const data = line.slice(5).trimStart();
      if (data !== "[DONE]") dataLines.push(data);
    }
  }
}
flushEvent();

if (!finalImage) throw new Error("No image returned");
fs.writeFileSync("output.png", Buffer.from(finalImage, "base64"));

7. Python 示例

下面示例使用 requests 读取 SSE。生产环境建议使用成熟 SSE 客户端库,并加入超时、重试和日志。

import base64
import json
import requests

url = "https://junfeiai.com/v1/responses"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
    "Accept": "text/event-stream",
}
payload = {
    "model": "gpt-5.5",
    "input": [
        {
            "type": "message",
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "请生成一张简洁高级的科技产品宣传图,白色背景,主体是一台银色智能音箱,柔和棚拍光线,商业摄影风格",
                }
            ],
        }
    ],
    "stream": True,
    "store": False,
    "parallel_tool_calls": True,
    "tool_choice": {"type": "image_generation"},
    "reasoning": {"effort": "xhigh", "summary": "auto"},
    "tools": [
        {
            "type": "image_generation",
            "model": "gpt-image-2",
            "size": "1024x1024",
            "quality": "medium",
            "output_format": "png",
            "partial_images": 1,
        }
    ],
}


def find_image(value):
    if isinstance(value, dict):
        for key, item in value.items():
            if key in {"result", "b64_json", "image", "image_b64", "partial_image", "partial_image_b64"}:
                if isinstance(item, str) and len(item) > 1000:
                    return item
            found = find_image(item)
            if found:
                return found
    elif isinstance(value, list):
        for item in value:
            found = find_image(item)
            if found:
                return found
    return ""


final_image = ""
event_name = "message"
data_lines = []

with requests.post(url, headers=headers, json=payload, stream=True, timeout=180) as resp:
    resp.raise_for_status()
    for raw_line in resp.iter_lines(decode_unicode=True):
        line = raw_line or ""
        if line == "":
            if data_lines:
                event = json.loads("\n".join(data_lines))
                data_lines = []
                image = find_image(event)
                if image:
                    final_image = image
                    print("image event:", event.get("type", event_name))
                else:
                    print("event:", event.get("type", event_name))
            event_name = "message"
        elif line.startswith("event:"):
            event_name = line[6:].strip()
        elif line.startswith("data:"):
            data = line[5:].lstrip()
            if data != "[DONE]":
                data_lines.append(data)

if not final_image:
    raise RuntimeError("No image returned")

with open("output.png", "wb") as f:
    f.write(base64.b64decode(final_image))

8. 常见尺寸与质量建议

场景推荐尺寸推荐质量说明
头像、Logo 草稿1024x1024low / medium快速出图,成本较低
电商主图1024x1024medium稳定、通用
横版海报1536x10242048x1152medium / high适合官网 Banner、横图宣传
竖版海报1024x15361152x2048medium / high适合小红书、抖音封面、手机海报
高清物料2048x2048 或更高high更慢、费用更高,适合定稿

说明:

9. Images API 兼容说明

旧客户端如果已经按 OpenAI Images API 接入,可继续使用:

POST https://junfeiai.com/v1/images/generations

但新接入不建议优先使用该路径。原因是 Images API 在部分账号或渠道下会被中转服务转换为 Responses + image_generation 工具调用,再把上游事件翻译回 Images API 风格。这样便于兼容旧客户端,但排查耗时阶段时不如 /v1/responses 直观。

Images API 兼容请求体示例:

{
  "model": "gpt-image-2",
  "prompt": "一只白色陶瓷杯放在木桌上,自然光,真实摄影风格",
  "size": "1024x1024",
  "quality": "medium",
  "output_format": "png",
  "stream": true,
  "partial_images": 1
}

兼容路径可能返回类似事件:

event: image_generation.partial_image
event: image_generation.completed

如果你需要观察更原始的阶段,请改用推荐的 /v1/responses

10. 图片编辑接口

图片编辑仍使用 Images Edits 兼容接口:

POST https://junfeiai.com/v1/images/edits
Authorization: Bearer <你的 API Key>
Content-Type: multipart/form-data

常用参数:

参数类型必填示例说明
modelstringgpt-image-2图片模型
image[]file@input.png输入图片,可传多张
promptstring把背景换成雪山...编辑要求
maskfile@mask.png局部编辑遮罩图;遮罩需和原图尺寸一致
sizestring1024x1024输出尺寸
qualitystringmedium输出质量
output_formatstringpng输出格式

curl 示例:

curl -X POST "https://junfeiai.com/v1/images/edits" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "model=gpt-image-2" \
  -F "image[]=@input.png" \
  -F "prompt=保留人物姿势和服装,把背景换成干净的白色摄影棚,商业大片质感" \
  -F "size=1024x1024" \
  -F "quality=medium"

11. 错误码排查

HTTP 状态码常见原因处理方式
401API Key 缺失、错误或已失效检查 Authorization: Bearer YOUR_API_KEY
403当前 Key 无模型权限或账户受限检查余额、分组权限、模型是否开通
404接口路径错误文生图确认使用 /v1/responses;编辑图确认使用 /v1/images/edits
429请求过快或额度限制降低并发,稍后重试
400参数错误检查 modelinputtoolstool_choicesize 等字段
500/502/503上游或中转服务暂时异常稍后重试;必要时联系君飞 AI 客服

12. 客户对接提醒

13. 资料来源