# Google: Nano Banana 2 Image To Image

> Google Nano Banana 2 (Gemini 3.1 Flash Image) makes quick, instruction-based image edits for retouching, background swaps and product variants. Work from up to 10 reference images, preview at 0.5K before exporting at 4K, and add web search or high thinking for harder requests.

- **Vendor**: Google
- **Series**: Nano Banana
- **Model / version**: 2

## Overview

- **Endpoint**: `POST https://api.musespan.com/v1/model-tasks`
- **Model ID**: `google/nano-banana-2/image-to-image`
- **Category**: `image-to-image`
- **Execution**: asynchronous task. Submit it, poll its status, then download the declared result files.

## Pricing

Price: $0.08 per image at default settings. Billed by the number of images actually generated. The price shown is for default settings; other settings can change the price and are billed at actual usage.
Each request temporarily reserves $0.08; you are charged for actual usage, usually within a minute: any unused amount is released and any usage above it is charged to your balance, even if that takes it below zero; while your balance is below zero, new requests are paused until a top-up covers it.
Failed generations are not charged.

## How to call

Authenticate with `Authorization: Bearer <API_KEY>` and send JSON. Model parameters belong inside input; do not flatten them beside model. Maximum request body: 4 MiB.

- Model: google/nano-banana-2/image-to-image
- POST /v1/model-tasks with {"model":"google/nano-banana-2/image-to-image","input":{...}}.
- X-Request-Id is required (1-128 letters, digits, _ or -; a UUID is recommended). The task ID equals the X-Request-Id.
- Submission is idempotent: if the POST times out, the connection fails, or it returns 429 or 5xx, resend the byte-identical body with the same X-Request-Id. It returns the existing task and is never charged twice. A different body with the same ID returns 409 request_id_conflict.
- Poll GET /v1/model-tasks/{id} every 5 seconds with a total deadline; queued and running are pending, and only status=completed includes output. Null or empty output can be successful. If it returns 404 task_not_found, the POST never arrived: resend it with the same X-Request-Id instead of polling.
- Declared file URLs are authenticated downloads. Preserve the API authorization header when downloading files.
- Task status and file downloads require the API key that submitted the task.

## Input parameters (inside `input`)

- `prompt` (`string`, required):
  The prompt for image editing.
  - Length: 3..50000
  - Example: `"make a photo of the man driving the car down the california coastline"`
- `aspect_ratio` (`string or null`, optional):
  The aspect ratio of the generated image. Supports extreme ratios: 4:1, 1:4, 8:1, 1:8.
  - Default: `"auto"`
  - Options: `auto`, `21:9`, `16:9`, `3:2`, `4:3`, `5:4`, `1:1`, `4:5`, `3:4`, `2:3`, `9:16`, `4:1`, `1:4`, `8:1`, `1:8`
- `enable_web_search` (`boolean`, optional):
  Enable web search for the image generation task. This will allow the model to use the latest information from the web to generate the image.
  - Default: `false`
- `image_urls` (`list<string>`, optional):
  The URLs of the images to use for image-to-image generation or image editing. Optional when at least one of `video_url`, `audio_url`, or `pdf_url` is provided.
  - Items: 0..10
- `num_images` (`integer`, optional):
  The number of images to generate.
  - Default: `1`
  - Range: 1..4
- `output_format` (`string`, optional):
  The format of the generated image.
  - Default: `"png"`
  - Options: `jpeg`, `png`, `webp`
- `resolution` (`string`, optional):
  The resolution of the image to generate.
  - Default: `"1K"`
  - Options: `0.5K`, `1K`, `2K`, `4K`
- `seed` (`integer or null`, optional):
  The seed for the random number generator.
- `system_prompt` (`string`, optional):
  Optional system instruction that steers the model's persona and output style across the request. Leave blank to omit; when provided, it is sent as the system instruction to Gemini (or as a system message on OpenAI-compatible providers).
  - Default: `""`
  - Length: 0..50000
- `thinking_level` (`string or null`, optional):
  When set, enables model thinking with the given level ('minimal' or 'high') and includes thoughts in the generation. Omit to disable.
  - Options: `minimal`, `high`

Do not send these platform-controlled fields: `audio_url`, `limit_generations`, `pdf_url`, `safety_tolerance`, `sync_mode`, `video_url`. Requests that include them fail validation.

## Request example

```json
{
  "model": "google/nano-banana-2/image-to-image",
  "input": {
    "prompt": "Turn the scene into a snowy winter evening: snow on the roof and planters, warm glowing lights inside the greenhouse; keep the isometric clay style and composition.",
    "aspect_ratio": "auto",
    "enable_web_search": false,
    "num_images": 1,
    "output_format": "png",
    "resolution": "1K",
    "system_prompt": "",
    "image_urls": [
      "https://pub-a7287c8d5de944d984e22a5bd3ab9bbe.r2.dev/uploads/capability-demo-a2e4c7ff2c095892fd69923b56f5d3a8.png"
    ]
  }
}
```

## Results

POST returns HTTP 202 with `{id, model, status}`. `queued` and `running` are pending; `completed` includes `output`; `failed` includes `error.code`.

Tasks beyond the number your account (or the platform) may run at once wait in our queue instead of being refused: they stay `queued` with an estimated `queue_position` (1 = next), which can change. Your own tasks wait in order while your account is at its limit.

A task still waiting in the queue (status queued with queue_position) can be cancelled with POST /v1/model-tasks/{id}/cancel and the same API key: it ends as failed with error.code cancelled and its hold is refunded in full. A task no longer waiting in the queue (being sent, sent, or ended) cannot be cancelled (409 task_not_cancellable).

Task objects may gain fields in later versions: ignore fields you do not know.

Completed task (example):

```json
{
  "id": "task_example",
  "model": "google/nano-banana-2/image-to-image",
  "status": "completed",
  "output": {
    "images": [
      {
        "url": "https://api.musespan.com/v1/model-tasks/task_example/artifacts/0"
      }
    ]
  }
}
```

Output schema (`output` of a completed task; same contract as OpenAPI):

```json
{
  "$ref": "#/components/schemas/NanoBanana2EditOutput",
  "components": {
    "schemas": {
      "ImageFile": {
        "properties": {
          "content_type": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "description": "The mime type of the file.",
            "examples": [
              "image/png"
            ],
            "title": "Content Type"
          },
          "file_name": {
            "anyOf": [
              {
                "type": "string"
              },
              {
                "type": "null"
              }
            ],
            "description": "The name of the file. It will be auto-generated if not provided.",
            "examples": [
              "z9RV14K95DvU.png"
            ],
            "title": "File Name"
          },
          "file_size": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "description": "The size of the file in bytes.",
            "examples": [
              4404019
            ],
            "title": "File Size"
          },
          "height": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "description": "The height of the image",
            "title": "Height"
          },
          "url": {
            "description": "The URL where the file can be downloaded from.",
            "title": "Url",
            "type": "string"
          },
          "width": {
            "anyOf": [
              {
                "type": "integer"
              },
              {
                "type": "null"
              }
            ],
            "description": "The width of the image",
            "title": "Width"
          }
        },
        "required": [
          "url"
        ],
        "title": "ImageFile",
        "type": "object"
      },
      "NanoBanana2EditOutput": {
        "properties": {
          "description": {
            "description": "The description of the generated images.",
            "title": "Description",
            "type": "string"
          },
          "images": {
            "description": "The edited images.",
            "items": {
              "$ref": "#/components/schemas/ImageFile"
            },
            "title": "Images",
            "type": "array"
          }
        },
        "required": [
          "images",
          "description"
        ],
        "title": "NanoBanana2ImageToImageOutput",
        "type": "object"
      }
    }
  }
}
```

Result files: the URLs at `images[].url` point to `GET https://api.musespan.com/v1/model-tasks/{id}/artifacts/{index}`. Download them with the same `Authorization` header (the API key that submitted the task) and never send the key to any other host. Files are served as `application/octet-stream`; never execute SVG or HTML result bytes. Keep the files you need.

## Errors

### Submit (POST)

- `400`: Invalid request: missing or malformed X-Request-Id, or input that does not match the model schema. Nothing was created. native_model_unavailable: this model is served on a different endpoint; read its openapi_url in GET /v1/models, and use an ID from suggested_models there.
- `401`: Missing or invalid API key.
- `402`: Insufficient balance. Nothing was created; top up and resend with the same X-Request-Id.
- `403`: This API key cannot use this model.
- `404`: model_not_found: this ID cannot be called with this API key. Nothing was created. Do not resend it unchanged: use an ID from suggested_models or an id from GET /v1/models.
- `409`: request_id_conflict: this X-Request-Id was used with a different request body (another spelling of the model ID also counts as a different body). Resend byte-identical bytes, or use a new X-Request-Id.
- `429`: Too many requests, or too many of your tasks already waiting in the queue (too_many_active_tasks). Tasks beyond the number your account may run at once wait in the queue instead of being refused; this means the queue itself is full. Back off a moment, then resend with the same X-Request-Id.
- `503`: Temporarily unavailable. Retry later with the same X-Request-Id.

### Query (GET /v1/model-tasks/{id})

- `401`: Missing or invalid API key.
- `404`: task_not_found: no task with this ID exists for this API key. If the POST may not have arrived, resend the exact same body with the same X-Request-Id instead of polling.
- `429`: Too many requests. Back off, then query the same task again.
- `503`: Temporarily unavailable. Query the same task again later.

### Cancel (POST /v1/model-tasks/{id}/cancel)

- `401`: Missing or invalid API key.
- `404`: task_not_found: no task with this ID exists for this API key.
- `409`: task_not_cancellable: the task is no longer waiting in the queue (being sent, sent, or ended). The body includes its current status; keep polling it.
- `429`: Too many requests. Back off, then try again.
- `503`: Temporarily unavailable. Try again later.

### Download (GET /v1/model-tasks/{id}/artifacts/{index})

- `401`: Missing or invalid API key.
- `404`: artifact_not_found: the task is not completed yet, the index is not one the completed task declares, or the task was submitted with another API key. Poll GET /v1/model-tasks/{id} until status is completed, then download only the indexes its output declares, with the API key that submitted the task.
- `429`: Too many requests or downloads at once. Back off, then download the same file again.
- `503`: Temporarily unavailable. Download the same file again later.

Task failures (HTTP 200 with `status` `failed`): read `error.code` and keep a branch for unknown codes. A failed task is final and not charged.

- `generation_timeout`: A model task may first wait in our queue (status queued, with an estimated queue_position) while the account or the platform is at its limit of tasks running at once; one still waiting 5 minutes after it was submitted ends as failed with error.code queue_timeout and is not charged. Once sent, a task with no result 15 minutes after it was accepted, or whose submission is still not confirmed 15 minutes after it was sent, ends as failed with error.code generation_timeout and is not charged (any hold is refunded in full); poll for up to 25 minutes to see the final status. To try again, submit a new task with a new X-Request-Id: the old ID keeps returning the failed task.
- `upstream_unavailable`: A task that could not be started because generation is temporarily unavailable ends at once as failed with error.code upstream_unavailable and is not charged (any hold is refunded in full); it does not mean your input was wrong. Try again later with a new X-Request-Id: the old ID keeps returning the failed task.
- `cancelled`: You cancelled the task (POST /v1/model-tasks/{id}/cancel) while it was waiting in the queue. It was never sent and is not charged; the hold is refunded in full.
- `queue_timeout`: The task waited in the queue for 5 minutes without being sent. It is not charged; submit it again with a new X-Request-Id.
- `model_unavailable_while_queued`: The model became unavailable while the task waited in the queue, so it was not started and is not charged. Submit it again with a new X-Request-Id; resending the old ID only returns this failure.
- `insufficient_balance`: Your balance went below zero while the task waited in the queue (another charge exceeded its hold), so it was not started and is not charged. Top up, then submit it again with a new X-Request-Id.
- `invalid_parameters`: A task whose input was rejected ends as failed with error.code invalid_parameters and is not charged (any hold is refunded in full). error.issues lists up to 8 entries {field, rule}: field is the input path (for example voice, voice_setting.voice_id or image_urls[0]) and rule is one of required, string, integer, number, boolean, array, object, allowed_value, range, length, multiple, invalid, unsupported_value, file_size, file_format, file_unreadable, duration, content_policy. Free-form error text is never returned. Fix those fields, then submit a new task with a new X-Request-Id: the old ID keeps returning the failed task.

## Usage Examples

Runtime: Node.js 20+ (native fetch / AbortSignal.timeout), or Python 3 with `pip install requests`.

Keep API keys on the server. The examples below save a request ID and resume querying when rerun.

### cURL

```bash
# Use a new directory for each new generation. Rerunning here continues this task.
set -eu
test -s model-task-id.txt || python3 -c "import uuid; print(uuid.uuid4())" > model-task-id.txt
REQUEST_ID=$(cat model-task-id.txt)
# Idempotent: resending the same bytes with the same ID never charges twice.
curl --fail-with-body --retry 3 --retry-connrefused --request POST 'https://api.musespan.com/v1/model-tasks' \
  --header "Authorization: Bearer $MUSESPAN_API_KEY" \
  --header "X-Request-Id: $REQUEST_ID" \
  --header "Content-Type: application/json" \
  --data '{"model":"google/nano-banana-2/image-to-image","input":{"prompt":"Turn the scene into a snowy winter evening: snow on the roof and planters, warm glowing lights inside the greenhouse; keep the isometric clay style and composition.","aspect_ratio":"auto","enable_web_search":false,"num_images":1,"output_format":"png","resolution":"1K","system_prompt":"","image_urls":["https://pub-a7287c8d5de944d984e22a5bd3ab9bbe.r2.dev/uploads/capability-demo-a2e4c7ff2c095892fd69923b56f5d3a8.png"]}}'
# Poll every 5 seconds for up to 25 minutes until status is completed or failed.
# Still queued (with queue_position) 5 minutes after submission: failed with queue_timeout, not charged.
# No result 15 minutes after acceptance (or no confirmation 15 minutes after submission): failed with generation_timeout, not charged.
# Any failure is final: generate again in a new directory (a new X-Request-Id).
# A 404 means the POST did not arrive: rerun this script to resend it with the same ID.
curl --fail-with-body 'https://api.musespan.com/v1/model-tasks/'"$REQUEST_ID"'' --header "Authorization: Bearer $MUSESPAN_API_KEY"
# When status is completed, download the first declared file with the same key.
curl --fail-with-body --output result-0 'https://api.musespan.com/v1/model-tasks/'"$REQUEST_ID"'/artifacts/0' --header "Authorization: Bearer $MUSESPAN_API_KEY"
```

### Complete async JavaScript

```javascript
import { readFile, writeFile } from 'node:fs/promises';
// Use a separate working directory for each new generation. Rerunning here continues this task.
let requestId;
try {
  requestId = (await readFile('model-task-id.txt', 'utf8')).trim();
} catch (error) {
  if (error.code !== 'ENOENT') throw error;
  requestId = crypto.randomUUID();
  await writeFile('model-task-id.txt', requestId);
}
const headers = { Authorization: `Bearer ${process.env.MUSESPAN_API_KEY}` };
// Keep the body as fixed bytes: a resend must be byte-identical.
const body = "{\"model\":\"google/nano-banana-2/image-to-image\",\"input\":{\"prompt\":\"Turn the scene into a snowy winter evening: snow on the roof and planters, warm glowing lights inside the greenhouse; keep the isometric clay style and composition.\",\"aspect_ratio\":\"auto\",\"enable_web_search\":false,\"num_images\":1,\"output_format\":\"png\",\"resolution\":\"1K\",\"system_prompt\":\"\",\"image_urls\":[\"https://pub-a7287c8d5de944d984e22a5bd3ab9bbe.r2.dev/uploads/capability-demo-a2e4c7ff2c095892fd69923b56f5d3a8.png\"]}}";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// Idempotent: the same ID with the same bytes returns the existing task and is never charged twice.
async function submit() {
  for (let attempt = 1; attempt <= 5; attempt++) {
    try {
      const response = await fetch('https://api.musespan.com/v1/model-tasks', {
        method: 'POST', signal: AbortSignal.timeout(30_000),
        headers: { ...headers, 'Content-Type': 'application/json', 'X-Request-Id': requestId },
        body,
      });
      if (response.ok) return;
      if (response.status !== 429 && response.status < 500) {
        // 409: this ID was used with a different body; use a new directory.
        // Other 4xx: nothing was created; fix the request, then rerun.
        throw new Error(`${response.status} ${await response.text()}`);
      }
    } catch (error) {
      if (!(error instanceof TypeError) && error.name !== 'TimeoutError') throw error;
    }
    await sleep(attempt * 2000); // Timeout, network error, 429 or 5xx: resend with the same ID.
  }
  throw new Error('Submission did not succeed; rerun to resend with the same ID.');
}

await submit();
// Up to 5 minutes in the queue (queue_timeout), then no result 15 minutes after acceptance (or no confirmation 15 minutes after submission) ends the task (generation_timeout); neither is charged, and 25 minutes covers both.
const deadline = Date.now() + 25 * 60_000;
let completed = false;
while (!completed && Date.now() < deadline) {
  await sleep(5000);
  let response;
  try {
    response = await fetch('https://api.musespan.com/v1/model-tasks/{id}'.replace('{id}', requestId), { headers, signal: AbortSignal.timeout(30_000) });
  } catch {
    continue; // Retry the read.
  }
  if (response.status === 404) { await submit(); continue; } // The POST never arrived: resend it with the same ID.
  if (response.status === 429 || response.status >= 500) continue;
  if (!response.ok) throw new Error(`${response.status} ${await response.text()}`);
  const task = await response.json();
  // Failed is final; to try again, use a new directory (a new X-Request-Id).
  if (task.status === 'failed') {
    // invalid_parameters lists each rejected field and its rule in error.issues.
    const issues = (task.error?.issues ?? []).map((issue) => `${issue.field} (${issue.rule})`).join(', ');
    throw new Error(`Task failed (${task.error?.code ?? 'unknown'}): ${task.error?.message ?? ''}${issues ? ` Issues: ${issues}` : ''}`);
  }
  if (task.status === 'completed') { console.log(task.output); completed = true; }
  // queued / running are still pending; a queued task may report its estimated queue_position.
}
if (!completed) console.log('Still pending after 25 minutes. Rerun to continue:', requestId);
```

### Complete async Python

```python
import os, time, uuid
import requests
# Use a separate working directory for each new generation. Rerunning here continues this task.
try:
    with open('model-task-id.txt') as saved:
        request_id = saved.read().strip()
except FileNotFoundError:
    request_id = str(uuid.uuid4())
    with open('model-task-id.txt', 'w') as saved:
        saved.write(request_id)
headers = {"Authorization": f"Bearer {os.environ['MUSESPAN_API_KEY']}"}
# Keep the body as fixed bytes: a resend must be byte-identical.
BODY = "{\"model\":\"google/nano-banana-2/image-to-image\",\"input\":{\"prompt\":\"Turn the scene into a snowy winter evening: snow on the roof and planters, warm glowing lights inside the greenhouse; keep the isometric clay style and composition.\",\"aspect_ratio\":\"auto\",\"enable_web_search\":false,\"num_images\":1,\"output_format\":\"png\",\"resolution\":\"1K\",\"system_prompt\":\"\",\"image_urls\":[\"https://pub-a7287c8d5de944d984e22a5bd3ab9bbe.r2.dev/uploads/capability-demo-a2e4c7ff2c095892fd69923b56f5d3a8.png\"]}}".encode()

def submit():
    # Idempotent: the same ID with the same bytes returns the existing task and is never charged twice.
    for attempt in range(1, 6):
        try:
            response = requests.post('https://api.musespan.com/v1/model-tasks', headers={**headers, 'X-Request-Id': request_id, 'Content-Type': 'application/json'}, data=BODY, timeout=(10, 30))
            if response.ok:
                return
            if response.status_code != 429 and response.status_code < 500:
                # 409: this ID was used with a different body; use a new directory.
                # Other 4xx: nothing was created; fix the request, then rerun.
                raise RuntimeError(f'{response.status_code} {response.text}')
        except requests.RequestException:
            pass  # Timeout or network error: resend with the same ID.
        time.sleep(attempt * 2)
    raise RuntimeError('Submission did not succeed; rerun to resend with the same ID.')

submit()
# Up to 5 minutes in the queue (queue_timeout), then no result 15 minutes after acceptance (or no confirmation 15 minutes after submission) ends the task (generation_timeout); neither is charged, and 25 minutes covers both.
deadline = time.time() + 1500
while time.time() < deadline:
    time.sleep(5)
    try:
        response = requests.get('https://api.musespan.com/v1/model-tasks/{id}'.replace('{id}', request_id), headers=headers, timeout=(10, 30))
    except requests.RequestException:
        continue  # Retry the read.
    if response.status_code == 404:
        submit()  # The POST never arrived: resend it with the same ID.
        continue
    if response.status_code == 429 or response.status_code >= 500:
        continue
    response.raise_for_status()
    task = response.json()
    if task['status'] == 'failed':
        # Failed is final; to try again, use a new directory (a new X-Request-Id).
        error = task.get('error') or {}
        # invalid_parameters lists each rejected field and its rule in error.issues.
        issues = ', '.join(f"{issue['field']} ({issue['rule']})" for issue in error.get('issues') or [])
        raise RuntimeError(f"Task failed ({error.get('code', 'unknown')}): {error.get('message', '')}" + (f' Issues: {issues}' if issues else ''))
    if task['status'] == 'completed':
        print(task['output'])
        break
    # queued / running are still pending; a queued task may report its estimated queue_position.
else:
    print('Still pending after 25 minutes. Rerun to continue:', request_id)
```

## Additional Resources

- [Model Playground](https://www.musespan.com/models/google/nano-banana-2/image-to-image)
- [OpenAPI Schema](https://www.musespan.com/v1/models/google/nano-banana-2/image-to-image/openapi.json)
- [Platform overview](https://www.musespan.com/llms.txt)
