Skip to main content
Flux is an industry-leading image generation model. Through APIYI’s OpenAI-compatible interface, you can easily call Flux Kontext Pro and Max models to generate high-quality images. We offer more competitive pricing than official rates, combined with exchange rate advantages and top-up bonuses to save you more.
🎯 High-Quality Generation Flux models are renowned for excellent image quality and detail representation, supporting flexible aspect ratios from 3:7 to 7:3.

🌟 Core Features

  • 📐 Flexible Ratios: Supports continuous aspect ratio range from 3:7 to 7:3
  • 🎨 High-Quality Output: 1 megapixel images with rich details and strong artistic expression
  • 💰 Pricing Advantage: More affordable than official pricing, reducing costs
  • 🔧 OpenAI Compatible: Uses standard Images API format, easy to integrate
  • ⏱️ URL Validity: Generated result URLs valid for 10 minutes, download promptly
  • 🔄 Reproducibility: Supports seed parameter for consistent results

📋 Model Comparison

ModelModel IDAPIYI PriceOfficial PriceSavingsFeatures
Flux Kontext Proflux-kontext-pro$0.035/call$0.040/image12.5%Cost-effective, suitable for batch use
Flux Kontext Maxflux-kontext-max$0.07/call$0.08/image12.5%Highest quality, suitable for professional use
💡 Pricing Advantage: Calling Flux models through APIYI, combined with exchange rate advantage (1:7) and top-up bonus policy (15% bonus on $100+ top-ups), saves over 25% compared to official pricing!

📐 Supported Aspect Ratios

Flux models support continuous aspect ratio range from 3:7 to 7:3, maintaining approximately 1 megapixel total. Here are some common ratio examples:
Ratio IDTypeApproximate SizeUse Cases
1:1Square1024×1024General scenarios, social media avatars
2:3Portrait~832×1248Phone wallpaper, portrait photos
3:2Landscape~1248×832Computer wallpaper, landscape photos
4:3Standard landscape~1182×886Traditional monitors, presentations
16:9Widescreen~1408×792Modern monitors, video thumbnails
9:16Vertical screen~792×1408Mobile videos, vertical posters
21:9Ultra-wide~1680×720Movie posters, ultra-wide monitors
3:7Narrowest portrait~662×1544Bookmarks, vertical long images
7:3Widest landscape~1544×662Website banners, panoramas
📏 Custom Ratios: Besides the above examples, you can use any ratio within the 3:7 to 7:3 range, such as 5:4, 4:5, 16:10, etc. The system automatically adjusts dimensions to maintain approximately 1 megapixel total area.

🚀 Quick Start

Basic Example

from openai import OpenAI

# Initialize client
client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.apiyi.com/v1"
)

# Generate image (full parameter version)
def generate_flux_image(prompt, aspect_ratio="1:1", model="flux-kontext-pro",
                       seed=None, safety_tolerance=2, output_format="jpeg",
                       prompt_upsampling=False):
    """
    Generate Flux image

    Parameters:
    - prompt: Image description text
    - aspect_ratio: Aspect ratio (3:7 to 7:3)
    - model: Model selection
    - seed: Random seed for result reproduction
    - safety_tolerance: Content safety level (0-6)
    - output_format: Output format "jpeg" or "png"
    - prompt_upsampling: Whether to enhance prompts
    """
    try:
        # Build extra_body parameters
        extra_params = {
            "aspect_ratio": aspect_ratio,
            "safety_tolerance": safety_tolerance,
            "output_format": output_format,
            "prompt_upsampling": prompt_upsampling
        }

        # Optional parameters
        if seed is not None:
            extra_params["seed"] = seed

        response = client.images.generate(
            model=model,
            prompt=prompt,
            extra_body=extra_params
        )

        # Get image URL (note: expires after 10 minutes)
        image_url = response.data[0].url
        return image_url

    except Exception as e:
        print(f"Generation failed: {e}")
        return None

# Usage example
image_url = generate_flux_image(
    prompt="A futuristic city with flying cars and neon lights",
    aspect_ratio="16:9",
    model="flux-kontext-pro",
    seed=42,  # Fixed seed for reproducibility
    safety_tolerance=2,  # Default safety level
    output_format="png",  # High-quality PNG format
    prompt_upsampling=True  # Enhance prompt effect
)

if image_url:
    print(f"Generated image: {image_url}")
    print("⚠️ Note: URL will expire after 10 minutes, download promptly!")

📝 Parameter Details

Parameters Passed via extra_body

ParameterTypeRange/OptionsDescriptionDefault
aspect_ratiostring3:7 to 7:3Output image aspect ratio”1:1”
seedintegerAny integerRandom seed for result reproductionRandom
safety_toleranceinteger0-6Content safety control, 0=strictest, 6=most lenient2
output_formatstring”jpeg”, “png”Output image format”jpeg”
prompt_upsamplingbooleantrue/falseWhether to auto-enhance promptsfalse
💡 Prompt Enhancement: Enabling prompt_upsampling allows AI to automatically optimize and expand your prompts, but may change original intent. Recommend testing effect first.

Advanced Example - Batch Generate Different Ratios

import requests
import time
from PIL import Image
from io import BytesIO

def batch_generate_flux(prompts_with_ratios, model="flux-kontext-pro"):
    """Batch generate images with different ratios"""
    results = []

    for prompt, ratio in prompts_with_ratios:
        try:
            print(f"Generating {ratio} ratio image...")

            response = client.images.generate(
                model=model,
                prompt=prompt,
                extra_body={"aspect_ratio": ratio}
            )

            image_url = response.data[0].url

            # Download and save image
            filename = save_image_from_url(image_url, prompt, ratio)

            results.append({
                "prompt": prompt,
                "ratio": ratio,
                "url": image_url,
                "filename": filename,
                "success": True
            })

        except Exception as e:
            results.append({
                "prompt": prompt,
                "ratio": ratio,
                "error": str(e),
                "success": False
            })

    return results

def save_image_from_url(url, prompt, ratio):
    """Download and save image from URL (considering 10-minute expiry)"""
    try:
        # Download immediately to avoid URL expiry
        response = requests.get(url, timeout=30)
        response.raise_for_status()

        # Generate filename
        timestamp = int(time.time())
        safe_prompt = prompt[:30].replace(" ", "_").replace("/", "_")
        filename = f"flux_{safe_prompt}_{ratio.replace(':', 'x')}_{timestamp}.png"

        with open(filename, 'wb') as f:
            f.write(response.content)

        print(f"✅ Saved: {filename}")
        return filename

    except requests.exceptions.RequestException as e:
        print(f"❌ Download failed: {e}")
        print("Note: Flux URLs are only valid for 10 minutes, ensure timely download!")
        return None

# Batch generation example
prompts_and_ratios = [
    ("A beautiful sunset over mountains", "3:2"),
    ("Portrait of a wise old wizard", "2:3"),
    ("Cyberpunk street scene", "16:9"),
    ("Minimalist app icon design", "1:1")
]

results = batch_generate_flux(prompts_and_ratios, "flux-kontext-max")

# Print results
for result in results:
    if result["success"]:
        print(f"✅ {result['prompt']} ({result['ratio']}) -> {result['filename']}")
    else:
        print(f"❌ {result['prompt']} ({result['ratio']}) -> {result['error']}")

Node.js Example

const OpenAI = require('openai');
const fs = require('fs');
const https = require('https');

// Initialize client
const openai = new OpenAI({
  apiKey: 'YOUR_API_KEY',
  baseURL: 'https://api.apiyi.com/v1'
});

// Generate Flux image
async function generateFluxImage(prompt, aspectRatio = '1:1', model = 'flux-kontext-pro') {
  try {
    const response = await openai.images.generate({
      model: model,
      prompt: prompt,
      extra_body: {
        aspect_ratio: aspectRatio
      }
    });

    return response.data[0].url;
  } catch (error) {
    console.error('Generation failed:', error);
    return null;
  }
}

// Download image
function downloadImage(url, filename) {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(filename);
    https.get(url, (response) => {
      response.pipe(file);
      file.on('finish', () => {
        file.close();
        resolve(filename);
      });
    }).on('error', (err) => {
      fs.unlink(filename, () => {}); // Delete failed file
      reject(err);
    });
  });
}

// Usage example
async function main() {
  const scenarios = [
    {
      prompt: "A serene Japanese garden with cherry blossoms",
      ratio: "3:2",
      model: "flux-kontext-pro"
    },
    {
      prompt: "Abstract geometric pattern in vibrant colors",
      ratio: "1:1",
      model: "flux-kontext-max"
    }
  ];

  for (const scenario of scenarios) {
    console.log(`Generating image: ${scenario.prompt}`);

    const imageUrl = await generateFluxImage(
      scenario.prompt,
      scenario.ratio,
      scenario.model
    );

    if (imageUrl) {
      const filename = `flux_${Date.now()}.png`;
      await downloadImage(imageUrl, filename);
      console.log(`Saved: ${filename}`);
    }
  }
}

main().catch(console.error);

🎯 Use Cases

1. Web Design Assets

# Website banner
banner = generate_flux_image(
    "Modern website banner with clean design and tech elements",
    aspect_ratio="7:3",
    model="flux-kontext-max"
)

# Product showcase image
product = generate_flux_image(
    "Elegant product photography of a smartphone on white background",
    aspect_ratio="1:1",
    model="flux-kontext-pro"
)

2. Social Media Content

# Instagram post
instagram_post = generate_flux_image(
    "Inspirational quote design with aesthetic background",
    aspect_ratio="1:1",
    model="flux-kontext-pro"
)

# Mobile wallpaper
mobile_wallpaper = generate_flux_image(
    "Abstract cosmic art with stars and nebula",
    aspect_ratio="9:16",
    model="flux-kontext-max"
)

3. Professional Design

# Poster design
poster = generate_flux_image(
    "Concert poster design with bold typography and music elements",
    aspect_ratio="2:3",
    model="flux-kontext-max"
)

# Website background
background = generate_flux_image(
    "Subtle geometric pattern for website background",
    aspect_ratio="16:9",
    model="flux-kontext-pro"
)

💡 Best Practices

1. URL Management and Download Strategy

Since Flux generated image URLs are only valid for 10 minutes, proper download strategy is crucial:
import time
from concurrent.futures import ThreadPoolExecutor
import requests

class FluxImageManager:
    """Flux image generation and download manager"""

    def __init__(self, api_key, base_url="https://api.apiyi.com/v1"):
        self.client = OpenAI(api_key=api_key, base_url=base_url)

    def generate_and_save(self, prompt, **kwargs):
        """Generate image and save immediately"""
        start_time = time.time()

        # Generate image
        image_url = generate_flux_image(prompt, **kwargs)
        if not image_url:
            return None

        # Download immediately (avoid timeout)
        elapsed = time.time() - start_time
        if elapsed > 540:  # Over 9 minutes
            print("⚠️ Warning: Approaching URL expiry time!")

        # Download and save
        filename = f"flux_{int(time.time())}.png"
        try:
            response = requests.get(image_url, timeout=30)
            response.raise_for_status()

            with open(filename, 'wb') as f:
                f.write(response.content)

            print(f"✅ Saved: {filename} (took: {elapsed:.1f}s)")
            return filename

        except Exception as e:
            print(f"❌ Download failed: {e}")
            return None

2. Model Selection Recommendations

Flux Kontext Pro:
  • ✅ Daily design needs
  • ✅ Batch content generation
  • ✅ Cost-sensitive projects
  • ✅ Rapid prototyping
Flux Kontext Max:
  • ✅ Professional design work
  • ✅ Commercial use images
  • ✅ High-quality requirements
  • ✅ Print output needs

3. Prompt Optimization

Based on official documentation recommendations, detailed and descriptive prompts yield better results:
# ❌ Too simple
prompt = "cat"

# ✅ Detailed description
prompt = """
A majestic orange tabby cat sitting by a window,
golden hour lighting, soft focus background,
professional pet photography style,
warm and cozy atmosphere
"""

# ✅ Use prompt_upsampling to enhance simple prompts
enhanced_result = generate_flux_image(
    prompt="cat by window",
    prompt_upsampling=True  # AI will auto-expand and optimize prompt
)

# ✅ Artistic style prompts
artistic_prompt = """
A surreal landscape painting in the style of Salvador Dali,
melting clocks draped over twisted trees,
vibrant sunset colors bleeding into a starry night sky,
hyper-detailed, dreamlike atmosphere
"""

4. Aspect Ratio Selection Strategy

def choose_aspect_ratio(use_case):
    """Choose best aspect ratio based on use case"""
    ratios = {
        "social_media_post": "1:1",
        "mobile_wallpaper": "9:16",
        "desktop_wallpaper": "16:9",
        "portrait_photo": "2:3",
        "landscape_photo": "3:2",
        "website_banner": "7:3",
        "bookmark_design": "3:7"
    }
    return ratios.get(use_case, "1:1")

# Usage example
ratio = choose_aspect_ratio("mobile_wallpaper")
wallpaper = generate_flux_image("Peaceful forest scene", ratio)

5. Batch Processing Optimization

Considering the 10-minute URL expiry limitation, batch processing requires special attention:
import asyncio
import aiohttp

async def generate_async(session, prompt, ratio, model):
    """Asynchronously generate image"""
    payload = {
        "model": model,
        "prompt": prompt,
        "extra_body": {"aspect_ratio": ratio}
    }

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

    async with session.post(
        "https://api.apiyi.com/v1/images/generations",
        json=payload,
        headers=headers
    ) as response:
        result = await response.json()
        return result["data"][0]["url"]

async def batch_generate_async(tasks):
    """Asynchronous batch generation"""
    async with aiohttp.ClientSession() as session:
        results = await asyncio.gather(*[
            generate_async(session, prompt, ratio, model)
            for prompt, ratio, model in tasks
        ])
    return results

📊 Cost Comparison Analysis

def calculate_flux_costs(num_images, model_type="pro"):
    """Calculate Flux generation costs"""
    prices = {
        "pro": {"apiyi": 0.035, "official": 0.040},
        "max": {"apiyi": 0.07, "official": 0.08}
    }

    apiyi_cost = num_images * prices[model_type]["apiyi"]
    official_cost = num_images * prices[model_type]["official"]
    savings = official_cost - apiyi_cost

    print(f"Flux Kontext {model_type.upper()} Cost Analysis:")
    print(f"Generation count: {num_images} images")
    print(f"APIYI price: ${apiyi_cost:.2f}")
    print(f"Official price: ${official_cost:.2f}")
    print(f"Savings: ${savings:.2f}")
    print(f"Savings percentage: {(savings/official_cost*100):.1f}%")

# Cost calculation examples
calculate_flux_costs(100, "pro")   # 100 Pro version
calculate_flux_costs(50, "max")    # 50 Max version

⚠️ Important Notes

  1. URL Validity:
    • Generated image URLs are only valid for 10 minutes
    • Must complete download before expiry
    • Recommend downloading immediately after generation
  2. Parameter Passing:
    • All Flux-specific parameters must be passed via extra_body
    • Cannot use Flux proprietary parameters directly in top-level parameters
  3. Aspect Ratio Range:
    • Supports continuous range from 3:7 to 7:3
    • Not limited to fixed ratios, can use any ratio within range
    • System automatically adjusts dimensions to maintain approximately 1 megapixel
  4. Content Safety:
    • safety_tolerance parameter controls moderation strictness (0-6)
    • 0 = Strictest, 6 = Most lenient
    • Default value 2 suitable for most scenarios
  5. Output Format:
    • Default JPEG format, smaller files
    • PNG format higher quality but larger files
    • Choose appropriate format based on use case
  6. Prompt Processing:
    • prompt_upsampling will auto-optimize prompts
    • May change original intent, recommend testing first
    • Significant effect on simple prompts

🔍 FAQ

Q: Why do image URLs expire?

A: This is Flux’s official security design, all generated image URLs automatically expire after 10 minutes. Please ensure timely download and save.

Q: What’s the difference between Flux and other models?

A: Flux models focus on high-quality image generation, supporting flexible aspect ratios (3:7 to 7:3), particularly suitable for professional design requiring specific dimensions.

Q: How to choose between Pro and Max versions?

A:
  • Pro: Cost-effective, $0.035/image, suitable for daily use and batch generation
  • Max: Highest quality, $0.07/image, suitable for commercial work and professional needs

Q: Can I use any aspect ratio?

A: You can use any ratio within the 3:7 to 7:3 range, such as 5:4, 16:10, 21:9, etc. The system will automatically adjust to maintain approximately 1 megapixel.

Q: How to set safety_tolerance?

A:
  • 0-1: Enterprise/commercial environment, strictest
  • 2-3: General creation, balanced mode (recommended)
  • 4-6: Artistic creation, more lenient

Q: What does prompt_upsampling do?

A: When enabled, AI automatically expands and optimizes your prompts, especially suitable for short prompts. But may change original meaning, recommend testing effect first.

Q: How to ensure reproducible results?

A: Use the same seed value and identical other parameters to generate consistent results. This is helpful for iterative design.

Q: How to avoid URL expiry in batch generation?

A:
  1. Download immediately after generation
  2. Use concurrency control to avoid excessive processing time
  3. Consider using asynchronous processing to improve efficiency

🎯 Multi-Image Processing Solution

Flux API natively only supports single image input, but through our batch processing script, you can achieve dual image composition processing.

Application Scenarios

  • Pattern Transfer: Transfer design patterns to clothing models
  • Style Fusion: Combine characteristic elements from two images
  • Comparison Display: Simultaneously show original and target effect

Technical Principle

  1. Auto Download: Fetch two input images from URLs
  2. Smart Merge: Use Python PIL to splice images left-right
  3. API Call: Pass merged image as single input
  4. Result Processing: AI performs smart processing based on merged image
  • Supports automated processing of multiple image pairs
  • Unified prompt control for processing effect
  • Auto result download and file management
  • Complete error handling and logging

Quick Start

# Download batch processing script
wget https://raw.githubusercontent.com/apiyi-api/ai-api-code-samples/main/flux-Image-API/flux-simple-batch.sh
chmod +x flux-simple-batch.sh

# Modify configuration
# 1. Set your API_KEY
# 2. Configure image pair array
# 3. Customize processing prompt

# Run batch processing
./flux-simple-batch.sh

Configuration Example

# Prompt configuration
BATCH_PROMPT="Look at the left image and right image. Transfer the pattern/design from the left image to the clothes of the model in the right image, with the size being 2/3 of the width of the chest, located in the middle. Make it look natural and well-integrated."

# Image pair array
IMAGE_PAIRS=(
    "https://example.com/pattern1.jpg|https://example.com/model1.jpg"
    "https://example.com/design2.jpg|https://example.com/shirt2.jpg"
)
Dependency Requirements: Script requires jq, Python3 + PIL, and optional ImageMagick. See script help for detailed installation instructions.
🎨 Professional Tip: Combining different aspect ratios and model versions can meet various needs from social media to professional design!