> ## Documentation Index
> Fetch the complete documentation index at: https://docs.laozhang.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Grok Imagine API: generate and edit images

> Generate 1K or 2K images with grok-imagine-image-2.0 at $0.055 per image using a LaoZhang API key, no xAI account, and edit with up to three references.

Grok Imagine Image 2.0 is xAI's current image model. Text-to-image and reference editing both use the OpenAI-compatible Images endpoints, and one request can return several images.

## What grok-imagine-image-2.0 supports

| Item | Details |
| - | - |
| Model ID | `grok-imagine-image-2.0`, including the final `.0` |
| Price | **\$0.055 per image** at `1k` or `2k` and `low` or `medium`, for both generation and editing, billed per successfully returned image |
| Account | No xAI account needed, only a LaoZhang API key |
| Token group and billing mode | `default`; Usage first (recommended) or Per-call |
| Endpoints | Text-to-image: JSON `POST /v1/images/generations`; reference editing: multipart `POST /v1/images/edits` |
| Concurrency and rate limits | No platform limit on concurrency and no throttling; a `429` comes from upstream capacity, see [Concurrency and 429](/en/faq/api-concurrency) |
| Failed requests | Non-200 responses with no image aren't billed; check the call log after a timeout, see [Billing and failure rules](/en/api-capabilities/image-billing-and-failures) |

Public pricing as of September 24, 2026, verified on October 14, 2026; see the [model and pricing catalog](/en/models). The model comes from xAI's official channel and is billed at one fixed price per image. xAI prices by resolution and quality, \$0.06 for 1K medium or 2K low and \$0.08 for 2K medium, plus \$0.01 per input image when editing ([xAI model page](https://docs.x.ai/docs/models/grok-imagine-image-2.0), verified October 13, 2026). On LaoZhang API each of these is \$0.055, with no input charge for edits.

<Frame caption="Output of the generate example below: 2K, 16:9, medium">
  <img src="https://mintcdn.com/laozhangai-edd05f2c/YuJHjB7ivlJQODe0/images/samples/grok-generate.jpg?fit=max&auto=format&n=YuJHjB7ivlJQODe0&q=85&s=79f29d5f27a47afdbe81b006d15ddcf0" alt="A cinematic lighthouse at sunrise with ocean reflections, generated by Grok Imagine Image 2.0" width="1200" height="675" data-path="images/samples/grok-generate.jpg" />
</Frame>

### Parameters and limits

| Parameter | Values |
| - | - |
| References per edit | 1–3 |
| Resolution | `1k` or `2k` |
| Quality | `low` or `medium`, set explicitly |
| Aspect ratios | 15 fixed values; omit to let the model choose |
| Images per request | `n` from 1 to 10, billed per returned image |
| Response format | `url` or `b64_json` |

<Warning>
  Editing accepts OpenAI-compatible file uploads, not the JSON image objects shown in xAI's documentation. Requests with four or five references fail, so enforce the three-image limit in your client and don't retry an over-limit request.
</Warning>

## Choose a Grok Imagine model

| Model ID | Scope | Best for |
| - | - | - |
| `grok-imagine-image-2.0` | 1K/2K, `low`/`medium`, 15 fixed ratios, edits with 1–3 references | New integrations, detailed images, and reference composition |
| `grok-imagine-image` | Lower-cost generation with the earlier multi-reference scope | Drafts, batch candidates, and cost-sensitive work |
| `grok-imagine-image-quality` | Earlier quality model with a smaller reference limit | Existing integrations and small final-asset jobs |

The earlier models have their own prices: \$0.025 per image for `grok-imagine-image` and \$0.045 per image for `grok-imagine-image-quality`. Like 2.0, they are billed per successfully returned image.

* `grok-imagine-image`: unaffected by the upstream change, so existing workloads don't need to migrate right away. Before switching, compare one image from each model using the same prompt, ratio, and resolution.
* `grok-imagine-image-quality`: xAI retires this model on November 2, 2026, after which xAI serves its requests with `grok-imagine-image-2.0` at `low` quality ([xAI migration guide](https://docs.x.ai/developers/migration/imagine-image-quality-nov-2)). If you still use it, switch to 2.0 before then and set `quality` explicitly.

## Before you call the API

<Steps>
  <Step title="Create and protect an API key">
    Create a key in the `default` group in [Token management](https://api.laozhang.ai/token) and set **Billing mode** (计费模式) to **Usage first** (按量优先, recommended) or **Per-call** (按次计费). A Usage first key can call both per-call and usage-based models; a Per-call key calls only per-call models.

    Keep the key in a server-side environment variable, never in browser code, a public repository, or logs.
  </Step>

  <Step title="Confirm model access and price">
    In [Models and pricing](https://api.laozhang.ai/account/pricing), check that the key can use `grok-imagine-image-2.0` and review the current price.
  </Step>

  <Step title="Set up your environment">
    Export the key and install the OpenAI Python SDK, which the Python examples use:

    ```bash theme={null}
    export LAOZHANG_API_KEY="YOUR_LAOZHANG_API_KEY"
    python3 -m pip install openai
    ```
  </Step>

  <Step title="Start with one image">
    Use `n=1` first. Save the output, inspect its content and dimensions, and check the call record before you increase resolution, output count, or concurrency.
  </Step>
</Steps>

## Generate an image

This request creates one 2K, 16:9 image at `medium` quality and writes the response to `grok-generation.json`:

```bash theme={null}
curl --fail-with-body "https://api.laozhang.ai/v1/images/generations" \
  -H "Authorization: Bearer $LAOZHANG_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-image-2.0",
    "prompt": "A cinematic lighthouse at sunrise, detailed ocean reflections, no text",
    "n": 1,
    "aspect_ratio": "16:9",
    "resolution": "2k",
    "quality": "medium",
    "response_format": "url"
  }' \
  -o grok-generation.json
```

A successful response returns HTTP 200 with one item in `data`:

```json theme={null}
{
  "data": [
    {
      "url": "https://..."
    }
  ]
}
```

### Save the result

The URL is temporary, so download the image right away. Save this script as `save_images.py`. It writes every image in a response to disk, whether the response contains `url` or `b64_json`, and picks the file extension from the image data:

```python save_images.py theme={null}
import base64
import json
import sys
import urllib.request
from pathlib import Path

response_file, stem = sys.argv[1], sys.argv[2]
response = json.loads(Path(response_file).read_text())
if not response.get("data"):
    sys.exit(f"No image in {response_file}: {response}")

for number, item in enumerate(response["data"], start=1):
    if item.get("b64_json"):
        # Drop an optional data:image/...;base64, prefix and restore missing padding.
        value = item["b64_json"].split(",", 1)[-1]
        image = base64.b64decode(value + "=" * (-len(value) % 4))
    else:
        with urllib.request.urlopen(item["url"], timeout=120) as download:
            image = download.read()
    if image.startswith(b"\x89PNG"):
        extension = "png"
    elif image[:4] == b"RIFF" and image[8:12] == b"WEBP":
        extension = "webp"
    else:
        extension = "jpg"
    path = Path(f"{stem}-{number}.{extension}")
    path.write_bytes(image)
    print(f"Saved {path}")
```

```bash theme={null}
python3 save_images.py grok-generation.json grok-lighthouse
```

The script prints a line such as `Saved grok-lighthouse-1.jpg`. Open the file and check the subject, text, and composition. To receive the image bytes in the response instead of a URL, set `response_format` to `b64_json`; the same script handles both.

### Generate with the Python SDK

The OpenAI Python SDK doesn't expose every Grok image option as a named parameter, so pass `aspect_ratio`, `resolution`, and `quality` in `extra_body`. This example requests Base64 output and saves the decoded image:

```python theme={null}
import base64
import os
from pathlib import Path

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["LAOZHANG_API_KEY"],
    base_url="https://api.laozhang.ai/v1",
    timeout=180,
)

response = client.images.generate(
    model="grok-imagine-image-2.0",
    prompt="A premium mechanical watch on dark slate, macro product photography",
    n=1,
    response_format="b64_json",
    extra_body={
        "aspect_ratio": "1:1",
        "resolution": "2k",
        "quality": "medium",
    },
)

value = response.data[0].b64_json.split(",", 1)[-1]
image = base64.b64decode(value + "=" * (-len(value) % 4))
extension = "png" if image.startswith(b"\x89PNG") else "jpg"
output = Path(f"grok-watch.{extension}")
output.write_bytes(image)
print(f"Saved {output}")
```

## Aspect ratio, resolution, and quality

`grok-imagine-image-2.0` accepts these 15 fixed aspect ratios:

| Orientation | Values |
| - | - |
| Square | `1:1` |
| Landscape | `16:9`, `4:3`, `3:2`, `2:1`, `19.5:9`, `20:9`, `21:9`, `5:2` |
| Portrait | `9:16`, `3:4`, `2:3`, `1:2`, `9:19.5`, `9:20` |

Omit `aspect_ratio` to let the model choose, or pass a value when the layout must be predictable.

* `resolution="1k"` is faster and suits drafts, thumbnails, and batch candidates.
* `resolution="2k"` produces larger files with longer latency, for final assets and cropping.
* `quality="low"` favors speed; `quality="medium"` favors detail.
* Don't send `quality="high"` or `resolution="4k"`.

Responses don't report which quality tier was used. Set `quality` to `low` or `medium` explicitly rather than relying on `auto`, so latency and output quality stay predictable.

## Edit one reference image

Editing requires a file upload. Put a local `product-photo.png` in the current directory, then run:

```bash theme={null}
curl --fail-with-body "https://api.laozhang.ai/v1/images/edits" \
  -H "Authorization: Bearer $LAOZHANG_API_KEY" \
  -F "model=grok-imagine-image-2.0" \
  -F "prompt=Change the mug to matte black. Preserve the composition, lighting, and background." \
  -F "image=@product-photo.png" \
  -F "response_format=url" \
  -o grok-edit.json

python3 save_images.py grok-edit.json grok-edit
```

Reference editing regenerates the scene; it isn't pixel-level mask inpainting. Check the subject, color, text, and composition in the saved image.

## Edit with two or three references

Repeat the `image[]` field for each reference. This request supplies the subject, the scene, and the style as three separate files:

```bash theme={null}
curl --fail-with-body "https://api.laozhang.ai/v1/images/edits" \
  -H "Authorization: Bearer $LAOZHANG_API_KEY" \
  -F "model=grok-imagine-image-2.0" \
  -F "prompt=Place the product from image 1 in the scene from image 2, and apply the visual style from image 3. Preserve the product colors." \
  -F "image[]=@product.png" \
  -F "image[]=@scene.jpg" \
  -F "image[]=@style.jpg" \
  -F "aspect_ratio=3:2" \
  -F "response_format=url" \
  -o grok-multi-edit.json

python3 save_images.py grok-multi-edit.json grok-multi-edit
```

Upload order maps to image 1, image 2, and image 3 in the prompt. A successful request returns one image; with `aspect_ratio=3:2`, expect a landscape result such as 1248×832. Count the files before you send the request, because a fourth reference makes the whole request fail.

### Edit with the Python SDK

The OpenAI SDK works for single-image edits. This example returns a URL and downloads the image immediately:

```python theme={null}
import os
import urllib.request
from pathlib import Path

from openai import OpenAI

client = OpenAI(
    api_key=os.environ["LAOZHANG_API_KEY"],
    base_url="https://api.laozhang.ai/v1",
    timeout=180,
)

with open("product.png", "rb") as source:
    response = client.images.edit(
        model="grok-imagine-image-2.0",
        image=source,
        prompt="Keep the product and change the background to a rainy neon street.",
        response_format="url",
    )

with urllib.request.urlopen(response.data[0].url, timeout=120) as download:
    image = download.read()
extension = "png" if image.startswith(b"\x89PNG") else "jpg"
output = Path(f"grok-sdk-edit.{extension}")
output.write_bytes(image)
print(f"Saved {output}")
```

For multiple references, start with the cURL form above to confirm how your HTTP client serializes repeated multipart fields.

## Parameters

| Parameter | Type | Required | Behavior |
| - | - | - | - |
| `model` | string | Yes | `grok-imagine-image-2.0` |
| `prompt` | string | Yes | Content, composition, style, and details that must stay the same |
| `n` | integer | No | 1–10 text-to-image outputs; each returned image is billed |
| `aspect_ratio` | string | No | One of the 15 values above; omit to let the model choose |
| `resolution` | string | No | Lowercase `1k` or `2k` for text-to-image |
| `quality` | string | No | `low` or `medium`; don't send `high` |
| `response_format` | string | No | `url` or `b64_json` |
| `image` | file | For one-image edits | One local image |
| `image[]` | file | For multi-image edits | Repeat the field for up to three files |

## Pricing and billing

Billing counts the images a request actually returns:

| Request | Billed as |
| - | - |
| `n=1`, one image returned | 1 image |
| `n=4`, four images returned | 4 images |
| `n=10`, ten images returned | 10 images (\$0.55 at the current price) |
| Three-reference edit returning one image | 1 image |

LaoZhang API charges the same price for `1k` and `2k` and for `low` and `medium`. xAI prices by resolution and quality; the comparison is in the price note at the top of this page.

Check the [console](https://api.laozhang.ai/account/pricing) before a large batch, and treat call records as the final billing source.

## Error handling

| Condition | Possible result | What to do |
| - | - | - |
| Invalid API key | 401 | Replace the key; don't retry with the same credential |
| Missing `prompt` | 400 | Fix the request |
| `n` above 10 | May return 429 | Validate `n` locally as 1–10 |
| Unsupported aspect ratio | May return 429 | Use the values listed above |
| `resolution="4k"` | May return 503 | Use `1k` or `2k`; this isn't a temporary outage |
| `quality="high"` | May still return an image | Reject it locally to avoid a silent fallback and charge |
| Four or five references | 500 | Reduce to three; don't retry the same request |

Retry valid requests that hit 429, network errors, or clearly temporary 5xx errors with jittered exponential backoff. After a client timeout, check the call record before you resubmit, so you don't generate and pay for the same image twice.

## Before you go to production

1. Generate one `1k`, `low` image with the production key.
2. Save the result and check its real format and dimensions.
3. Test the exact resolution, quality, aspect ratio, and `n` values you plan to use.
4. For edits, use distinct, non-sensitive references and confirm that each one affects the output.
5. Enforce the three-reference limit in your client.
6. Set a timeout of at least 60 seconds for `1k` `low` requests and 120–180 seconds for `medium` or `2k`.
7. Reconcile success rate, latency, output count, and call records before raising concurrency.

## Frequently asked questions

### Can I call Grok Imagine without an xAI account?

Yes. You need only a LaoZhang API key, not an xAI account. Generation and editing both use the OpenAI-compatible Images endpoints, billed per successfully returned image.

### What is the exact model ID?

Use `grok-imagine-image-2.0`, including the final `.0`. `grok-imagine-image` and `grok-imagine-image-quality` are separate, earlier models.

### Am I billed per image? Do resolution and quality change the price?

Per successfully returned image. `1k`, `2k`, `low`, and `medium` currently share one per-image price; see [Pricing and billing](#pricing-and-billing) for examples. Latency differs by tier, so plan timeouts accordingly: on October 14, 2026 the quick-start prompt took 16 s at 1K low and 71 s at 2K medium, and each call was logged at \$0.055.

<Columns cols={2}>
  <Frame caption="1K, low, 16:9: 16 s, $0.055">
    <img src="https://mintcdn.com/laozhangai-edd05f2c/20UJZ-8MviaLAz5r/images/samples/grok-1k-low.jpg?fit=max&auto=format&n=20UJZ-8MviaLAz5r&q=85&s=f83ade14ebc124ee23ec1b56e1ab2ac3" alt="Lighthouse on a rocky coast at sunrise with sunlight reflecting on the sea, generated by Grok Imagine Image 2.0 at 1K low" width="1200" height="675" data-path="images/samples/grok-1k-low.jpg" />
  </Frame>

  <Frame caption="2K, medium, 16:9: 71 s, $0.055">
    <img src="https://mintcdn.com/laozhangai-edd05f2c/20UJZ-8MviaLAz5r/images/samples/grok-2k-medium.jpg?fit=max&auto=format&n=20UJZ-8MviaLAz5r&q=85&s=0911bebb8edf5ac6b2e8ac61deba42b3" alt="Lighthouse on a rocky coast at sunrise with detailed clouds and waves, generated by Grok Imagine Image 2.0 at 2K medium" width="1200" height="675" data-path="images/samples/grok-2k-medium.jpg" />
  </Frame>
</Columns>

A request that returns a non-200 error and no image isn't billed per image. A client timeout isn't the same as a failure, though: the server may have finished and charged for the image, so check the call record before you resend. Call records are the final billing source.

### Can I edit with xAI's JSON format or send four or five references?

No to both. Editing accepts only multipart file uploads, with up to three references, as the table at the top of this page shows. xAI's JSON image objects return HTTP 400.

xAI's documentation says the OpenAI SDK's `images.edit()` doesn't work for Grok editing; that applies to xAI's own JSON-only API.

On LaoZhang API, `images.edit()` works for single-image edits, as shown in [Edit with the Python SDK](#edit-with-the-python-sdk). For several references, start with the cURL `image[]` form.

### What aspect ratio does an edit return?

According to xAI, an edit without `aspect_ratio` follows the first reference image's aspect ratio. To fix the frame, add `aspect_ratio` to the edit request; the three-reference example uses `aspect_ratio=3:2` and returns a 1248×832 image.

### Can I keep editing the previous result?

Yes. Download the previous result, upload it as the `image`, and describe only this round's change in the prompt, such as "Keep everything the same and add a gold border." Each round is a new edit request, billed for the images it returns.

### How should I store generated images?

Download URL results promptly into your own storage; xAI also describes the returned URLs as temporary. Use `b64_json` when the image must arrive inside the API response.

## Sources and related documentation

* [Grok Imagine Image 2.0 launch announcement](/en/announcements/grok-imagine-image-2-0-2026-09): availability and the three-reference editing scope
* [xAI Grok Imagine Image 2.0 model](https://docs.x.ai/developers/models/grok-imagine-image-2.0): official model ID and upstream pricing by resolution and quality
* [xAI image generation](https://docs.x.ai/developers/model-capabilities/images/generation): official ratios, resolution, quality, batching, and response formats
* [xAI image editing](https://docs.x.ai/developers/model-capabilities/images/editing): the upstream JSON editing format, which differs from LaoZhang API's multipart interface
* [xAI multi-image editing](https://docs.x.ai/developers/model-capabilities/images/multi-image-editing): how to write multi-image edit prompts; LaoZhang API accepts up to three references per edit
* [Images API reference](/en/api-reference/images): shared request and response structure
* [Choose an image generation API](/en/api-capabilities/image-generation-guide): compare Grok Imagine with other image models
* [Models and pricing in the console](https://api.laozhang.ai/account/pricing): models, groups, prices, and call records for your account


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.