Skip to main content
Lesson 9 of 14 · Generate and Edit Images with Grok

Batch generation and the n parameter

Lesson 9 of 14 Updated November 2, 2026 Beginner
On this page
  1. Generate multiple images in a single request
  2. The n parameter in detail
  3. Impact on costs and rate limits
  4. Selection strategies
  5. Batching multiple prompts
  6. Batch downloading
  7. Key takeaways

Updated November 2, 2026 — Imagine. grok-imagine-image-quality was removed on November 2, 2026 (its requests are now served by Imagine 2.0 in low quality): examples now use grok-imagine-image (Imagine 1.0) and grok-imagine-image-2.0 (Imagine 2.0, low, medium, or auto quality). With the OpenAI SDK, aspect_ratio, resolution, and quality are passed via extra_body, and editing is handled via the xAI SDK or an HTTP request.

Generate multiple images in a single request

The n parameter in the generation API lets you produce up to 10 images from a single prompt. Each image is a unique variation, giving you a range of choices to select the best result or build a gallery of visuals.

The n parameter in detail

The n parameter accepts an integer between 1 and 10, and defaults to 1. Its real value lies in a property of image generation that’s easy to forget: the result is non-deterministic. The same prompt produces different images every time you call it, and none is more “correct” than another. Generating four variations at once isn’t waste—it’s acknowledging that you don’t know in advance which one will work.

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1"
)

# Generate 5 variations
response = client.images.generate(
    model="grok-imagine-image",
    prompt="A zen Japanese garden with a red bridge, ukiyo-e style",
    n=5,
    extra_body={"aspect_ratio": "16:9", "resolution": "1k"},
)

for i, image in enumerate(response.data):
    print(f"Variation {i + 1}: {image.url}")

Impact on costs and rate limits

The key point to understand before building a pipeline on this: n=10 isn’t a discount. You pay for ten images and consume ten units of rate limit, exactly like ten separate calls. The only gain is network—one round trip instead of ten—which helps latency but doesn’t change the budget.

Parameter n=1 n=5 n=10
Cost (Imagine 1.0) $0.02 $0.10 $0.20
Cost (Imagine 2.0, low) $0.04 $0.20 $0.40
Images generated 1 5 10

A request with n=10 consumes the same budget as 10 individual requests with n=1, but it’s faster because it requires only one network call.

Selection strategies

Generating ten variations without a sorting method just shifts the problem: you had one uncertain image, now you have ten images to judge. The question to settle first is the criterion—aesthetic, where the human eye remains unbeatable; or verifiable (is the product visible, is the text legible, is the format respected), where automation becomes possible.

Manual selection

For critical cases (advertising, book covers), download all variations and compare them visually:

import urllib.request

response = client.images.generate(
    model="grok-imagine-image-2.0",
    prompt="Science fiction book cover, organic spaceship",
    n=8,
    extra_body={"aspect_ratio": "3:4", "resolution": "2k"},
)

for i, image in enumerate(response.data):
    urllib.request.urlretrieve(image.url, f"variation_{i + 1}.png")
    print(f"Variation {i + 1} saved")

Automated selection

Having a vision model judge the images works on one condition: the criterion must be factual. “Does this image contain a product centered on a solid background?” gets a reliable answer; “which one is the most beautiful?” gets an arbitrary answer presented with confidence. Formulate verifiable criteria, and keep aesthetic judgment for yourself.

def generate_and_select(prompt, n=5):
    """Generate n variations and return all URLs."""
    response = client.images.generate(
        model="grok-imagine-image",
        prompt=prompt,
        n=n
    )
    return [image.url for image in response.data]

Batching multiple prompts

To generate images from multiple different prompts, combine the calls:

prompts = [
    "Illustration of a Parisian café, impressionist style",
    "Aerial view of terraced rice fields, photographic style",
    "Interior of an old library, dim lighting"
]

all_results = {}
for prompt in prompts:
    response = client.images.generate(
        model="grok-imagine-image",
        prompt=prompt,
        n=3
    )
    all_results[prompt] = [img.url for img in response.data]

# 3 prompts x 3 variations = 9 images, total cost: $0.18

Batch downloading

This is the habit to build from the first line of code, not when deploying to production: URLs expire. A batch of ten images generated in the morning and downloaded in the evening is a lost batch—and you’ll have to pay for it again.

import urllib.request
import os

def download_batch(response, output_dir="generated"):
    """Download all images from a response."""
    os.makedirs(output_dir, exist_ok=True)

    for i, image in enumerate(response.data):
        filepath = os.path.join(output_dir, f"image_{i + 1}.png")
        urllib.request.urlretrieve(image.url, filepath)

    print(f"{len(response.data)} images saved in {output_dir}/")

Pricing as of August 5, 2026 — prices change regularly: before any budget calculation, check the current rate card on the official xAI models and pricing page.

Key takeaways

  • The n parameter lets you generate 1 to 10 variations per request
  • Each image counts individually for billing
  • Generating in batch (one request with n>1) is faster than n individual requests
  • Download results immediately because URLs are temporary
  • Use n=3 to 5 to explore, n=1 for targeted production