Developer Dashboard

Image Generation

Learn how to generate or manipulate images using models available through the AvalAI API, including GPT Image, Gemini image, Qwen image, Seedream, FLUX, Cloudflare, Runway, and Imagen models.

Introduction

The AvalAI Image API provides endpoints for image creation:

  • Generations: Create images from scratch based on a text prompt.
  • Edits: Modify existing images based on a new prompt, reference image, or mask when the selected model supports editing.
  • Variations: Create variations of an existing image when the selected model supports variations.

This guide covers using these capabilities via AvalAI.

Choosing the Right Endpoint

  • Use v1/images/generations or v1/images/edits when you need one direct image generation or editing request and want to choose the image model yourself.
  • Use v1/responses only when the selected model and AvalAI route support an image-generation tool inside a conversation or multi-step agent flow.
  • For editable, multi-turn image experiences, keep the generated image ID or file reference in your application state so the next turn can target the right image.

Responses Image Tool Migration Path

OpenAI documents two image paths: the direct Image API for one-shot generation or edits, and the Responses API image-generation tool for conversational or multi-step image workflows. In AvalAI, keep v1/images/generations and v1/images/edits as the production default unless your selected /v1/responses model and account explicitly support the hosted image_generation tool.

Existing Image API workflowResponses API equivalentAvalAI guidance
Generate one image with gpt-image-2tools=[{"type": "image_generation"}] on a Responses model such as gpt-5.5Prefer Image API for simple jobs; use Responses when the image is part of a chat or agent flow.
Stream progress from the Image APIstream=True plus partial_images on the toolTreat as route-dependent and fall back to direct streaming image endpoints when unavailable.
Edit with uploaded image/maskProvide image file IDs or image inputs to Responses and set action="edit" when supportedKeep /v1/images/edits for deterministic editing and masking.
Store the output in app stateUse previous_response_id or persist the generated image/tool call IDPersist IDs or the saved file path so follow-up turns can target the right image.

When using the Responses tool, set action deliberately: auto lets the model decide whether to generate or edit, generate forces a new image, and edit should be used only when an image is already in context. To guarantee the model calls the tool on supported routes, use tool_choice={"type": "image_generation"}; otherwise the model may answer with text instead of an image.

Do not set the Responses model field to a GPT Image model such as gpt-image-2. The Responses image tool is called by a text-capable mainline model such as gpt-5.5; the hosted tool then selects the GPT Image backend. Direct Image API calls are the place to choose gpt-image-2, gpt-image-1.5, gpt-image-1, or gpt-image-1-mini explicitly.

python
from openai import OpenAI
import base64
import os

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.5",
    input="Draw a clean product hero image of a matte black smart speaker on a walnut desk.",
    tools=[
        {
            "type": "image_generation",
            "quality": "medium",
            "size": "1024x1024",
        }
    ],
)

image_calls = [item for item in response.output if item.type == "image_generation_call"]

if not image_calls:
    raise RuntimeError(
        "No image was generated. Confirm Responses image-tool support or use /v1/images/generations."
    )

with open("responses-product-hero.png", "wb") as image_file:
    image_file.write(base64.b64decode(image_calls[0].result))

print("Revised prompt:", getattr(image_calls[0], "revised_prompt", None))

If the hosted tool is unavailable for your route, use the Image API directly, save the generated image, and pass the URL, file ID, or metadata into your next /v1/responses turn as application context.

Current GPT Image Endpoints in AvalAI

The active OpenAI GPT Image models in data/models.json currently expose these direct Image API routes:

ModelDirect generationDirect editsNotes
gpt-image-2YesYesDefault choice for new high-quality generation and editing workflows.
gpt-image-1.5YesNoKeep for existing generation-only workflows while comparing output quality and cost.
gpt-image-1YesYesOlder stable route for existing image apps.
gpt-image-1-miniYesYesLower-cost option for drafts, bulk ideation, and simple edits.

This table describes AvalAI's direct /v1/images/* routes. Responses image-tool support is separate and should be verified per account, route, and selected mainline model.

Which Model to Use?

AvalAI provides access to various image generation models. Capabilities (like edits/variations) and quality can differ:

  • GPT Image 2: OpenAI's current default recommendation for new high-quality generation and editing workflows. Use it for prompt-heavy visuals, text in images, UI mockups, infographics, product shots, compositing, and edits where preserving identity, layout, or labels matters. See Generate Images with GPT Image Models for a Cookbook-inspired prompting playbook.
  • GPT Image 1.5: A previous advanced OpenAI image generation and editing model. Keep it for existing validated workflows while you compare output quality, retry rates, and cost before migrating to GPT Image 2.
  • GPT Image 1 & GPT Image 1 Mini: Older GPT Image models. GPT Image 1 Mini can still be useful for cost-sensitive drafts and high-volume ideation.
  • Seedream 5.0: ByteDance's state-of-the-art image generation and editing model with unique capabilities:
    • seedream-5-0-260128: Advanced model supporting sequential image generation (up to 15 related images), multi-image blending, streaming output, and high-resolution generation up to 4K. Features intelligent batch processing and supports both text-to-image and image-to-image editing. See our comprehensive guide for detailed usage examples.
  • Google Imagen 4.0 Models: Google's latest image generation models with exceptional quality and detail:
  • imagen-4.0-ultra-generate-001: Ultra-high quality image generation with exceptional detail and realism, supporting resolutions up to 2816x1536.
  • imagen-4.0-generate-001: High-quality professional image generation supporting resolutions up to 2048x2048.
  • imagen-4.0-fast-generate-001: Fast image generation optimized for speed while maintaining quality.
  • imagen-3.0-generate-002: Updated version of Imagen 3.0 with improved capabilities.
  • imagen-3.0-generate-001: Base Imagen 3.0 model for high-quality image generation.
  • imagen-3.0-fast-generate-001: A faster version optimized for reduced latency while maintaining good quality.
  • BFL (FLUX) Models: Advanced image generation and editing models from Black Forest Labs:
  • flux.2-pro: The most advanced FLUX model with superior image quality and megapixel-based pricing. First megapixel: $0.03, additional megapixels: $0.015, reference image: $0.015/MP. Best for professional-quality image generation. Note: Optimized for English prompts only.
  • flux-1.1-pro: Advanced image generation model with superior performance in image quality, prompt adherence, and generation speed.
  • flux.1-kontext-pro: Versatile model supporting both generation and editing, excelling in text editing and character preservation tasks.
  • Alibaba Qwen Image Models: Advanced image generation and editing models with dual SDK support:
    • qwen-image-2.0-pro: Professional image generation with advanced typography achieving near-zero text rendering errors in 40+ languages. Native 2K resolution output ideal for infographics and complex visual content. Pricing: $0.06/image.
    • qwen-image-2.0: Unified generation and editing model with enhanced photorealism and reliable text rendering. Native 2K resolution with professional-quality output. Pricing: $0.04/image.
    • z-image-turbo: Ultra-fast image generation with optional Thinking mode for enhanced quality. Fast default mode ($0.015/image) or Thinking mode ($0.03/image) for complex scenes.
    • qwen-image-edit-plus: Advanced image editing with enhanced quality over the original qwen-image-edit. Supports both v1/images/generations and v1/images/edits endpoints. Pricing: $0.03/image.
    • qwen-image: Professional text-to-image generation with intelligent prompt enhancement, supporting multiple aspect ratios and advanced parameters.
    • qwen-image-edit: Sophisticated image editing capabilities with multi-image input support and precise modification control. Check the Models Overview for specific image models available through AvalAI and their features.

The GPT Image guidance above is adapted from the official OpenAI Cookbook and openai/openai-cookbook, with AvalAI model and endpoint details.

Prompting Pattern for Production Images

For production assets, write prompts as structured briefs:

text
Goal: where the image will be used
Format: photo, ad, slide, UI mockup, infographic, diagram, product shot
Canvas: size, orientation, aspect ratio
Subject: the main object, person, scene, or interface
Composition: framing, viewpoint, placement, whitespace
Style: photorealistic, editorial, flat vector, 3D render, etc.
Text: exact words in quotes, placement, typography, language
Constraints: no watermark, no extra text, preserve logo/layout/colors

Use quality="low" for fast drafts, quality="medium" for general use, and quality="high" for dense text, infographics, close-up product work, identity-sensitive edits, or final customer-facing assets.

For edits, state both the change and the invariants:

text
Change only the wall color to warm white.
Keep the sofa, table, lighting, shadows, camera angle, floor texture,
object positions, and image crop exactly the same.

Using Non-OpenAI Providers with Provider-Specific Parameters

When using image generation models from providers other than OpenAI (such as Black Forest Labs, Alibaba, BytePlus, Cloudflare, or Google), you may need to pass provider-specific parameters that aren't directly supported by the OpenAI client library. AvalAI offers two approaches for this:

Using extra_body Parameter

The standard approach is to use the extra_body parameter. The system will automatically map these provider-specific parameters to the appropriate provider since these are not OpenAI standard parameters.

Common Provider-Specific Parameters

Here are examples of provider-specific parameters commonly used by supported image providers:

  • output_format - Specify the output format for the generated image
  • aspect_ratio - Control the aspect ratio of generated images
  • prompt_upsampling - Enable or disable prompt enhancement
  • safety_tolerance - Adjust content safety filtering
  • samples - Number of samples to generate
  • extras - Additional model-specific options
  • image_strength - Control strength of image-to-image generation
  • init_image_mode - Set initialization mode for image editing
  • init_image - Provide initial image for editing
python
# Python example using Black Forest Labs model with provider-specific parameters
response = client.images.generate(
    model="flux-1.1-pro",
    prompt="A majestic dragon soaring through clouds",
    size="1024x1024",
    extra_body={
        "aspect_ratio": "16:9",
        "output_format": "png",
        "safety_tolerance": 2,
        "prompt_upsampling": True,
    },
)

The extra_body parameter allows you to pass any additional parameters required by the specific provider. For requests with the GET verb, extra parameters will be in the query string, while for all other requests, they will be sent in the body.

Using Undocumented Parameters Directly (JavaScript/TypeScript)

For TypeScript users, you can also pass undocumented parameters directly by using // @ts-expect-error:

javascript
// JavaScript/TypeScript example using undocumented parameters directly
const response = await client.images.generate({
  model: "flux.2-pro",
  prompt: "A detailed landscape with mountains and a lake at sunset",
  size: "1024x1024",
  // @ts-expect-error provider-specific parameters pass through to AvalAI
  extra_body: {
    aspect_ratio: "16:9",
    output_format: "png",
    safety_tolerance: 2,
    prompt_upsampling: true,
  },
  response_format: "url",
});

This library doesn't validate at runtime that the request matches the type, so any extra values you send will be sent as-is to the provider's API. For GET requests, these extra parameters will be in the query string, while for all other requests, they will be sent in the body.

If you want to explicitly send extra arguments, you can also do so with the body request options.

Alibaba Qwen Image Models

The Qwen image models offer unique dual SDK support, allowing you to use both OpenAI-compatible format and native Alibaba Dashscope format for maximum flexibility and access to advanced features.

Using OpenAI SDK Format

python
# Python example using Qwen models with OpenAI SDK format
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

# Text-to-image generation
response = client.images.generate(
    model="qwen-image",
    prompt="A serene mountain landscape with a crystal clear lake reflecting snow-capped peaks",
    size="1328x1328",  # Supports multiple aspect ratios
    n=1,
    response_format="url",  # or b64_json
)

print(f"Generated image URL: {response.data[0].url}")

# Image editing
import requests

with open("input_image.jpg", "rb") as image_file:
    edit_response = requests.post(
        "https://api.avalai.ir/v1/images/edits",
        headers={"Authorization": f"Bearer {os.environ['AVALAI_API_KEY']}"},
        files={"image": image_file},
        data={
            "model": "qwen-image-edit",
            "prompt": "Change the sky to a dramatic sunset with orange and purple colors",
        },
    )

print(f"Edited image: {edit_response.json()}")

Using Native Dashscope Format

For advanced features like intelligent prompt enhancement, negative prompts, and precise control, use the native Dashscope format:

python
# Python example using native Dashscope format for advanced features
import os
import requests

# Advanced text-to-image with native Dashscope parameters
response = requests.post(
    "https://api.avalai.ir/v1/images/generations",
    headers={
        "Authorization": f"Bearer {os.environ['AVALAI_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "qwen-image",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {
                            "text": "A professional headshot of a confident business person in modern office setting"
                        }
                    ],
                }
            ]
        },
        "parameters": {
            "size": "1328*1328",  # Note: Dashscope uses * instead of x
            "prompt_extend": True,  # Enable intelligent prompt enhancement
            "watermark": False,  # Control watermark
            "negative_prompt": "blurry, low quality, distorted, unprofessional",
            "seed": 12345,  # For reproducible results
        },
    },
)

print(f"Advanced generation result: {response.json()}")

# Advanced image editing with multiple images
edit_response = requests.post(
    "https://api.avalai.ir/v1/images/edits",
    headers={
        "Authorization": f"Bearer {os.environ['AVALAI_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "qwen-image-edit",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {
                            "image": "https://example.com/input-image.jpg"  # Or base64 data
                        },
                        {
                            "text": "Change the person to a standing position, bending over to hold the front paws of the dog"
                        },
                    ],
                }
            ]
        },
        "parameters": {
            "negative_prompt": "distorted, unnatural pose",
            "watermark": False,
        },
    },
)

print(f"Advanced editing result: {edit_response.json()}")

Qwen Model-Specific Features

  • Multiple Aspect Ratios: 1:1, 4:3, 3:4, 16:9, 9:16 (1328×1328, 1664×928, 1472×1140, 1140×1472, 928×1664)
  • Intelligent Prompt Enhancement: Automatic prompt rewriting for better results
  • Negative Prompts: Specify what you don't want in the image
  • Watermark Control: Choose whether to include Qwen-Image watermark
  • Seed Support: Reproducible results with consistent seed values
  • Multi-Image Input: Support for multiple reference images in editing tasks

Important Note for Qwen Models: While Qwen models support both Chinese and English prompts, using clear and descriptive English prompts often yields the best results for international use cases.

Generations

Create an original image from a text prompt using the v1/images/generations endpoint.

python
# Python Example using AvalAI for Image Generation
import base64
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

try:
    response = client.images.generate(
        model="gpt-image-2",
        prompt="A white Siamese cat sitting in a sunlit minimalist studio",
        size="1024x1024",
        quality="medium",
        n=1,
    )
    image_base64 = response.data[0].b64_json
    with open("siamese-cat.png", "wb") as image_file:
        image_file.write(base64.b64decode(image_base64))
    print("Saved siamese-cat.png")
except Exception as e:
    print(f"An error occurred: {e}")
javascript
// JavaScript Example using AvalAI for Image Generation
import fs from "fs";
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

async function main() {
  try {
    const response = await client.images.generate({
      model: "gpt-image-2",
      prompt: "A white Siamese cat sitting in a sunlit minimalist studio",
      n: 1,
      size: "1024x1024",
      quality: "medium",
    });

    const imageBase64 = response.data[0].b64_json;
    fs.writeFileSync("siamese-cat.png", Buffer.from(imageBase64, "base64"));
    console.log("Saved siamese-cat.png");
  } catch (error) {
    if (error.response) {
      console.error(error.response.status, error.response.data);
    } else {
      console.error(`Error with AvalAI API request: ${error.message}`);
    }
  }
}
main();
bash
# cURL Example using AvalAI for Image Generation
curl https://api.avalai.ir/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
  "model": "gpt-image-2",
  "prompt": "A white Siamese cat sitting in a sunlit minimalist studio",
  "n": 1,
  "size": "1024x1024",
  "quality": "medium"
}' | jq -r '.data[0].b64_json' | base64 --decode >siamese-cat.png

Size and Quality Options

Supported sizes and quality options depend on the model:

  • GPT Image 2: Supports standard sizes such as 1024x1024, 1536x1024, and 1024x1536, plus route-dependent custom resolutions where both dimensions meet provider constraints. Use quality: "low" for drafts, medium for most production previews, high for final detail, or auto when you want the model to choose.
  • GPT Image 2 custom size checklist: Keep the longest edge at or below 3840px, make both dimensions multiples of 16px, keep the long-edge/short-edge ratio at 3:1 or less, and stay between 655,360 and 8,294,400 total pixels. Treat outputs above 2560x1440 as experimental until you test latency, cost, and visual consistency on your AvalAI route.
  • Output format: GPT Image routes return base64 image data. When the selected route supports output customization, request output_format as png, jpeg, or webp; use output_compression for JPEG/WebP size control.
  • Background: Transparent backgrounds require a format with alpha support such as PNG or WebP and must be supported by the selected model. OpenAI's gpt-image-2 reference currently treats transparent backgrounds as unsupported, so keep background: "auto" or opaque unless your route confirms support.
  • Input fidelity: For gpt-image-2, omit input_fidelity; OpenAI's current guidance says it processes all image inputs at high fidelity automatically. For older GPT Image routes that expose input_fidelity, use high for faces, logos, packaging, UI screenshots, or other edits where preserving distinctive details matters.

Prompting

Provide clear, descriptive prompts. GPT Image and Responses image-tool routes may revise prompts for detail or safety. The revised prompt might be available in the response object (revised_prompt field) if supported by the AvalAI integration.

When using the Responses API image-generation tool, inspect image_generation_call.revised_prompt when present. It is useful for debugging prompt rewrites and for explaining why two similar user prompts produced different outputs.

Streaming and Partial Images

Some GPT Image routes can stream partial images while the final render is still running. If your route supports stream and partial_images, request 1-3 partial images for interactive previews and still save the final image from the completed response. Treat partial images as progressive previews, not final assets. You may receive fewer partial images than requested if the final render completes quickly, and partial previews can affect token usage or image billing; verify AvalAI route pricing before enabling them by default.

Edits (Model-Dependent)

Requires a model and route that support edits, such as GPT Image routes or provider-specific editing models enabled in AvalAI.

The v1/images/edits endpoint allows modifying parts of an image using a mask. Upload the original image and a mask with the same dimensions; for mask-based GPT Image workflows, the mask should include an alpha channel. The prompt should describe the entire desired final image, not only the changed area.

python
import base64
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

try:
    response = client.images.edit(
        model="gpt-image-2",
        image=open("original_image.png", "rb"),
        mask=open("mask.png", "rb"),
        prompt="A sunlit indoor lounge area with a pool containing a flamingo",
        n=1,
        size="1024x1024",
    )
    image_base64 = response.data[0].b64_json
    with open("edited-lounge.png", "wb") as image_file:
        image_file.write(base64.b64decode(image_base64))
except Exception as e:
    print(f"An error occurred: {e}")
    # Check if the model supports edits or if image/mask formats are correct

Sending Base64 Images to Edits Without an SDK

For non-SDK environments, call v1/images/edits directly. For GPT Image-style JSON edit requests, put each source image in the images array and provide a Base64 data URL through image_url. This matches the expected OpenAI edit schema: each image object contains exactly one of image_url or file_id, and image_url may be either a fully qualified URL or a Base64 data URL. This avoids multipart uploads when your runtime only has JSON HTTP primitives.

bash
# macOS/BSD base64 uses `-i`; on Linux you can use `base64 -w 0 input_image.png`
IMAGE_BASE64=$(base64 -i input_image.png | tr -d '\n')

curl https://api.avalai.ir/v1/images/edits \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
  "model": "gpt-image-2",
  "prompt": "Change only the background to a tropical beach while preserving the person, pose, and lighting",
  "images": [
    {
      "image_url": "data:image/png;base64,'"$IMAGE_BASE64"'"
    }
  ],
  "size": "1024x1024",
  "quality": "medium",
  "n": 1
}' | jq -r '
  .data[0]
  | if .b64_json then .b64_json
    elif (.url // "" | startswith("data:")) then (.url | split(",")[1])
    else error("response did not include b64_json or a data URL")
    end
' | base64 --decode >edited-beach.png
python
import base64
import os

import requests


def save_image_result(image, output_path):
    """Save an image result that may contain b64_json or a data URL in url."""
    if image.get("b64_json"):
        image_bytes = base64.b64decode(image["b64_json"])
    elif image.get("url", "").startswith("data:"):
        _, encoded = image["url"].split(",", 1)
        image_bytes = base64.b64decode(encoded)
    elif image.get("url"):
        image_response = requests.get(image["url"], timeout=120)
        image_response.raise_for_status()
        image_bytes = image_response.content
    else:
        raise ValueError(f"No image payload found in response item: {image}")

    with open(output_path, "wb") as image_file:
        image_file.write(image_bytes)


with open("input_image.png", "rb") as image_file:
    image_base64 = base64.b64encode(image_file.read()).decode("utf-8")

response = requests.post(
    "https://api.avalai.ir/v1/images/edits",
    headers={
        "Authorization": f"Bearer {os.environ['AVALAI_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "gpt-image-2",
        "prompt": (
            "Change only the background to a tropical beach while preserving "
            "the person, pose, and lighting"
        ),
        "images": [{"image_url": f"data:image/png;base64,{image_base64}"}],
        "size": "1024x1024",
        "quality": "medium",
        "n": 1,
    },
    timeout=120,
)
response.raise_for_status()

save_image_result(response.json()["data"][0], "edited-beach.png")

Use multipart/form-data instead when the route expects uploaded files or binary masks. In that case, send image=@input_image.png and mask=@mask.png with curl, or use files={"image": image_file, "mask": mask_file} with Python requests. For JSON masks, use the same reference-object shape as images, for example { "image_url": "data:image/png;base64,..." } or { "file_id": "file_..." }.

Requirements:

  • The image and mask should use the same dimensions and compatible formats. Keep files below the selected route's upload limit; OpenAI's GPT Image reference uses a 50MB per image/mask guidance for edits.
  • The mask should include an alpha channel when the route expects transparency to identify editable regions.
  • For multi-image reference workflows, send each reference image explicitly and test token/cost impact before production. See Generate Images with GPT Image Models for specific masking techniques.

Variations (Model-Dependent)

Warning

Feature Not Implemented!

This functionality is currently under development and not yet available in AvalAI. We’ll announce its release through our official channels. Stay tuned for updates!

AvalAI does not currently list a supported variation model in data/models.json. For now, implement variations by calling v1/images/generations with a detailed description of the source image, or use v1/images/edits with the source image as a reference when your selected model supports edits.

Content Moderation

Prompts and images submitted via AvalAI are subject to moderation based on underlying provider policies and potentially AvalAI's own policies. Requests may be rejected if flagged.

For GPT Image routes that expose the OpenAI moderation control, keep moderation: "auto" for production defaults. Use moderation: "low" only after a product and safety review, because it can make filtering less restrictive for supported image models.

When a request is blocked, do not blindly retry the same payload. Log the request ID, endpoint, model, and stable error code; if the provider returns moderation details, keep them in developer logs and show the user a generic remediation message such as "Revise the prompt or input image and try again." OpenAI-style moderation details can include moderation_stage (input, output, or unknown) and coarse categories such as harassment, self-harm, sexual, or violence; treat those fields as optional debugging hints, not user-facing classifier explanations.

Handle image-specific user errors separately from transient infrastructure errors. If the provider returns an OpenAI-style image_generation_user_error, change the prompt, uploaded image, mask, size, or unsupported option before retrying. If the code is moderation_blocked, branch on that stable code first, then use optional moderation_details only to choose a safer user-facing hint.

Handling Image Data

Examples show reading files from disk. You can also use in-memory image data (e.g., BytesIO in Python, Buffer in Node.js). Ensure the data object includes a filename with the correct extension (e.g., .png) when passing it to the SDK function.

python
# Python Example with in-memory data (BytesIO)
import os
from io import BytesIO
from PIL import Image  # Example using Pillow library
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

# Assume 'image_data' is your raw image bytes (e.g., from a download)
# image = Image.open(BytesIO(image_data)) # Example: Load bytes into Pillow

# # --- Optional: Process image (e.g., resize) ---
# width, height = 512, 512
# image = image.resize((width, height))
# # --- End Optional Processing ---

byte_stream = BytesIO()
# Save to BytesIO object, ensuring PNG format if required by API endpoint
image.save(byte_stream, format="PNG")
byte_array = byte_stream.getvalue()

try:
    byte_stream.name = "reference.png"
    response = client.images.edit(
        model="gpt-image-2",
        image=byte_stream,
        prompt="Keep the original composition but make the lighting warmer.",
        n=1,
        size="1024x1024",
    )
    print(response.data[0].b64_json[:80] + "...")
except Exception as e:
    print(f"An error occurred: {e}")

Example with a FLUX Model

Here's a complete example of generating an image using a supported Black Forest Labs model:

python
# Python Example using a FLUX model via AvalAI
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

try:
    response = client.images.generate(
        model="flux.2-pro",
        prompt="A photorealistic mountain landscape with a lake reflecting the sunset, detailed lighting, high resolution",
        size="1024x1024",
        extra_body={
            "aspect_ratio": "16:9",
            "output_format": "png",
            "safety_tolerance": 2,
            "prompt_upsampling": True,
        },
        response_format="url",
    )
    image_url = response.data[0].url
    print(f"Generated image URL: {image_url}")
except Exception as e:
    print(f"An error occurred: {e}")

Error Handling

Wrap API calls in try...except (Python) or try...catch (JavaScript) blocks to handle potential errors like invalid inputs, rate limits, or provider issues.

python
# Python Error Handling Example
import os
import openai
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

try:
    response = client.images.generate(
        model="gpt-image-2",
        prompt="a valid prompt",
        n=1,
        size="1024x1024",
    )
    print(response.data[0].b64_json[:80] + "...")
except openai.APIError as e:
    # Handles API errors (e.g., rate limits, server errors from AvalAI/provider)
    print(f"API Error: {e.status_code} - {e.message}")
    print(e.body)  # Contains more details
except openai.AuthenticationError as e:
    print(f"Authentication Error: {e.message}")
except openai.BadRequestError as e:
    print(f"Bad Request Error: {e.message}")  # e.g., invalid parameters
except Exception as e:
    # Handles other potential errors (network issues, etc.)
    print(f"An unexpected error occurred: {e}")