GPT Image 1 Input Fidelity

Hi,

I tried to use the Input Fidelity parameter while using the GPT Image 1 API and it returned an error? Is there some mistake that I’m making or is it that the parameter is not accepted anymore?

1 Like

The input_fidelity parameter was only just announced today.

It is only on the edits endpoint, and is meant to improve the reproduction of input images if used with input_fidelity="high".

Ensure the latest SDK, as the OpenAI library will block unknown API parameters, quickly becoming obsolete:

pip install --upgrade --upgrade-strategy=eager openai

Then send your input image, such as this woman from the announcement:

Along with a prompt:

Photograph of a woman pictured from the input image.
However, she now has colorful rainbow-streaked hair, and wears a pretty yellow blouse.

Receive an output, with the cropping received showing that you need to refine the technique, such as demanding a “zoom out”, or needing a vertical profile aspect ratio:

The model itself requires an organization to be ID-verified.

2 Likes

Hi, it’s great, but I can’t get it to work. What am I doing wrong, it keeps giving me an error:
:cross_mark: Chyba 400: {
“error”: {
“message”: “Unknown parameter: ‘input_fidelity’.”,
“type”: “invalid_request_error”,
“param”: “input_fidelity”,
“code”: “unknown_parameter”
}
}

This is my python code:

-- coding: utf-8 --

import base64
import requests
from PIL import Image
from io import BytesIO

api_key = “sk-”

URL obrázků

url_person = “…/imggallery/reklamyfromgpt/76-23153-36-ig.jpg”
url_shirt = “…/imggallery/reklamyfromgpt/slayer-shirt.png”

Funkce pro převod na base64

def image_url_to_base64(url):
resp = requests.get(url)
if resp.status_code != 200:
raise Exception(f"Chyba při stahování: {url}")
return base64.b64encode(resp.content).decode(“utf-8”)

Načti obrázky jako base64

img_person = image_url_to_base64(url_person)
img_shirt = image_url_to_base64(url_shirt)

JSON payload

payload = {
“model”: “gpt-image-1”,
“prompt”: “”"
The first image shows a man wearing a blank shirt.
The second image shows a Slayer T-shirt design.
Put the design from the second image on the shirt in the first image, keeping realistic lighting, folds, and perspective.
“”",
“size”: “1024x1024”,
“quality”: “high”,
“input_fidelity”: “high”,
“response_format”: “b64_json”,
“referenced_images”: [
{ “type”: “image”, “data”: img_person },
{ “type”: “image”, “data”: img_shirt }
]
}

Zavolání API přes HTTP

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

response = requests.post(
“… /v1/images/generations”,
headers=headers,
json=payload
)

if response.status_code == 200:
data = response.json()
img_data = base64.b64decode(data[‘data’][0][‘b64_json’])
image = Image.open(BytesIO(img_data))
image.save(“output.png”)
image.show()
print(“:white_check_mark: Obrázek vygenerován a uložen jako output.png”)
else:
print(f":cross_mark: Chyba {response.status_code}: {response.text}")

You are sending to the “generations” API endpoint URL, which only accepts prompt. Not a good way to “edit”. :slight_smile: Also, there are elides where you need a full URL. The same issue is possible in your image sources too if you didn’t do that just for privacy.

.post("https://api.openai.com/v1/images/edits", ...)

Now the error is like this, I didn't send it as a code last time, sorry:
❌ Chyba 400: {
  "error": {
    "message": "Unsupported content type: 'application/json'. This API method only accepts 'multipart/form-data' requests, but you specified the header 'Content-Type: application/json'. Please try again with a supported content type.",
    "type": "invalid_request_error",
    "param": null,
    "code": "unsupported_content_type"
  }
}

# -*- coding: utf-8 -*-
import base64
import requests
from PIL import Image
from io import BytesIO

api_key = "sk-"

# URL obrázků
url_person = "https://www.atakt.cz/imggallery/reklamyfromgpt/76-23153-36-ig.jpg"
url_shirt  = "https://www.atakt.cz/imggallery/reklamyfromgpt/slayer-shirt.png"

# Funkce pro převod na base64
def image_url_to_base64(url):
    resp = requests.get(url)
    if resp.status_code != 200:
        raise Exception(f"Chyba při stahování: {url}")
    return base64.b64encode(resp.content).decode("utf-8")

# Načti obrázky jako base64
img_person = image_url_to_base64(url_person)
img_shirt  = image_url_to_base64(url_shirt)

# JSON payload
payload = {
    "model": "gpt-image-1",
    "prompt": """
The first image shows a man wearing a blank shirt.
The second image shows a Slayer T-shirt design.
Put the design from the second image on the shirt in the first image, keeping realistic lighting, folds, and perspective.
""",
    "size": "1024x1024",
    "quality": "high",
    "input_fidelity": "high",
    "response_format": "b64_json",
    "referenced_images": [
        { "type": "image", "data": img_person },
        { "type": "image", "data": img_shirt }
    ]
}

# Zavolání API přes HTTP
headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.post(
    "https://api.openai.com/v1/images/edits",
    headers=headers,
    json=payload
)

if response.status_code == 200:
    data = response.json()
    img_data = base64.b64decode(data['data'][0]['b64_json'])
    image = Image.open(BytesIO(img_data))
    image.save("output.png")
    image.show()
    print("✅ Obrázek vygenerován a uložen jako output.png")
else:
    print(f"❌ Chyba {response.status_code}: {response.text}")

# this is my last tested version, so I sent multipart/form-data
# but I have another new error

PS C:\PythonScript\GPTImages> python generate_image2.py
❌ Chyba 400: {
  "error": {
    "message": "Unknown parameter: 'response_format'.",
    "type": "invalid_request_error",
    "param": "response_format",
    "code": "unknown_parameter"
  }
}

# -*- coding: utf-8 -*-
import base64
import requests
from io import BytesIO
from PIL import Image

api_key = "sk-"

# URL obrázků
url_person = "https://www.atakt.cz/imggallery/reklamyfromgpt/76-23153-36-ig.jpg"
url_shirt  = "https://www.atakt.cz/imggallery/reklamyfromgpt/slayer-shirt.png"

# Stažení obrázku a načtení jako soubor
def download_image(url):
    resp = requests.get(url)
    if resp.status_code != 200:
        raise Exception(f"Chyba při stahování: {url}")
    return BytesIO(resp.content)

# Načti oba obrázky jako soubory
image_person = download_image(url_person)
image_shirt  = download_image(url_shirt)

# Sestavení multipart/form-data požadavku
files = {
    "image": ("person.png", image_person, "image/png"),
    "mask":  ("mask.png", image_shirt, "image/png")
}

data = {
    "model": "gpt-image-1",
    "prompt": "The first image shows a man wearing a blank shirt.\n"
              "The second image shows a Slayer T-shirt design.\n"
              "Put the design from the second image on the shirt in the first image, "
              "keeping realistic lighting, folds, and perspective.",
    "size": "1024x1024",
    "response_format": "b64_json"
}

headers = {
    "Authorization": f"Bearer {api_key}"
}

# Odeslání požadavku
response = requests.post(
    "https://api.openai.com/v1/images/edits",
    headers=headers,
    data=data,
    files=files
)

# Zpracování odpovědi
if response.status_code == 200:
    data = response.json()
    img_data = base64.b64decode(data['data'][0]['b64_json'])
    image = Image.open(BytesIO(img_data))
    image.save("output.png")
    image.show()
    print("✅ Obrázek vygenerován a uložen jako output.png")
else:
    print(f"❌ Chyba {response.status_code}: {response.text}")

You’ve asked how to properly use the “files=” parameter of Python’s requests library. You send binaries with the files method, such as bytes from a different file download or by reading a file, and should provide a file name. That creates the multipart/form-data API request.

The model gpt-image-1 does not accept a “response_format”, as it only can send you base64 in a JSON.

Here’s a complete learning path through making an edits API call, submitting the form with the alternate httpx library, with some parameters for you. It is focused on local files being read. I commented the new parameter so first experiments are cheaper.

"""
Edit one or more images via the /v1/images/edits endpoint, using httpx
and multipart/form‑data. The code mirrors my earlier SDK example of another
topic, while keeping the same parameter documentation and error‑handling style.
"""

import os
import base64
from pathlib import Path
import httpx

# ---------------------------------------------------------------------------
# User‑supplied inputs
# ---------------------------------------------------------------------------
PROMPT = "The woman pictured is transformed into a blonde!"
INPUT_PATHS = [
    "your-input.png",
    # "another_dir/yet_another_file.png",
]
OUTPUT_FILE = "new-output.png"

# ---------------------------------------------------------------------------
# Build the multipart payload
# ---------------------------------------------------------------------------
# Convert string paths to Path objs (normalizes Win/Mac/Linux separators)
file_paths = [Path(p) for p in INPUT_PATHS]

# Each form part is a 2‑tuple: (field_name, (filename|None, bytes|fileobj, content_type?))
# * All parts, including non‑file params, MUST go in the `files=` argument.
multipart_parts = []

# Image file parts
for p in file_paths:
    # "image" is the official field name; endpoint accepts multiple of them
    multipart_parts.append(
        (
            "image",
            (p.name, p.open("rb"), "image/png"),  # supply filename
        )
    )

# Non‑file parameters (model, prompt, options...)
params = {
    "model": "gpt-image-1",
    "prompt": PROMPT.strip(),
    "quality": "medium",       # "high" | "medium" | "low"
    "size": "1024x1024",       # or "1536x1024", "1024x1536", "auto"
    "output_format": "png",    # "png" | "jpg" | "webp"
    "background": "opaque",    # "opaque" | "transparent" (not with jpg)
    # "input_fidelity": "high",  # this is the new parameter - additional $0.04 or $0.06 for better copying
    "stream": "false",
    "user": "myCustomer",
}

# For form‑data, non‑file fields go in the same list; give them no filename
for key, val in params.items():
    multipart_parts.append((key, (None, str(val))))

# ---------------------------------------------------------------------------
# Send the request
# ---------------------------------------------------------------------------
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
    raise RuntimeError("OPENAI_API_KEY env var is missing")

headers = {"Authorization": f"Bearer {api_key}"}
url = "https://api.openai.com/v1/images/edits"

try:
    with httpx.Client(timeout=60.0) as client:
        resp = client.post(url, files=multipart_parts, headers=headers)
        resp.raise_for_status()  # raises httpx.HTTPStatusError on 4xx/5xx

    # -----------------------------------------------------------------------
    # Decode the returned base64 image
    # -----------------------------------------------------------------------
    data = resp.json()
    b64 = data["data"][0]["b64_json"]
    img_bytes = base64.b64decode(b64)

    out_path = Path(OUTPUT_FILE)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_bytes(img_bytes)

    print(f"Image written to {out_path.resolve()}")

except httpx.HTTPStatusError as e:
    # API returned a non‑2xx; include code and body for debugging
    print(f"OpenAI API error [{e.response.status_code}]: {e.response.text}")

except httpx.RequestError as e:
    # Network problem, DNS failure, etc.
    print(f"Request error: {e}")