GPT-4o Image Generation Format
GPT-4o Image Generation Format
Section titled “GPT-4o Image Generation Format”Page Overview
📝 AI Painting Model Introduction
Section titled “📝 AI Painting Model Introduction”gpt-4o-imageandgpt-4o-image-vipare the new GPT-4o image-capable models in ChatGPT. The OpenAI API modelgpt-image-1provides multiple powerful image generation capabilities, allowing you to create images from natural language descriptions and edit or modify images conversationally.size: (optional) Image dimensions. Supports"1024x1024"(square),"1536x1024"(portrait), and"1024x1536"(landscape). There is also an"auto"option (default), where the model automatically chooses the best size based on the prompt.
💡 Python Request Example
Section titled “💡 Python Request Example”Create Image Example 1 ✅
Section titled “Create Image Example 1 ✅”- Images are generated and automatically saved to a local directory file
from openai import OpenAIimport openai # Import openai to catch its specific exceptionsimport base64import datetime # <<--- ***Make sure this line exists and is not commented out***
# Please make sure to keep your API key safe and never expose it publicly.OPENAI_API_KEY = ( "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Enter the API key provided by 4All API)# Example: OPENAI_API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
OPENAI_BASE_URL = "https://sg.4All API.com/v1" # Enter 4All API's Base URL
# 2. Initialize the OpenAI client# ==============================================# Make sure the API key is set (if it is still a placeholder)if OPENAI_API_KEY == "sk-YOUR_API_KEY_HERE" or not OPENAI_API_KEY: # Check whether it is still a template value print("Error: Please set your OPENAI_API_KEY correctly in the code.") exit()
client_params = {"api_key": OPENAI_API_KEY}
# Handle base_url configuration correctlyif OPENAI_BASE_URL: client_params["base_url"] = OPENAI_BASE_URL print(f"Base URL in use: {OPENAI_BASE_URL}")else: print("No custom Base URL in use; the default OpenAI endpoint will be used.")
try: client = OpenAI(**client_params) # client.models.list() # Optional: test the API key and connection print("OpenAI client initialized successfully.")except openai.AuthenticationError as e: error_msg = "OpenAI API authentication failed: " if hasattr(e, 'message') and e.message: error_msg += e.message elif hasattr(e, 'body') and isinstance(e.body, dict) and e.body.get('message'): error_msg += e.body.get('message') else: error_msg += "Please check your API key." print(error_msg) print("Please make sure your OPENAI_API_KEY is correct, valid, and that your account has sufficient balance/permissions.") exit()except Exception as e: print(f"An unexpected error occurred while initializing the OpenAI client: {e}") exit()# ==============================================
# 3. Define the Prompt and Model# ==============================================prompt = """椰树牌椰汁风格广告海报显眼漂亮性感的美女,主题是GPT最新AI绘画服务的广告促销, 强调‘惊爆价9.9/张’、‘适用各种场景、图像融合、局部重绘’、‘每张提交3次修改'、'AI直出效果,无需修改',底部醒目标注‘有意向点右 下“我想要”,右下角绘制一个手指点击按钮动作,左下角展示OpenAl标志"""
MODEL_TO_USE = "gpt-image-1" # The model you want to use# MODEL_TO_USE = "dall-e-3"# ==============================================
# 4. Generate and Save the Image# ==============================================try: print(f"Generating an image using model '{MODEL_TO_USE}' with the prompt...") result = client.images.generate( model=MODEL_TO_USE, prompt=prompt, n=1, size="1024x1024", response_format="b64_json", )
if not result.data or not result.data[0].b64_json: print("Error: The API did not return base64-encoded image data.") if result.data and result.data[0].revised_prompt: print(f"Revised Prompt: {result.data[0].revised_prompt}") exit()
image_base64 = result.data[0].b64_json image_bytes = base64.b64decode(image_base64)
# --- Auto-generate the filename --- now = datetime.datetime.now() # <<--- datetime is used here timestamp_str = now.strftime("%Y%m%d_%H%M%S") output_filename = f"image_{timestamp_str}.png" # --- Filename update ends here ---
with open(output_filename, "wb") as f: f.write(image_bytes) print(f"Image generated and saved successfully as {output_filename}") if result.data[0].revised_prompt: print(f"Actual prompt used to generate the image (Revised Prompt): {result.data[0].revised_prompt}")
except openai.APIError as e: error_message = "Unknown API error" status_code_info = f"(status code: {e.status_code})" if hasattr(e, 'status_code') else ""
if hasattr(e, 'message') and e.message: error_message = e.message elif hasattr(e, 'body') and isinstance(e.body, dict) and e.body.get('message'): error_message = e.body.get('message') elif hasattr(e, 'body') and isinstance(e.body, str): error_message = e.body
print(f"OpenAI API returned an error {status_code_info}: {error_message}")
if hasattr(e, 'body') and e.body: print(f"Error details: {e.body}")
if isinstance(e, openai.AuthenticationError): print("This usually means the API key is incorrect or there is an account issue. Please check again.") elif isinstance(e, openai.RateLimitError): print("Request rate limit exceeded. Please try again later.") elif isinstance(e, openai.BadRequestError): if hasattr(e, 'body') and isinstance(e.body, dict) and 'error' in e.body and isinstance(e.body['error'], dict): error_details = e.body['error'] if error_details.get("code") == "content_policy_violation": print("Detailed error: content policy violation. The prompt may violate OpenAI's usage policies.") elif error_details.get("param"): print(f"There may be an issue with the parameter '{error_details.get('param')}'.") else: print("BadRequestError, but unable to parse detailed error information.")
except Exception as e: # The previous NameError will be caught here print(f"An unexpected error occurred while processing or saving the image: {e}")finally: print("Script execution complete.")Create Image Example 2 ✅
Section titled “Create Image Example 2 ✅”- If the image generation link returns an error, open the link to download it
import http.clientimport json
API_HOST = "sg.4All API.com"API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # Please replace with your actual API keyMODEL = "gpt-image-1" # You can switch models: `gpt-4o-image` `gpt-4o-image-vip``gpt-image-1``dall-e-3`
# Define the image generation parametersPROMPT = "椰树牌椰汁风格广告海报显眼漂亮性感的美女,主题是GPT最新AI绘画服务的广告促销,强调‘惊爆价9.9/张’、‘适用各种场景、图像融合、局部重绘’、‘每张提交3次修改'、'AI直出效果,无需修改',底部醒目标注‘有意向点右下“我想要”,右下角绘制一个手指点击按钮动作,左下角展示OpenAI标志。"N = 1 # Number of images to generateSIZE = "1536x1024" # Image size
# Build the request payloadpayload = json.dumps({ "stream": True, "model": MODEL, "messages": [ { "content": PROMPT, "role": "user" } ], "num_images": N, # Number of images to generate "size": SIZE # Image size})
# Set request headersheaders = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {API_KEY}' # API key if required}
# Send the HTTP requestconn = http.client.HTTPSConnection(API_HOST)conn.request("POST", "/v1/chat/completions", payload, headers)
# Get and print the responseres = conn.getresponse()data = res.read()print(data.decode("utf-8"))