# Image Generation (Gemini Native Protocol)

## 1. Overview

A text-to-image/image-to-image model launched by Google.

{% hint style="info" %}
This API uses the Gemini native interface.
{% endhint %}

{% hint style="info" %}
This document only covers a subset of parameters. For the full parameter list, refer to the [official documentation](https://ai.google.dev/api/generate-content).
{% endhint %}

**Model List:**

* `gemini-2.5-flash-image` (Nano-Banana)
* `gemini-3-pro-image-preview` (Nano-Banana-Pro)
* `gemini-3.1-flash-image-preview` (Nano-Banana-2)

{% hint style="warning" %}
This is a multimodal model. The description must explicitly include the scene to be drawn or explicitly request image generation. Simple words or phrases may not produce image output.
{% endhint %}

## 2. Request Description

* **Request Method**: `POST`
* **Request URL**:

  > `https://gateway.theturbo.ai/v1/v1beta/models/{model}:generateContent`

***

## 3. Request Parameters

### 3.1 Header Parameters

| Parameter Name  | Type   | Required | Description                                                | Example                |
| --------------- | ------ | -------- | ---------------------------------------------------------- | ---------------------- |
| `Content-Type`  | string | Yes      | Set the request header type, must be `application/json`    | `application/json`     |
| `Authorization` | string | Yes      | API\_KEY for authentication, format `Bearer $YOUR_API_KEY` | `Bearer $YOUR_API_KEY` |

***

### 3.2 Body Parameters (application/json)

| Parameter Name                           | Type   | Required | Description                                                                                                                                                                                                                       | Example                                                        |
| ---------------------------------------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| **contents**                             | array  | Yes      | The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries (e.g., chat), this is a repeated field containing conversation history and the latest request. | `[{"role":"user","parts":[{"text":"A cute baby sea otter"}]}]` |
| content.role                             | string | Yes      | The message role. Must be `user` or `model`.                                                                                                                                                                                      | `user`                                                         |
| content.parts                            | array  | No       | Ordered Parts that make up a single message. Parts may have different MIME types.                                                                                                                                                 | `[{"text":"A cute baby sea otter"}]}]`                         |
| content.parts.text                       | string | No       | Inline text.                                                                                                                                                                                                                      | `A cute baby sea otter`                                        |
| content.parts.inlineData                 | struct | No       | Inline media bytes.                                                                                                                                                                                                               |                                                                |
| content.parts.inlineData.mimeType        | string | Yes      | The IANA standard MIME type of the source data.                                                                                                                                                                                   | `image/png`                                                    |
| content.parts.inlineData.data            | string | Yes      | Raw bytes in media format. A base64-encoded string.                                                                                                                                                                               |                                                                |
| generationConfig                         | struct | No       | Configuration options for model generation and output.                                                                                                                                                                            |                                                                |
| generationConfig.imageConfig             | struct | No       | Image generation configuration. If this field is set for a model that does not support these configuration options, an error will be returned.                                                                                    |                                                                |
| generationConfig.imageConfig.aspectRatio | string | No       | Optional. The aspect ratio of the image to generate. Supported aspect ratios: `1:1` `2:3` `3:2` `3:4` `4:3` `9:16` `16:9` `21:9`.                                                                                                 | `16:9`                                                         |
| generationConfig.imageConfig.imageSize   | string | No       | Specify the size of the generated image. Supported values are `1K`, `2K`, `4K`.                                                                                                                                                   | `1K`                                                           |

***

## 4. Request Examples

### 4.1 Text-to-Image

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/v1beta/models/gemini-2.5-flash-image:generateContent
Content-Type: application/json
Accept: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"contents": [{
		"role": "user",
		"parts": [{
			"text": "A cute baby sea otter"
		}]
	}],
	"generationConfig": {
		"imageConfig": {
			"aspectRatio": "4:3",
			"imageSize": "1K"
		}
	}
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
curl https://gateway.theturbo.ai/v1/v1beta/models/gemini-2.5-flash-image:generateContent \
	-H "Content-Type: application/json" \
	-H "Accept: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"contents\": [{
		\"role\": \"user\",
		\"parts\": [{
			\"text\": \"A cute baby sea otter\"
		}]
	}],
	\"generationConfig\": {
		\"imageConfig\": {
			\"aspectRatio\": \"4:3\",
			\"imageSize\": \"1K\"
		}
	}
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"
	"os"

	"google.golang.org/genai"
)

func main() {

	apiKey := "sk-123456789012345678901234567890123456789012345678"
	exampleFilePath := "example.png"

	client, err := genai.NewClient(
		context.Background(),
		&genai.ClientConfig{
			APIKey:  apiKey,
			Backend: genai.BackendGeminiAPI,
			HTTPOptions: genai.HTTPOptions{
				BaseURL: "https://gateway.theturbo.ai",
			},
		})
	if err != nil {
		fmt.Println("error creating client:", err)
		return
	}

	resp, err := client.Models.GenerateContent(
		context.Background(),
		"gemini-2.5-flash-image",
		[]*genai.Content{
			{
				Role: "user",
				Parts: []*genai.Part{
					{Text: "A cute baby sea otter"},
				},
			},
		},
		&genai.GenerateContentConfig{
			ImageConfig: &genai.ImageConfig{
				AspectRatio: "4:3",
				ImageSize:   "1K",
			},
		},
	)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	var imageData []byte
	for _, candidate := range resp.Candidates {
		for _, part := range candidate.Content.Parts {
			if part.InlineData != nil && part.InlineData.MIMEType == "image/png" {
				imageData = part.InlineData.Data
				break
			}
		}
		if imageData != nil {
			break
		}
	}

	if imageData == nil {
		fmt.Println("error: no image data found")
		return
	}

	if err := os.WriteFile(exampleFilePath, imageData, 0644); err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println("success to write to file", exampleFilePath)
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

from google import genai

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"
    example_file_path = "example.png"

    client = genai.Client(
        api_key=api_key,
        http_options={
            "base_url": "https://gateway.theturbo.ai"
        }
    )

    response = client.models.generate_content(
        model="gemini-2.5-flash-image",
        contents="A cute baby sea otter",
        config=genai.types.GenerateContentConfig(
            image_config=genai.types.ImageConfig(
                aspect_ratio="4:3",
                image_size="1K"
            )
        )
    )

    image_data = None
    for candidate in response.candidates:
        for part in candidate.content.parts:
            if part.inline_data and part.inline_data.mime_type == "image/png":
                image_data = part.inline_data.data
                break
        if image_data:
            break

    if not image_data:
        print("error: no image data found")
        return

    with open(example_file_path, "wb") as f:
        f.write(image_data)

    print(f"success to write to file {example_file_path}")

if __name__ == "__main__":
    main()

```

{% endtab %}
{% endtabs %}

### 4.2 Image-to-Image

<details>

<summary>Supported inline image types</summary>

`image/png` `image/jpeg` `image/webp` `image/heic` `image/heif`

</details>

{% tabs %}
{% tab title="HTTP" %}

```http
POST /v1/v1beta/models/gemini-2.5-flash-image:generateContent
Content-Type: application/json
Accept: application/json
Authorization: Bearer $YOUR_API_KEY

{
	"contents": [{
		"role": "user",
		"parts": [{
			"text": "add a rainbow"
		}, {
			"inlineData": {
				"mimeType": "image/png",
				"data": "..."
			}
		}]
	}],
	"generationConfig": {
		"imageConfig": {
			"aspectRatio": "4:3",
			"imageSize": "1K"
		}
	}
}
```

{% endtab %}

{% tab title="Shell" %}

```sh
base64_image=$(base64 -i "Path/to/agi/image.png");
curl https://gateway.theturbo.ai/v1/v1beta/models/gemini-2.5-flash-image:generateContent \
	-H "Content-Type: application/json" \
	-H "Accept: application/json" \
	-H "Authorization: Bearer $YOUR_API_KEY" \
	-d "{
	\"contents\": [{
		\"role\": \"user\",
		\"parts\": [{
			\"text\": \"add a rainbow\"
		}, {
			\"inlineData\": {
				\"mimeType\": \"image/png\",
				\"data\": \"${base64_image}\"
			}
		}]
	}],
	\"generationConfig\": {
		\"imageConfig\": {
			\"aspectRatio\": \"4:3\",
			\"imageSize\": \"1K\"
		}
	}
}"
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"context"
	"fmt"
	"os"

	"google.golang.org/genai"
)

func main() {

	apiKey := "sk-123456789012345678901234567890123456789012345678"
	inputPath := "example.png"
	outputPath := "example2.png"

	inputData, err := os.ReadFile(inputPath)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	client, err := genai.NewClient(
		context.Background(),
		&genai.ClientConfig{
			APIKey:  apiKey,
			Backend: genai.BackendGeminiAPI,
			HTTPOptions: genai.HTTPOptions{
				BaseURL: "https://gateway.theturbo.ai",
			},
		})
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	resp, err := client.Models.GenerateContent(
		context.Background(),
		"gemini-2.5-flash-image",
		[]*genai.Content{
			{
				Role: "user",
				Parts: []*genai.Part{
					{Text: "add a rainbow"},
					{
						InlineData: &genai.Blob{
							MIMEType: "image/png",
							Data:     inputData,
						},
					},
				},
			},
		},
		&genai.GenerateContentConfig{
			ImageConfig: &genai.ImageConfig{
				AspectRatio: "4:3",
				ImageSize:   "1K",
			},
		},
	)
	if err != nil {
		fmt.Println("error:", err)
		return
	}

	var imageData []byte
	for _, candidate := range resp.Candidates {
		for _, part := range candidate.Content.Parts {
			if part.InlineData != nil && part.InlineData.MIMEType == "image/png" {
				imageData = part.InlineData.Data
				break
			}
		}
		if imageData != nil {
			break
		}
	}

	if imageData == nil {
		fmt.Println("error: no image data found")
		return
	}

	if err := os.WriteFile(outputPath, imageData, 0644); err != nil {
		fmt.Println("error:", err)
		return
	}

	fmt.Println("success to write to file", outputPath)
}

```

{% endtab %}

{% tab title="Python" %}

```python
#!/usr/bin/env python3

from google import genai

def main():
    api_key = "sk-123456789012345678901234567890123456789012345678"
    input_path = "example.png"
    output_path = "example2.png"

    with open(input_path, "rb") as f:
        input_data = f.read()

    client = genai.Client(
        api_key=api_key,
        http_options={
            "base_url": "https://gateway.theturbo.ai"
        }
    )

    response = client.models.generate_content(
        model="gemini-2.5-flash-image",
        contents=[
            "add a rainbow",
            genai.types.Part(
                inline_data=genai.types.Blob(
                    mime_type="image/png",
                    data=input_data
                )
            )
        ],
        config=genai.types.GenerateContentConfig(
            image_config=genai.types.ImageConfig(
                aspect_ratio="4:3",
                image_size="1K"
            )
        )
    )

    image_data = None
    for candidate in response.candidates:
        for part in candidate.content.parts:
            if part.inline_data and part.inline_data.mime_type == "image/png":
                image_data = part.inline_data.data
                break
        if image_data:
            break

    if not image_data:
        print("error: no image data found")
        return

    with open(output_path, "wb") as f:
        f.write(image_data)

    print(f"success to write to file {output_path}")

if __name__ == "__main__":
    main()

```

{% endtab %}
{% endtabs %}

## 5. Response Example

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "inlineData": {
              "mimeType": "image/png",
              "data": "..."
            }
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 5,
    "candidatesTokenCount": 1290,
    "totalTokenCount": 1295,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 5
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "IMAGE",
        "tokenCount": 1290
      }
    ]
  },
  "modelVersion": "gemini-2.5-flash-image",
  "createTime": "2025-12-02T05:44:30.324935Z",
  "responseId": "vmU2acfqE--ijeYP-9ykgAI"
}

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.console.zenlayer.com/api/compute/aig/image-generation/nano-banana/nano-banana-image-generation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
