gpt-image-2

最后更新:2026-11-14

POSThttps://www.sagelib.com/images/generations

gpt-image-2 模型的图像生成接口,OpenAI兼容,支持文生图、图像参数配置等。

接口鉴权方式请参考:API接入与鉴权

请求参数

请求头

参数名称 描述
*Authorization string 鉴权令牌,格式为 Bearer ${AIGATEWAY_TOKEN}
*Content-Type string 默认值:application/json
可选值:application/json
内容类型,固定为 application/json

Body 参数

参数名称 描述
*model string 可选值:"gpt-image-2"
模型名称
*prompt string 可选值:Any text
描述期望生成的图像
n integer 默认值:1
可选值:1 ~ 10
生成的候选图像数量
size string 默认值:auto
可选值:auto / 宽x高(宽高均需被 16 整除)
输出图像尺寸
quality string 默认值:auto
可选值:low、medium、high、auto
图像质量等级
background string 默认值:opaque
可选值:opaque、auto
背景类型,不支持 transparent
output_format string 默认值:png
可选值:png、jpeg
输出图像格式,不支持 webp
output_compression integer 可选值:0 ~ 100 (jpeg only)
JPEG 输出压缩质量
moderation string 默认值:auto
可选值:auto、low
内容审核等级
user string 可选值:Any string
终端用户标识

请求示例

curl -v 'https://www.sagelib.com/images/generations' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "An orange tabby crouches on a windowsill; outside is a city skyline at sunset, watercolor style, warm tones, delicate and soft, rich light and shadow layers"
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your Bearer token

url = f"https://www.sagelib.com/images/generations"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "model": "gpt-image-2",
    "prompt": "An orange tabby crouches on a windowsill; outside is a city skyline at sunset, watercolor style, warm tones, delicate and soft, rich light and shadow layers"
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/images/generations";

        String jsonRequestBody = """
            {
                "model": "gpt-image-2",
                "prompt": "An orange tabby crouches on a windowsill; outside is a city skyline at sunset, watercolor style, warm tones, delicate and soft, rich light and shadow layers"
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/images/generations"

    jsonRequestBody := `
            {
                "model": "gpt-image-2",
                "prompt": "An orange tabby crouches on a windowsill; outside is a city skyline at sunset, watercolor style, warm tones, delicate and soft, rich light and shadow layers"
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/images/generations' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-image-2",
    "prompt": "An orange tabby crouches on a windowsill; outside is a sunset city skyline, watercolor style, warm tones",
    "size": "1024x1024",
    "quality": "high",
    "n": 2,
    "output_format": "jpeg",
    "output_compression": 80,
    "background": "opaque",
    "moderation": "auto"
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your Bearer token

url = f"https://www.sagelib.com/images/generations"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "model": "gpt-image-2",
    "prompt": "An orange tabby crouches on a windowsill; outside is a sunset city skyline, watercolor style, warm tones",
    "size": "1024x1024",
    "quality": "high",
    "n": 2,
    "output_format": "jpeg",
    "output_compression": 80,
    "background": "opaque",
    "moderation": "auto"
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/images/generations";

        String jsonRequestBody = """
            {
                "model": "gpt-image-2",
                "prompt": "An orange tabby crouches on a windowsill; outside is a sunset city skyline, watercolor style, warm tones",
                "size": "1024x1024",
                "quality": "high",
                "n": 2,
                "output_format": "jpeg",
                "output_compression": 80,
                "background": "opaque",
                "moderation": "auto"
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/images/generations"

    jsonRequestBody := `
            {
                "model": "gpt-image-2",
                "prompt": "An orange tabby crouches on a windowsill; outside is a sunset city skyline, watercolor style, warm tones",
                "size": "1024x1024",
                "quality": "high",
                "n": 2,
                "output_format": "jpeg",
                "output_compression": 80,
                "background": "opaque",
                "moderation": "auto"
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}

响应参数

Body 参数

参数名称 描述
created integer 图像生成时间戳(Unix 秒)
model string 实际使用的模型名称
data array 生成的图像列表
data[0] object
    b64_json string Base64 编码的图像二进制数据
usage object Token 用量统计
    input_tokens integer 输入文本 Token 数
    output_tokens integer 输出 Token 总数
    total_tokens integer 总计 Token 数
size string 实际生成的图像尺寸
quality string 实际生效的图像质量等级
background string 背景类型(始终为 opaque)
output_format string 实际输出的图像格式
POSThttps://www.sagelib.com/openai/images/generations

gpt-image-2 模型的图像编辑接口,OpenAI直连模式(URL 前缀 /openai),multipart 文件上传形式。

接口鉴权方式请参考:API接入与鉴权

请求参数

请求头

参数名称 描述
*Authorization string 鉴权令牌,格式为 Bearer ${AIGATEWAY_TOKEN}
*Content-Type string 可选值:multipart/form-data
multipart/form-data; boundary=${boundary},boundary由请求工具自动生成

Body 参数

参数名称 描述
*model string 可选值:Gateway-mounted model name, e.g. gpt-image-2
指定用于图像编辑的模型
*prompt string 可选值:No hard limit
描述编辑目标的文本指令
*image string 可选值:Image file or public image URL
待编辑的原始图像
mask string 可选值:Transparent PNG image file
指定需重绘区域的遮罩图
n integer 默认值:1
可选值:1-10
一次生成的图片数量
size string 默认值:1024x1024
可选值:Such as 1024x1024, 1536x1024; width and height must both be divisible by 16
输出图片尺寸
quality string 默认值:auto
可选值:auto / high / medium / low
生成质量档位,影响细节与耗时
background string 默认值:auto
可选值:auto / opaque
背景处理方式(是否保留透明通道)
output_format string 默认值:png
可选值:png / jpeg / webp
输出图片编码格式
output_compression integer 可选值:0-100 (jpeg/webp only)
输出图片压缩率,值越小体积越小
input_fidelity string 可选值:high / low
控制对输入图像细节的保真程度
user string 终端用户标识,用于风控与用量追踪
moderation string 默认值:auto
可选值:auto / low
内容审核级别控制
response_format string 可选值:url / b64_json
响应中图像的返回形式

请求示例

curl -v 'https://${base_url}/v2/llm/images/edits' \
  -H "Authorization: Bearer ***" \
  -F "image=${image_url}" \
  -F "model=gpt-image-2" \
  -F "n=1" \
  -F "prompt=Replace the background with a starry night sky, keeping the cat's posture and fur color unchanged, photorealistic style, with the Milky Way clearly visible" \
  -F "size=1024x1024"
curl -v 'https://${base_url}/v2/llm/images/edits' \
  -H "Authorization: Bearer ***" \
  -F "image=${image_url}" \
  -F "mask=@${image_path}" \
  -F "model=gpt-image-2" \
  -F "n=1" \
  -F "prompt=Replace the background with a starry night sky, keeping the cat's posture and fur color unchanged, photorealistic style, with the Milky Way clearly visible" \
  -F "size=1024x1024"
curl -v 'https://${base_url}/v2/llm/images/edits' \
  -H "Authorization: Bearer ***" \
  -F "image=${image_url}" \
  -F "model=gpt-image-2" \
  -F "n=1" \
  -F "output_compression=80" \
  -F "output_format=jpeg" \
  -F "prompt=Replace the background with a starry night sky, keeping the cat's posture and fur color unchanged, photorealistic style, with the Milky Way clearly visible" \
  -F "size=1024x1024"

响应参数

Body 参数

参数名称 描述
created integer 响应生成时间戳(Unix 秒)
model string 实际调用的模型名,回显为 gpt-image-2
data array 生成结果数组,元素个数等于请求的 n
    b64_json string Base64 编码的图像数据(本端点不返回 URL 形式)
usage object Token 用量统计
    input_tokens integer 输入总 token 数
    input_tokens_details object 输入 token 细分
        image_tokens integer 输入中的图像 token 数
        text_tokens integer 输入中的文本 token 数
    output_tokens integer 输出总 token 数
    output_tokens_details object 输出 token 细分
        image_tokens integer 输出中的图像 token 数
    total_tokens integer 总 token 数
size string 回显实际输出尺寸
quality string 回显质量档位
background string 回显背景处理方式
output_format string 回显输出格式