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

# Generate images with the AI Gateway

> Generate and edit images from your backend functions through the AI Gateway's OpenAI-compatible image endpoints.

The [AI Gateway](/developers/references/sdk/docs/interfaces/ai-gateway) serves OpenAI-compatible image endpoints, so your app can generate images from a prompt or edit them using reference images, with control over the model, aspect ratio, resolution, and quality. Requests are billed to your app's credits, with no separate provider account or API key.

<Tip>
  **Before you begin:** Call the gateway from a [backend function](/developers/backend/resources/backend-functions/overview) rather than the browser, so you can check who's calling and control usage before a request is billed to your app. Get the `baseURL` and `token` from [`base44.aiGateway.connection()`](/developers/references/sdk/docs/interfaces/ai-gateway#connection).
</Tip>

For a quick image from a prompt with no extra options, [`Core.GenerateImage`](/developers/references/sdk/docs/type-aliases/integrations#generateimage) is simpler and also accepts reference images.

## Endpoints

| Endpoint                            | Description                                                      |
| ----------------------------------- | ---------------------------------------------------------------- |
| `POST {baseURL}/images/generations` | Generates images from a prompt. Also accepts reference images.   |
| `POST {baseURL}/images/edits`       | Generates images from a prompt and at least one reference image. |

Both endpoints accept JSON or `multipart/form-data` and follow OpenAI's request and response format, with a few Base44 fields added. Authenticate with `Authorization: Bearer {token}`.

## Generate an image

With the Vercel AI SDK, create an OpenAI-compatible provider from the connection details and call `generateImage()`. Pass Base44 fields such as `aspect_ratio` and `resolution` under `providerOptions`, keyed by the provider name you chose.

```typescript Generate an image with the Vercel AI SDK theme={null}
import { createClientFromRequest } from "npm:@base44/sdk";
import { generateImage } from "npm:ai";
import { createOpenAICompatible } from "npm:@ai-sdk/openai-compatible";

export default async function (req: Request): Promise<Response> {
  const base44 = createClientFromRequest(req);
  const user = await base44.auth.me();
  if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });

  const { baseURL, token } = base44.aiGateway.connection();
  const gateway = createOpenAICompatible({ name: "base44", baseURL, apiKey: token });

  const { image } = await generateImage({
    model: gateway.imageModel("automatic"),
    prompt: "A watercolor illustration of a lighthouse at dawn",
    providerOptions: {
      base44: { aspect_ratio: "16:9", resolution: "2K" },
    },
  });

  const file = new File([image.uint8Array], "lighthouse.png", { type: image.mediaType });
  const { file_url } = await base44.integrations.Core.UploadFile({ file });

  return Response.json({ url: file_url });
}
```

The Vercel AI SDK's own `aspectRatio` option isn't sent to the gateway. Use `aspect_ratio` in `providerOptions`, or `size` with exact pixel dimensions.

To call the endpoint without a client library, send the request with `fetch()`. Setting `response_format` to `url` returns a link to a stored image instead of base64 data:

```typescript Generate an image with fetch theme={null}
const { baseURL, token } = base44.aiGateway.connection();

const response = await fetch(`${baseURL}/images/generations`, {
  method: "POST",
  headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
  body: JSON.stringify({
    model: "automatic",
    prompt: "A watercolor illustration of a lighthouse at dawn",
    aspect_ratio: "16:9",
    response_format: "url",
  }),
});

const { data } = await response.json();
console.log(data[0].url);
```

## Use reference images

Reference images let you edit an existing image, keep a character or product consistent, or match a style. Describe in the prompt what to do with them.

With the Vercel AI SDK, pass the images in the prompt. The SDK downloads each URL and uploads the image data to `/images/edits`, so each URL must be reachable from your backend function:

```typescript Edit an image with the Vercel AI SDK theme={null}
const { image } = await generateImage({
  model: gateway.imageModel("automatic"),
  prompt: {
    text: "Place this product on a marble kitchen counter in soft morning light",
    images: [productPhotoUrl],
  },
});
```

To have the gateway fetch the images itself, pass their URLs in `reference_image_urls` instead. This also works for private files that your app owns:

```typescript Pass reference image URLs theme={null}
const { image } = await generateImage({
  model: gateway.imageModel("automatic"),
  prompt: "Place this product on a marble kitchen counter in soft morning light",
  providerOptions: {
    base44: { reference_image_urls: [productPhotoUrl, styleReferenceUrl] },
  },
});
```

Reference images can be JPEG, PNG, WebP, GIF, BMP, TIFF, or HEIC files, passed as `https://` URLs, `data:image/...` URIs, or file uploads. FLUX, GPT Image 2.5, Grok, and Seedream models accept only JPEG, PNG, and WebP. You can pass up to 10 reference images per request, and some models accept fewer. See [Models](#models) and [Limits](#limits).

## Models

Set `model` to `automatic` or leave it out to let Base44 choose, or pin one of these model IDs. Image models are separate from the [chat models](/developers/references/sdk/docs/interfaces/ai-gateway#openai-compatible-models) the gateway uses for text.

| Model ID                      | Provider          | Reference images | Resolutions        | Quality                                         |
| ----------------------------- | ----------------- | ---------------- | ------------------ | ----------------------------------------------- |
| `gemini_3_1_flash_lite_image` | Google            | Up to 10         | `1K`               | Not supported                                   |
| `gemini_3_1_flash_image`      | Google            | Up to 10         | `1K`, `2K`, `4K`   | Not supported                                   |
| `gemini_2_5_flash_image`      | Google            | Up to 10         | `1K`               | Not supported                                   |
| `gpt_image_1`                 | OpenAI            | Not supported    | `1K`               | `auto`, `low`, `medium`, `high`                 |
| `gpt_image_2`                 | OpenAI            | Up to 10         | `1K`, `2K`         | `auto`, `low`, `medium`, `high`                 |
| `gpt_image_2_5_flare`         | OpenAI            | Up to 10         | `1K`, `2K`         | `auto`, `low`, `medium`, `high`, `xhigh`, `max` |
| `gpt_image_2_5_sunburst`      | OpenAI            | Up to 10         | `1K`, `2K`         | `auto`, `low`, `medium`, `high`, `xhigh`, `max` |
| `flux_2_pro`                  | Black Forest Labs | Up to 8          | `1K`, `2K`         | Not supported                                   |
| `flux_2_flex`                 | Black Forest Labs | Up to 8          | `1K`, `2K`         | Not supported                                   |
| `flux_2_max`                  | Black Forest Labs | Up to 8          | `1K`, `2K`         | Not supported                                   |
| `grok_imagine_image_2`        | xAI               | Up to 5          | `1K`, `2K`         | `auto`, `low`, `medium`                         |
| `seedream_5_0_lite`           | ByteDance         | Up to 10         | `2K`, `3K`, `4K`   | `auto`                                          |
| `seedream_5_0_pro`            | ByteDance         | Up to 10         | `1K`, `1.5K`, `2K` | `auto`                                          |

A pinned model is never swapped for another one. If the model doesn't support an option you set, the request fails with an error that names the option.

<AccordionGroup>
  <Accordion title="Supported aspect ratios">
    | Models                                                                      | Aspect ratios                                                                                                              |
    | --------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
    | `gemini_3_1_flash_lite_image`                                               | `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`, `1:4`, `4:1`, `1:8`, `8:1`                        |
    | `gemini_3_1_flash_image`                                                    | Same as Gemini 3.1 Flash Lite, plus `9:21`                                                                                 |
    | `gemini_2_5_flash_image`                                                    | `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9`                                                    |
    | `gpt_image_1`                                                               | `1:1`, `3:2`, `2:3`                                                                                                        |
    | `gpt_image_2`, `gpt_image_2_5_flare`, `gpt_image_2_5_sunburst`, FLUX models | `1:1`, `3:2`, `2:3`, `4:3`, `3:4`, `16:9`, `9:16`                                                                          |
    | `grok_imagine_image_2`                                                      | `auto`, `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`, `2:1`, `1:2`, `19.5:9`, `9:19.5`, `20:9`, `9:20`, `21:9`, `5:2` |
    | Seedream models                                                             | `auto`, `1:1`, `4:3`, `3:4`, `16:9`, `9:16`, `3:2`, `2:3`, `21:9`, `9:21`, `4:5`, `5:4`, `2:1`, `1:2`                      |
  </Accordion>

  <Accordion title="Supported output formats and backgrounds">
    * **GPT Image models:** `output_format` can be `png` (default), `jpeg`, or `webp`. `background` can be `auto`, `opaque`, or `transparent`.
    * **FLUX models:** `output_format` can be `jpeg` (default), `png`, or `webp`.
    * **Seedream models:** `output_format` can be `jpeg` or `png`.
    * **Gemini and Grok models:** Return the provider's native format. `output_format` and `background` aren't supported.
  </Accordion>
</AccordionGroup>

### How automatic chooses a model

`automatic` picks the first model in this order that supports everything in your request, including the resolution, aspect ratio, reference images, and any `quality`, `output_format`, or `background` you set:

1. Gemini 3.1 Flash Lite
2. Gemini 3.1 Flash
3. Gemini 2.5 Flash
4. GPT Image 1
5. GPT Image 2
6. GPT Image 2.5 Flare
7. GPT Image 2.5 Sunburst

A plain request runs on Gemini 3.1 Flash Lite. Asking for `2K` or `4K` resolution, or a `9:21` aspect ratio, moves it to Gemini 3.1 Flash. FLUX, Grok, and Seedream models are never chosen automatically, so pin them by ID to use them.

<Warning>
  Gemini models don't support `quality`, `output_format`, or `background`. Setting any of them with `automatic`, even `quality: "auto"`, skips the Gemini models and runs the request on a GPT Image model, which changes the result and the cost. Leave these fields out unless you need them.
</Warning>

### Quality

`quality` trades cost for detail, from `low` up to `high`, with `xhigh` and `max` available only on GPT Image 2.5 models. On GPT Image models, `auto` and an omitted `quality` both use `low`. Gemini and FLUX models don't support `quality`.

## Request parameters

| Parameter              | Type       | Description                                                                                                                                                                                                |
| ---------------------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `prompt`               | `string`   | Required. What to generate, or what to do with the reference images.                                                                                                                                       |
| `model`                | `string`   | Model ID from [Models](#models). Defaults to `automatic`.                                                                                                                                                  |
| `n`                    | `integer`  | Number of images to generate, from 1 to 4. Seedream models generate up to 2. Defaults to `1`.                                                                                                              |
| `aspect_ratio`         | `string`   | Base44 field. Aspect ratio of the image, such as `16:9`. Can't be combined with `size`.                                                                                                                    |
| `resolution`           | `string`   | Base44 field. `1K`, `1.5K`, `2K`, `3K`, or `4K`, depending on the model. Values are case-sensitive. Can't be combined with `size`.                                                                         |
| `size`                 | `string`   | Exact dimensions as `WIDTHxHEIGHT`, such as `1536x1024`, or `auto`. Gemini models and GPT Image 1 accept `1024x1024`, `1536x1024`, and `1024x1536`. Can't be combined with `aspect_ratio` or `resolution`. |
| `quality`              | `string`   | `auto`, `low`, `medium`, `high`, `xhigh`, or `max`, depending on the model.                                                                                                                                |
| `output_format`        | `string`   | `png`, `jpeg`, or `webp`, depending on the model. `jpg` isn't accepted.                                                                                                                                    |
| `background`           | `string`   | `auto`, `opaque`, or `transparent`. GPT Image models only. Transparent backgrounds need `png` or `webp` output.                                                                                            |
| `response_format`      | `string`   | `b64_json` or `url`. Defaults to `b64_json`.                                                                                                                                                               |
| `reference_image_urls` | `string[]` | Base44 field. URLs of reference images for the gateway to fetch.                                                                                                                                           |
| `image`                | file       | Reference image files, sent as `image` or `image[]` parts of a multipart request.                                                                                                                          |
| `dry_run`              | `boolean`  | Base44 field. Returns the model that would run and its cost without generating an image. See [Estimate the cost](#estimate-the-cost).                                                                      |

The gateway rejects requests that set `mask`, `style`, `output_compression`, `moderation`, `partial_images`, or `stream`. Other fields that aren't listed here are ignored.

## Response

```json theme={null}
{
  "created": 1790000000,
  "data": [{ "b64_json": "iVBORw0KGgo..." }],
  "usage": { "base44_credits": 7 }
}
```

Each item in `data` has either `b64_json` with the image data, or `url` when you set `response_format` to `url`. URLs point to a file stored in your app's public file storage. The Vercel AI SDK always requests `b64_json` and returns each image as a `GeneratedFile` with `base64`, `uint8Array`, and `mediaType`.

When you ask for more than one image, the gateway generates them in parallel. If some fail, `data` contains only the images that succeeded, and you're billed only for those.

## Estimate the cost

Set `dry_run` to `true` to see which model a request would run on and what it would cost, without generating an image or using credits:

```typescript Estimate the cost of a request theme={null}
const response = await fetch(`${baseURL}/images/generations`, {
  method: "POST",
  headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
  body: JSON.stringify({ model: "automatic", prompt, resolution: "4K", dry_run: true }),
});

const { model, usage } = await response.json();
// { dry_run: true, model: "gemini_3_1_flash_image", usage: { base44_credits: ... } }
```

Image requests use your app's credits, the same shared quota as the rest of the [AI Gateway](/developers/references/sdk/docs/interfaces/ai-gateway#billing-and-limits). The cost of each image depends on the model, resolution, quality, and number of reference images. If a request produces no images, it's still billed a minimum charge.

## Limits

| Limit                          | Value                                                       |
| ------------------------------ | ----------------------------------------------------------- |
| Images per request (`n`)       | 4, or 2 for Seedream models                                 |
| Reference images per request   | 10, or fewer for some [models](#models)                     |
| Size of each reference image   | 20 MB                                                       |
| Total size of reference images | 48 MB per request                                           |
| Request body                   | 50 MB                                                       |
| Requests                       | 200 per minute per app, shared with all AI Gateway requests |

The gateway needs a `Content-Length` header on every request, and rejects chunked uploads. `fetch()` and the Vercel AI SDK set it for you.

<Note>
  The Vercel AI SDK sends up to 10 images in one call. To generate more than 4 images with one `generateImage()` call, set `maxImagesPerCall: 4` (or `2` for Seedream) so the SDK splits them into several requests.
</Note>

## Errors

Errors use OpenAI's format, `{ "error": { "message", "type", "code", "param" } }`, so client libraries report them like any other OpenAI error.

| Status | Cause                                                                                                                                                                                                                            |
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400`  | An invalid or unsupported option, too many or unreadable reference images, a request with no reference image sent to `/images/edits`, or a prompt the model refused. The message names the problem, and `param` names the field. |
| `402`  | Your app is out of credits.                                                                                                                                                                                                      |
| `404`  | The model ID doesn't exist.                                                                                                                                                                                                      |
| `411`  | The request has no `Content-Length` header.                                                                                                                                                                                      |
| `413`  | The request body is larger than 50 MB.                                                                                                                                                                                           |
| `429`  | Your app or the model provider is rate limiting requests. Retry after a short wait.                                                                                                                                              |
| `502`  | The model provider failed to generate the image.                                                                                                                                                                                 |

## See also

* [ai-gateway](/developers/references/sdk/docs/interfaces/ai-gateway): Get connection details and use chat models through the gateway.
* [GenerateImage](/developers/references/sdk/docs/type-aliases/integrations#generateimage): Generate an image with one SDK call.
* [Backend functions](/developers/backend/resources/backend-functions/overview): Write the server-side code that calls the gateway.
