Developer Dashboard

Image Generation API ​

The Image Generation API allows you to create and edit images using AI models from various providers through the AvalAI platform.

For conversational or multi-step image workflows, AvalAI can also expose OpenAI-style Responses image-generation tools when the selected model and route support them. Keep the endpoints on this page as the direct, portable path, and see the Responses image migration path before moving image flows into /v1/responses.

Latest OpenAI Image Models ​

Use gpt-image-2.5-flare as the general default for faster generation and editing, or gpt-image-2.5-sunburst for tighter edit precision in premium product and campaign workflows at longer generation times. Both support /v1/images/generations and /v1/images/edits.

OpenAI reports improved lighting, textures, reference-subject retention, targeted edits, and consistency across multiple editing turns. The provider reports up to 50% lower generation latency for Flare versus GPT Image 2; this is not an AvalAI latency guarantee. For repeated edits, save each output and submit it as the source image for the next request, restating what must remain unchanged.

Do not use either image model ID as the model in /v1/responses. Hosted Responses image tools require a separately supported text-capable model. ChatGPT Sketch and templates are not AvalAI API features. See the release announcement.

GPT-6 Sol, GPT-6 Luna, and Grok 4.7 ​

OpenAI's gpt-6-sol and gpt-6-luna and xAI's grok-4.7 support image understanding and reasoning, but are not image-generation models. Do not send these IDs as the image model to v1/images/generations or v1/images/edits. Use dedicated models such as gpt-image-2.5-flare or gpt-image-2.5-sunburst for direct generation and editing.

Sol and Luna have full v1/chat/completions, v1/messages, and v1/responses support. Grok 4.7 has full Chat Completions and Messages support and partial v1/responses support. None of these endpoint declarations alone confirms access to the hosted image_generation tool; verify the selected model, route, and account separately. Grok's partial support is not full hosted-tool or stateful-workflow parity.

For a portable workflow, let a reasoning model analyze a reference image or prepare a text brief, then have your application call the dedicated Image API with an image model. See the new-model announcement and image generation guide.

Endpoint ​

POST https://api.avalai.ir/v1/images/generations

Request Body ​

ParameterTypeRequiredDescription
modelstringYesID of the model to use (e.g., gpt-image-2.5-flare or gpt-image-2.5-sunburst).
promptstringYesA text description of the desired image(s). Use a structured visual brief for GPT Image models when layout, text, or editing precision matters.
nintegerNoThe number of images to generate. Defaults to 1.
sizestringNoThe size of the generated images. Common OpenAI sizes include 1024x1024, 1024x1536, and 1536x1024; gpt-image-2 also supports flexible custom sizes within model constraints.
qualitystringNoModel-specific quality setting. GPT Image models use low, medium, high, or auto where supported. Only GPT Image 2.5 Flare and Sunburst additionally support xhigh and max; do not send these values to older models.
stylestringNoModel-specific style setting. Some legacy image models support values such as vivid or natural.
response_formatstringNoLegacy image models may support url or b64_json. GPT Image models return base64 image data; decode data[0].b64_json and save it yourself.
output_formatstringNoGPT Image output file format where supported: png, jpeg, or webp.
output_compressionintegerNoCompression level for JPEG/WebP output where supported.
backgroundstringNoBackground handling where supported. Use auto or opaque unless your selected model confirms transparent output support.
moderationstringNoGPT Image moderation level where exposed. Keep auto for production defaults; use low only after safety review.
streambooleanNoEnables streaming image generation where the route supports it.
partial_imagesintegerNoNumber of partial preview images to emit while streaming, where supported. GPT Image-style routes commonly use 0-3.
userstringNoA unique identifier representing your end-user, which can help monitor and detect abuse.

Output, Streaming, and Cost Notes ​

  • GPT Image-style routes return Base64 image data in data[0].b64_json; decode it and save the bytes yourself. Legacy or provider-specific routes may return URLs when they support response_format: "url".
  • Image generation usage can include input_tokens, output_tokens, and image-token details. Size, quality, input images, and partial previews affect cost and latency; check AvalAI pricing before bulk or high-resolution workflows.
  • Streaming generation emits preview events such as image_generation.partial_image and a final image_generation.completed event on supported Image API routes. partial_images controls how many previews are requested, but the route may return fewer if the final image completes quickly.
  • For gpt-image-2, keep background as auto or opaque; transparent backgrounds are not supported unless the selected AvalAI route explicitly documents otherwise.
  • Prefer jpeg or webp with output_compression when small files and latency matter. Use png when you need lossless output or alpha support from a model that supports transparency.

Examples ​

Basic Image Generation ​

For production prompting patterns, text-in-image guidance, localization, compositing, and surgical edits, see Generate Images with GPT Image. That guide adapts the official OpenAI Cookbook GPT Image prompting material for AvalAI.

bash
curl https://api.avalai.ir/v1/images/generations \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
  "model": "gpt-image-2.5-flare",
  "prompt": "A cute baby sea otter floating on its back in the ocean",
  "n": 1,
  "size": "1024x1024",
  "quality": "medium"
}' | jq -r '.data[0].b64_json' | base64 --decode >sea-otter.png
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",
)

response = client.images.generate(
    model="gpt-image-2.5-flare",
    prompt="A cute baby sea otter floating on its back in the ocean",
    n=1,
    size="1024x1024",
    quality="medium",
)

image_base64 = response.data[0].b64_json
with open("sea-otter.png", "wb") as image_file:
    image_file.write(base64.b64decode(image_base64))
javascript
import fs from "fs";
import OpenAI from "openai";

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

const response = await client.images.generate({
  model: "gpt-image-2.5-flare",
  prompt: "A cute baby sea otter floating on its back in the ocean",
  n: 1,
  size: "1024x1024",
  quality: "medium",
});

const imageBase64 = response.data[0].b64_json;
fs.writeFileSync("sea-otter.png", Buffer.from(imageBase64, "base64"));

Responses Image Tool Example ​

Use /v1/responses only when the selected AvalAI model and account support the hosted image_generation tool. The direct Image API above remains the portable default for one-shot generation and editing.

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",
)

response = client.responses.create(
    model="gpt-5.6-luna",
    input="Generate a friendly mascot for an API documentation site.",
    tools=[
        {
            "type": "image_generation",
            "action": "generate",
            "size": "1024x1024",
            "quality": "medium",
        }
    ],
)

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

if image_calls:
    with open("docs-mascot.png", "wb") as image_file:
        image_file.write(base64.b64decode(image_calls[0].result))
javascript
import fs from "fs";
import OpenAI from "openai";

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

const response = await client.responses.create({
  model: "gpt-5.6-luna",
  input: "Generate a friendly mascot for an API documentation site.",
  tools: [
    {
      type: "image_generation",
      action: "generate",
      size: "1024x1024",
      quality: "medium",
    },
  ],
});

const imageCall = response.output.find(
  (item) => item.type === "image_generation_call"
);

if (imageCall) {
  fs.writeFileSync("docs-mascot.png", Buffer.from(imageCall.result, "base64"));
}

Responses Tool Options ​

ParameterTypeDescription
typestringMust be image_generation.
actionstringOptional. Use auto to let the model choose, generate to force a new image, or edit to force editing when an image is in context.
sizestringImage dimensions, such as 1024x1024, 1024x1536, 1536x1024, or another route-supported size.
qualitystringRendering quality, commonly low, medium, high, or auto where supported.
output_formatstringOutput file format where supported: png, jpeg, or webp.
output_compressionintegerCompression level for JPEG/WebP outputs where supported.
backgroundstringUse auto or opaque unless the selected model confirms transparent output support.
partial_imagesintegerNumber of progressive preview images to stream, usually 0-3 where supported.
input_image_maskobjectMask object for Responses image edits, usually a file ID, where supported.

Provider-Specific Parameters ​

When using non-OpenAI image generation or editing models (such as Black Forest Labs, Alibaba, BytePlus, or Google models), you may need to pass provider-specific parameters that aren't directly supported by the OpenAI SDK. Use the extra_body parameter to pass these additional parameters.

Using extra_body for Provider-Specific Parameters ​

The system will automatically map 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

Example with Provider-Specific Parameters ​

python
import os
from openai import OpenAI

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

# 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,
    },
)

image_url = response.data[0].url
print(image_url)
javascript
import OpenAI from "openai";

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

// Using Black Forest Labs model with provider-specific parameters
const response = await client.images.generate({
    model: "flux-1.1-pro",
    prompt: "A majestic dragon soaring through clouds",
    size: "1024x1024",
    // @ts-expect-error extra_body is a provider-specific parameter
    extra_body: {
        aspect_ratio: "16:9",
        output_format: "png",
        safety_tolerance: 2,
        prompt_upsampling: true
    },
    response_format: "url", // or b64_json
});

const imageUrl = response.data[0].url;
console.log(imageUrl);

Alibaba Qwen Image Models ​

The Qwen image models support both OpenAI SDK format and native Alibaba Dashscope format, providing maximum flexibility for developers.

python
import os
from openai import OpenAI
import requests

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

# Text-to-image generation using OpenAI SDK format
response = client.images.generate(
    model="qwen-image",
    prompt="A serene mountain landscape with a crystal clear lake reflecting snow-capped peaks",
    size="1328x1328",
    n=1,
)

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

# Image editing using OpenAI SDK format
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 parameters
dashscope_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",
            "prompt_extend": True,
            "watermark": False,
            "negative_prompt": "blurry, low quality, distorted",
        },
    },
)

print(f"Dashscope format result: {dashscope_response.json()}")
javascript
import OpenAI from "openai";

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

// Text-to-image generation using OpenAI SDK format
const response = await client.images.generate({
    model: "qwen-image",
    prompt: "A futuristic cityscape with flying cars and neon lights",
    size: "1664x928", // 16:9 aspect ratio
    n: 1,
    response_format: "url", // or b64_json
});

console.log(`Generated image URL: ${response.data[0].url}`);

// Using native Dashscope format for advanced parameters
const dashscopeResponse = await fetch("https://api.avalai.ir/v1/images/generations", {
    method: "POST",
    headers: {
        "Authorization": `Bearer ${process.env.AVALAI_API_KEY}`,
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        model: "qwen-image",
        input: {
            messages: [
                {
                    role: "user",
                    content: [
                        {
                            text: "A magical forest scene with glowing mushrooms and fairy lights"
                        }
                    ]
                }
            ]
        },
        parameters: {
            size: "1328*1328",
            prompt_extend: true,
            watermark: false,
            negative_prompt: "dark, gloomy, scary"
        }
    })
});

const result = await dashscopeResponse.json();
console.log("Dashscope format result:", result);

Qwen Model-Specific Parameters ​

When using the native Dashscope format, you can access additional parameters:

  • prompt_extend - Enable intelligent prompt rewriting for better results
  • watermark - Control whether to add Qwen-Image watermark
  • negative_prompt - Specify what you don't want in the image
  • size - Support for multiple aspect ratios (1328×1328, 1664×928, 1472×1140, 1140×1472, 928×1664)
  • seed - Set random seed for reproducible results

Note

The specific parameters available depend on the model provider. Refer to the individual model documentation for complete parameter lists. The system will automatically handle the mapping of these parameters to the appropriate provider's API format.

Response Format ​

GPT Image routes return base64 image data. Decode data[0].b64_json and save the bytes yourself:

json
{
  "created": 1589478378,
  "data": [
    {
      "b64_json": "iVBORw0KGgoAAAANSUhEU...",
      "revised_prompt": "A cute baby sea otter with brown fur, floating on its back in the clear blue ocean water. The otter's small paws are visible as it rests peacefully, with gentle waves surrounding it under a bright sky."
    }
  ]
}

Some legacy image models or provider routes may return URLs when response_format is set to url:

json
{
  "created": 1589478378,
  "data": [
    {
      "url": "https://avalai-generated-images.storage.googleapis.com/image1.png",

      "revised_prompt": "A cute baby sea otter with brown fur, floating on its back in the clear blue ocean water. The otter's small paws are visible as it rests peacefully, with gentle waves surrounding it under a bright sky."
    }
  ]
}

Response Parameters ​

ParameterTypeDescription
createdintegerThe Unix timestamp (in seconds) of when the images were created.
dataarrayAn array of image objects.

Image Object ​

ParameterTypeDescription
b64_jsonstringThe base64-encoded image data. Present for GPT Image-style routes.
urlstringThe URL of the generated image. Only present when the selected model/route supports URL output.
revised_promptstringThe prompt that was used to generate the image, potentially modified for improved results.

Image Editing ​

AvalAI supports comprehensive image editing capabilities through the following endpoint:

POST https://api.avalai.ir/v1/images/edits

This allows you to edit an existing image by providing the image file and a descriptive prompt for the desired changes.

Request Body (Multipart or JSON) ​

ParameterTypeRequiredDescription
modelstringYesID of the model to use for editing (see supported models below).
imagefile or file[]Yes for multipartSource image file(s) to edit in multipart/form-data. Requirements are model-dependent; GPT Image-style routes can accept one or more source images.
imagesarrayYes for JSON edit requestsJSON source image references for GPT Image-style edit requests. Each item is an object with exactly one of image_url or file_id; image_url may be a fully qualified URL or a Base64 data URL. GPT Image-style routes can accept up to 16 input images where enabled.
maskfile or objectNoOptional mask. Use a file in multipart requests, or an object with exactly one of image_url or file_id in JSON requests. For GPT Image-style masking, use the same dimensions as the source image and include an alpha channel where required.
promptstringYesA text description of the desired final image. Describe the full final image, not only the changed area.
nintegerNoThe number of edited images to generate. Defaults to 1.
sizestringNoThe size of the edited images. Supported sizes are model-dependent.
qualitystringNoGPT Image quality where supported: low, medium, high, or auto. GPT Image 2.5 Flare and Sunburst also support xhigh and max; these are not options for older GPT Image models.
response_formatstringNoLegacy image models may support url or b64_json. GPT Image routes return base64 image data.
output_formatstringNoOutput file format where supported: png, jpeg, or webp.
output_compressionintegerNoCompression level for JPEG/WebP output where supported.
streambooleanNoEnables streaming image edits where supported.
partial_imagesintegerNoNumber of progressive preview images while streaming, where supported.
input_fidelitystringNoPreserves input details for supported models/routes. Omit for gpt-image-2, which processes image inputs at high fidelity automatically.
userstringNoA unique identifier representing your end-user, which can help monitor and detect abuse.

GPT Image 2.5 Pricing and Output Estimates ​

Both gpt-image-2.5-flare and gpt-image-2.5-sunburst use these confirmed AvalAI rates in USD per 1M tokens:

UsagePrice
Text input$5.00
Image input$8.00
Cached text input$1.25
Cached image input$2.00
Text output$0.00
Image output$30.00
QualityEstimated output component per 1024x1024 image, either model (USD)
low$0.00588
medium$0.01317
high$0.05268
xhigh$0.09366
max$0.21072

These estimates cover output image tokens only, not the total generation or edit cost. Add prompt text and all reference-image input tokens; cached rates apply only to eligible cached input. Use low for drafts, medium for general use, and compare high, xhigh, and max for final assets against your quality, time, and cost budget. The additional xhigh and max levels are specific to these GPT Image 2.5 models.

GPT Image 2 Edit Pricing and Cost Calculation ​

Edits made with gpt-image-2 on v1/images/edits use pure token-based billing rather than a fixed per-edit fee. The total cost consists of:

text
estimated edit cost = prompt text token cost
                    + all reference image input token costs
                    + output image token cost

Prompt text is billed at $5.00 / 1M tokens, image inputs at $8.00 / 1M tokens ($2.00 / 1M when cached), and image output at $30.00 / 1M tokens. The requested quality and size control the output image token count, while each source or reference image adds image input tokens.

Approximate Per-Image Costs by Quality and Resolution ​

The table shows estimated output image cost from OpenAI's image generation cost calculator. These values are not fixed flat rates and do not include prompt text or reference-image input tokens. Actual edit costs vary with prompt complexity, output size, and the number and dimensions of reference images.

Quality1024x1024 (square)1024x1536 (portrait)1536x1024 (landscape)
Low~$0.008~$0.012~$0.012
Medium~$0.032~$0.048~$0.048
High~$0.125~$0.187~$0.187

Always use OpenAI's official image generation calculator with your specific prompt, reference images, quality, and resolution for an exact estimate.

What Each Quality Setting Produces ​

  • Low: Faster generation at the lowest cost. Use it for drafts, small-format digital assets, and automated pipelines where cost control matters more than fine detail.
  • Medium: Suitable for most marketing and content production, including social media imagery, editorial graphics, product mockups, and campaign assets. It is sufficient for professional publication in most contexts.
  • High: Intended for final production assets where pixel-level accuracy matters, including hero product photography, high-resolution print materials, packaging designs, and detailed UI mockups.

For cost-sensitive edit workflows, iterate with quality="low", then render only the approved result with quality="high". See Generate Images with GPT Image for additional cost-control guidance.

Editing Request Formats and Masks ​

  • Use multipart/form-data when uploading local files: send source images with image / image[] and an optional binary mask.
  • Use application/json for GPT Image-style JSON edits: send source images in images as objects with exactly one of image_url or file_id. image_url can be either a fully qualified URL or a Base64 data URL such as data:image/png;base64,....
  • Send JSON masks as objects with exactly one of image_url or file_id, for example { "image_url": "data:image/png;base64,..." } or { "file_id": "file_..." }.
  • For masked edits, the mask and source image should use the same format and dimensions. GPT Image-style masks should include an alpha channel; transparent areas identify where the model may edit.
  • For gpt-image-2, omit input_fidelity; the model processes image inputs at high fidelity automatically. On older routes that expose it, use high fidelity for faces, logos, product packaging, screenshots, and other detail-preserving edits.
  • Streaming edits emit events such as image_edit.partial_image and image_edit.completed on supported routes. Treat partial images as previews and save the final completed output as the production asset.

Supported Models for Image Editing ​

The following models support the v1/images/edits endpoint:

OpenAI GPT Image Models ​

  • gpt-image-2.5-flare - Latest general default for faster image generation and editing
  • gpt-image-2.5-sunburst - Latest premium option for tighter edit precision at longer generation times
  • gpt-image-2 - Previous-generation GPT Image model for existing validated workflows
  • gpt-image-1.5 - Previous advanced GPT Image model for validated existing workflows
  • gpt-image-1 - GPT Image generation and editing model
  • gpt-image-1-mini - Lower-cost GPT Image model for drafts and high-volume ideation

Black Forest Labs Models ​

  • flux.1-kontext-pro - Advanced FLUX model with professional image editing capabilities

Google Models ​

  • gemini-3.1-flash-image (Nano Banana 2) - Flagship Google image model; use it through v1/chat/completions or v1beta/ for image-to-image editing workflows. All imagen-* models are deprecated and removed from the catalog.

Alibaba Models ​

  • qwen-image-2.0-pro - Professional image editing with strong typography support
  • qwen-image-2.0 - Unified generation and editing for photorealistic output
  • qwen-image-edit-plus - Advanced image editing with multi-image support
  • qwen-image-edit - Image editing with multi-image input support

GPT Image 2.5 Sunburst Editing with curl ​

Set AVALAI_API_KEY and provide a local source image named input_image.png. This multipart example requires curl, jq, and base64. Flare supports the same endpoint; change only the model ID to compare results.

bash
curl --fail-with-body https://api.avalai.ir/v1/images/edits \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -F "model=gpt-image-2.5-sunburst" \
  -F "image=@input_image.png" \
  -F "prompt=Change only the background to warm white. Keep the product, logo, texture, camera angle, and composition unchanged." \
  -F "size=1024x1024" \
  -F "quality=high" \
  -F "n=1" >sunburst-response.json \
  && jq -er '.data[0].b64_json' sunburst-response.json | base64 --decode >sunburst-edit.png

Image Editing Example ​

python
import os
from openai import OpenAI

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

# Edit existing image
with open("input_image.png", "rb") as image_file:
    response = client.images.edit(
        model="gpt-image-2",
        image=image_file,
        prompt="Add a rainbow in the sky above the mountains",
        size="1024x1024",
        n=1,
    )

# Save edited image
import base64

edited_image = base64.b64decode(response.data[0].b64_json)
with open("edited_image.png", "wb") as f:
    f.write(edited_image)

print("✅ Image edited and saved as edited_image.png")
javascript
import fs from 'fs';
import OpenAI from "openai";

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

// Edit existing image
const imageFile = fs.createReadStream("input_image.png");
const response = await client.images.edit({
 model: "gpt-image-2",
 image: imageFile,
 prompt: "Add a rainbow in the sky above the mountains",
 size: "1024x1024",
 n: 1,
});

// Save edited image
const imageBase64 = response.data[0].b64_json;
fs.writeFileSync("edited_image.png", Buffer.from(imageBase64, "base64"));

console.log("✅ Image edited and saved as edited_image.png");

Image Edit with Base64 Input (Without the SDK) ​

If you are working in an environment without the OpenAI SDK, you can call v1/images/edits directly over HTTP. For GPT Image-style JSON edit requests, encode the source image as a Base64 data URL (data:{mime_type};base64,{encoded_data}) and send it in the images array using an object with image_url, following the request formats above. This is the expected JSON schema for image references; image_url can also be a public HTTPS URL, and file_id can be used for images uploaded through the Files API. Depending on the route, the edited image may come back in data[0].b64_json, as a Base64 data URL in data[0].url, or as a downloadable URL; handle all supported shapes before saving the bytes.

bash
# Encode the source image as Base64 (use `base64 -w 0` on Linux for no line breaks)
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": "Add a rainbow in the sky above the mountains",
  "images": [
    { "image_url": "data:image/png;base64,'"$IMAGE_BASE64"'" }
  ],
  "size": "1024x1024",
  "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_image.png
python
import base64
import os

import requests


def save_image_result(image, output_path):
    """Save an image result that may contain b64_json, a data URL, or a 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 f:
        f.write(image_bytes)


# Encode the source image as a Base64 data URL
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": "Add a rainbow in the sky above the mountains",
        "images": [{"image_url": f"data:image/png;base64,{image_base64}"}],
        "size": "1024x1024",
        "n": 1,
    },
)
response.raise_for_status()

save_image_result(response.json()["data"][0], "edited_image.png")

print("✅ Image edited and saved as edited_image.png")

If your route only supports multipart/form-data, upload the raw file instead of Base64 — with curl use -F "image=@input_image.png", and with Python requests pass the open file handle via files={"image": image_file} as shown in the Qwen example above. Base64 data URLs apply to JSON edit requests only.

Image Variations ​

AvalAI does not currently list a supported variation model in data/models.json. Keep this endpoint as a compatibility placeholder and use v1/images/edits with a source image or v1/images/generations with a detailed source-image brief for variation-style workflows.

POST https://api.avalai.ir/v1/images/variations

Available Models ​

AvalAI supports various image generation and editing models from different providers:

Image Generation Models ​

ProviderModelDescriptionSupported Endpoints
BytePlusseedream-5-0-260128Most advanced Seedream model with Chain of Thought reasoning, MJ-style aesthetics, and intelligent prompt optimizationv1/images/generations, v1/images/edits
BytePlusseedream-4-5-251128Latest Seedream model with enhanced generation modes, improved prompt adherence, and multi-image editing capabilitiesv1/images/generations, v1/images/edits
OpenAIgpt-image-2.5-flareLatest general default for faster generation and editing/v1/images/generations, /v1/images/edits
OpenAIgpt-image-2.5-sunburstLatest premium model for tighter edit precision at longer generation times/v1/images/generations, /v1/images/edits
OpenAIgpt-image-2Previous-generation model with strong prompt adherence and editing capabilitiesv1/images/generations, v1/images/edits
OpenAIgpt-image-1.5Previous advanced image generation and editing modelv1/images/generations, v1/images/edits
OpenAIgpt-image-1OpenAI's advanced image generation and editing model (Tier 3, 4, 5 only)v1/images/generations, v1/images/edits
OpenAIgpt-image-1-miniCost-efficient version of GPT Image 1 for high-volume applications (Tier 3, 4, 5 only)v1/images/generations, v1/images/edits
Black Forest Labsflux.2-proMost advanced FLUX model with superior image quality and megapixel-based pricingv1/images/generations
Black Forest Labsflux-1.1-proAdvanced FLUX modelv1/images/generations
Black Forest Labsflux.1-kontext-proAdvanced FLUX model with professional editing capabilitiesv1/images/generations

| Google | gemini-2.5-flash-image | Nano Banana - Stable state-of-the-art image generation model with text-to-image and image-to-image capabilities | v1/chat/completions | | Google | gemini-3-pro-image | Nano Banana Pro (stable) - Professional-grade image generation for brand assets, photorealistic quality | v1/chat/completions, v1beta/ | | Google | gemini-3.1-flash-image | Nano Banana 2 (stable) - Flagship high-efficiency image generation with up to 4K resolution, advanced text rendering | v1/chat/completions, v1beta/ | | Google | gemini-3.1-flash-lite-image | Nano Banana 2 Lite - Efficiency specialist with sub-2 second latency and cost-effective generation at 1K resolution | v1/chat/completions, v1beta/ | | Google | gemini-3-pro-image-preview | Legacy preview alias for Nano Banana Pro. Prefer gemini-3-pro-image for new production integrations | v1/chat/completions | | Google | gemini-3.1-flash-image-preview | Legacy preview alias for Nano Banana 2. Prefer gemini-3.1-flash-image for new production integrations | v1/chat/completions | | Google | imagen-4.0-ultra-generate-001 | ❌ Deprecated and removed - Ultra-high quality image generation. Migrate to gemini-3-pro-image | Removed | | Google | imagen-4.0-generate-001 | ❌ Deprecated and removed - High-quality professional image generation. Migrate to gemini-3.1-flash-image | Removed | | Google | imagen-4.0-fast-generate-001 | ❌ Deprecated and removed - Fast image generation. Migrate to gemini-3.1-flash-image | Removed | | Google | imagen-3.0-generate-002 | ❌ Deprecated and removed - Imagen 3.0 refresh. Migrate to gemini-3.1-flash-image | Removed | | Google | imagen-3.0-generate-001 | ❌ Deprecated and removed - Google's Imagen 3.0 model for image generation and editing. Migrate to gemini-3.1-flash-image | Removed | | Google | imagen-3.0-fast-generate-001 | ❌ Deprecated and removed - Fast Imagen 3.0 variant. Migrate to gemini-3.1-flash-image | Removed | | Alibaba | qwen-image-3.0-pro | Professional image generation and editing; $0.04 at 1K/~1 MP, $0.075 at 2–4 MP, plus $0.003 per reference image | v1/images/generations, v1/images/edits | | Alibaba | qwen-image-3.0 | General image generation and editing; $0.04 at 1K/~1 MP, $0.075 at 2–4 MP, plus $0.003 per reference image | v1/images/generations, v1/images/edits | | Alibaba | qwen-image-2.0-pro | Professional image generation with advanced typography and 2K native resolution | v1/images/generations | | Alibaba | qwen-image-2.0 | Unified generation and editing with 2K native resolution and photorealism | v1/images/generations, v1/images/edits | | Alibaba | z-image-turbo | Ultra-fast image generation with Thinking mode for enhanced quality | v1/images/generations | | Alibaba | qwen-image | Advanced text-to-image generation with intelligent prompt enhancement | v1/images/generations | | Cloudflare | cf.flux-2-klein-9b | FLUX 2 Klein 9B - High quality image generation | v1/images/generations | | Cloudflare | cf.flux-2-klein-4b | FLUX 2 Klein 4B - Fast image generation | v1/images/generations | | Cloudflare | cf.flux-2-dev | FLUX 2 Dev - Development version with flexible features | v1/images/generations | | Cloudflare | cf.lucid-origin | Lucid Origin - Creative and artistic image generation | v1/images/generations | | Cloudflare | cf.phoenix-1.0 | Phoenix 1.0 - Balanced quality and speed | v1/images/generations |

Image Editing Models ​

ProviderModelDescriptionSupported Endpoints
OpenAIgpt-image-2.5-flareLatest general default for faster editing/v1/images/edits
OpenAIgpt-image-2.5-sunburstLatest premium option for tighter edit precision at longer generation times/v1/images/edits
OpenAIgpt-image-2Previous-generation image editing modelv1/images/edits
OpenAIgpt-image-1.5Previous advanced image editing modelv1/images/edits
OpenAIgpt-image-1OpenAI's advanced image generation and editing model (Tier 3, 4, 5 only)v1/images/edits
OpenAIgpt-image-1-miniCost-efficient version of GPT Image 1 for high-volume applications (Tier 3, 4, 5 only)v1/images/edits
Black Forest Labsflux.1-kontext-proAdvanced FLUX model with professional editing capabilitiesv1/images/edits
Googlegemini-3.1-flash-imageNano Banana 2 - Flagship Google image editing model (replaces the removed imagen-* editing routes); use through v1/chat/completions or v1beta/v1/chat/completions, v1beta/
Alibabaqwen-image-3.0-proProfessional editing with $0.003 charged per reference/input imagev1/images/edits
Alibabaqwen-image-3.0General image editing with $0.003 charged per reference/input imagev1/images/edits
Alibabaqwen-image-2.0-proProfessional editing with near-zero typography errors in 40+ languagesv1/images/edits
Alibabaqwen-image-2.0Unified generation and editing with professional photorealistic outputv1/images/edits
Alibabaqwen-image-edit-plusAdvanced image editing with enhanced quality and multi-image supportv1/images/generations, v1/images/edits
Alibabaqwen-image-editSophisticated image editing with multi-image input supportv1/images/edits

Error Handling ​

The API may return various error codes:

Status CodeDescription
400Bad Request - Your request is invalid (e.g., prompt too long).
401Unauthorized - Your API key is wrong.
403Forbidden - You don't have permission to access this resource.
404Not Found - The specified resource could not be found.
429Too Many Requests - You have exceeded your rate limit.
500Internal Server Error - We had a problem with our server.

For more information on handling errors, see the Error Handling guide.

For image-specific user errors, avoid automatic retries until you change the prompt, mask, or source image. Moderation failures may use error.code = "moderation_blocked" and can include optional moderation_details with:

  • moderation_stage: input, output, or unknown
  • categories: coarse public labels such as harassment, self-harm, sexual, or violence

Use those details for developer logs and support workflows, but keep end-user messages generic and actionable.

Content Moderation ​

All image generation requests are subject to content moderation. Prompts or generated outputs that violate the content policy will be rejected. GPT Image-style routes may expose a moderation parameter; keep auto for production defaults and use low only after safety review. For more information, see the Content Policy guide.