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

# Text To Image

> Generate the desired image from the text description.

export const GeminiTextToImage = ({model = "gemini-2.5-flash-image"}) => {
  const curlExample = `curl --request POST \\
  --url 'https://aiandgpu.com/v1beta/models/${model}:generateContent' \\
  --header 'Authorization: Bearer <YOUR_API_KEY>' \\
  --header 'Content-Type: application/json' \\
  --data '{
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "text": "帮我生成一张小猫在草地上玩耍的图片"
        }
      ]
    }
  ],
  "generationConfig": {
    "imageConfig": {
      "aspectRatio": "1:1"
    }
  }
}'`;
  const pythonExample = `import requests

url = "https://aiandgpu.com/v1beta/models/${model}:generateContent"

payload = {
    "contents": [
        {
            "role": "user",
            "parts": [
                {
                    "text": "帮我生成一张小猫在草地上玩耍的图片"
                }
            ]
        }
    ],
    "generationConfig": {
        "imageConfig": {
            "aspectRatio": "1:1"
        }
    }
}

headers = {
    "Authorization": "Bearer <YOUR_API_KEY>",
    "Content-Type": "application/json",
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())`;
  const jsExample = `const response = await fetch('https://aiandgpu.com/v1beta/models/${model}:generateContent', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <YOUR_API_KEY>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    contents: [
      {
        role: 'user',
        parts: [
          {
            text: '帮我生成一张小猫在草地上玩耍的图片'
          }
        ]
      }
    ],
    generationConfig: {
      imageConfig: {
        aspectRatio: '1:1'
      }
    }
  })
});

const data = await response.json();
console.log(data);`;
  const goExample = `package main

import (
\t"fmt"
\t"io"
\t"net/http"
\t"strings"
)

func main() {
\turl := "https://aiandgpu.com/v1beta/models/${model}:generateContent"

\tpayload := strings.NewReader(\`{
  "contents": [
    {
      "role": "user",
      "parts": [
        {"text": "帮我生成一张小猫在草地上玩耍的图片"}
      ]
    }
  ],
  "generationConfig": {
    "imageConfig": {"aspectRatio": "1:1"}
  }
}\`)

\treq, _ := http.NewRequest("POST", url, payload)

\treq.Header.Add("Authorization", "Bearer <YOUR_API_KEY>")
\treq.Header.Add("Content-Type", "application/json")

\tres, _ := http.DefaultClient.Do(req)
\tdefer res.Body.Close()

\tbody, _ := io.ReadAll(res.Body)
\tfmt.Println(string(body))
}`;
  const javaExample = `import java.net.http.*;
import java.net.URI;

HttpClient client = HttpClient.newHttpClient();

String body = """
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {"text": "帮我生成一张小猫在草地上玩耍的图片"}
      ]
    }
  ],
  "generationConfig": {
    "imageConfig": {"aspectRatio": "1:1"}
  }
}
""";

HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://aiandgpu.com/v1beta/models/${model}:generateContent"))
    .header("Authorization", "Bearer <YOUR_API_KEY>")
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());`;
  const phpExample = `<?php

$curl = curl_init();

$payload = json_encode([
    'contents' => [
        [
            'role' => 'user',
            'parts' => [
                ['text' => '帮我生成一张小猫在草地上玩耍的图片']
            ]
        ]
    ],
    'generationConfig' => [
        'imageConfig' => [
            'aspectRatio' => '1:1'
        ]
    ]
]);

curl_setopt_array($curl, [
    CURLOPT_URL => "https://aiandgpu.com/v1beta/models/${model}:generateContent",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer <YOUR_API_KEY>",
        "Content-Type: application/json",
    ],
]);

$response = curl_exec($curl);
curl_close($curl);

echo $response;`;
  const csharpExample = `using System.Net.Http;
using System.Text;

var client = new HttpClient();

var payload = @"{
    ""contents"": [
        {
            ""role"": ""user"",
            ""parts"": [
                {""text"": ""帮我生成一张小猫在草地上玩耍的图片""}
            ]
        }
    ],
    ""generationConfig"": {
        ""imageConfig"": {""aspectRatio"": ""1:1""}
    }
}";

var request = new HttpRequestMessage(HttpMethod.Post, "https://aiandgpu.com/v1beta/models/${model}:generateContent");
request.Headers.Add("Authorization", "Bearer <YOUR_API_KEY>");
request.Content = new StringContent(payload, Encoding.UTF8, "application/json");

var response = await client.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);`;
  return <>
      <h2>Request Examples</h2>

      <CodeGroup>
        <CodeBlock language="shellscript" filename="cURL">
          {curlExample}
        </CodeBlock>
        <CodeBlock language="python" filename="Python">
          {pythonExample}
        </CodeBlock>
        <CodeBlock language="javascript" filename="JavaScript">
          {jsExample}
        </CodeBlock>
        <CodeBlock language="go" filename="Go">
          {goExample}
        </CodeBlock>
        <CodeBlock language="java" filename="Java">
          {javaExample}
        </CodeBlock>
        <CodeBlock language="php" filename="PHP">
          {phpExample}
        </CodeBlock>
        <CodeBlock language="csharp" filename="C#">
          {csharpExample}
        </CodeBlock>
      </CodeGroup>
    </>;
};

export const GeminiApiResponse = ({successJson, successTitle = "200 - Success", streaming = false}) => {
  const error400 = `{
   "error": {
        "code": 400,
        "message": "Invalid request error",
        "status": "INVALID_ARGUMENT"
   }
}`;
  const error401 = `{
   "error": {
        "code": 401,
        "message": "Invalid API Key",
        "status": "UNAUTHENTICATED"
   }
}`;
  const error402 = `{
   "error": {
        "code": 402,
        "message": "Insufficient balance",
        "status": "INSUFFICIENT_BALANCE"
   }
}`;
  const error403 = `{
   "error": {
        "code": 403,
        "message": "Permission denied on this model",
        "status": "PERMISSION_DENIED"
   }
}`;
  const error404 = `{
   "error": {
        "code": 404,
        "message": "Invalid URL",
        "status": "INVALID_ARGUMENT"
   }
}`;
  const error429 = `{
   "error": {
        "code": 429,
        "message": "Too many requests",
        "status": "RATE_LIMIT_ERROR"
   }
}`;
  const error500 = `{
    "error": {
        "code": 500,
        "message": "Internal server error",
        "status": "INTERNAL_ERROR"
   }
}`;
  return <>
      <h2>Response Examples</h2>

      <CodeGroup>
        <CodeBlock language={streaming ? "text" : "json"} filename={streaming ? "200 - Streaming Response (SSE)" : successTitle}>
          {successJson}
        </CodeBlock>
        <CodeBlock language="json" filename="400 - Bad Request">
          {error400}
        </CodeBlock>
        <CodeBlock language="json" filename="401 - Unauthorized">
          {error401}
        </CodeBlock>
        <CodeBlock language="json" filename="402 - Insufficient Balance">
          {error402}
        </CodeBlock>
        <CodeBlock language="json" filename="403 - Permission Denied">
          {error403}
        </CodeBlock>
        <CodeBlock language="json" filename="404 - Invalid URL">
          {error404}
        </CodeBlock>
        <CodeBlock language="json" filename="429 - Too Many Requests">
          {error429}
        </CodeBlock>
        <CodeBlock language="json" filename="500 - Internal Server Error">
          {error500}
        </CodeBlock>
      </CodeGroup>
    </>;
};

## Authorization

* **Auth Type**: `Bearer Auth` (In: `header`)
* **Format**: `Authorization: Bearer <YOUR_API_KEY>`
* **Description**: Use `Bearer <YOUR_API_KEY>`. Format: `Authorization: Bearer sk-xxxxxx.`
* **API Key**: where <strong>API Key</strong> is your <a href="https://developer.aiandgpu.com" target="_blank" rel="noopener noreferrer">AGCloud API KEY</a>

<GeminiTextToImage model="gemini-3.1-flash-image-preview" />

<GeminiApiResponse
  successJson={`{
    "candidates": [
        {
            "content": {
                "role": "model",
                "parts": [
                    {
                        "text": "好的，这是一张小猫在草地上玩耍的图片："
                    },
                    {
                        "inlineData": {
                            "mimeType": "image/png",
                            "data": "base64_encoded_image_data",
                            "url": "your_finish_image_url"
                        },
                        "thoughtSignature": ""
                    }
                ]
            },
            "finishReason": "STOP"
        }
    ],
    "usageMetadata": {
        "promptTokenCount": 13,
        "candidatesTokenCount": 1306,
        "totalTokenCount": 1319,
        "trafficType": "ON_DEMAND",
        "promptTokensDetails": [
            {
                "modality": "TEXT",
                "tokenCount": 13
            }
        ],
        "candidatesTokensDetails": [
            {
                "modality": "TEXT",
                "tokenCount": 16
            },
            {
                "modality": "IMAGE",
                "tokenCount": 1290
            }
        ]
    },
    "modelVersion": "gemini-3.1-flash-image-preview",
    "createTime": "2026-03-04T06:31:28.809553Z",
    "responseId": "wNGnadG0Mcf_48APrffd-Qw"
}`}
/>

## Parameters

### Core Parameters

| Field                                  | Type     | Required | Description                                                                                                                                                                                                  |
| :------------------------------------- | :------- | :------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `contents`                             | `array`  | ✅        | Content of the current conversation with the model. For single-turn queries, this contains one instance. For multi-turn queries (e.g., chat), this contains the conversation history and the latest request. |
| `>contents.role`                       | `string` | ✅        | The role of the message sender. Can be `user` `model`.                                                                                                                                                       |
| `>contents.parts`                      | `array`  | ✅        | The content parts of the message, which can contain different types of content (text, inlineData, etc.). See [Multimodal](#multimodal-input)                                                                 |
| `>>contents.parts.text`                | `string` | ✅        | The prompt for generating images. To include images or multiple images                                                                                                                                       |
| `generationConfig`                     | `object` | -        | Configuration options for content generation.                                                                                                                                                                |
| `>generationConfig.imageConfig`        | `object` | -        | Configuration for image generation. If set for models that don’t support these configuration options, the system will return an error. See [ImageConfiguration](#image-configuration)                        |
| `>generationConfig.responseModalities` | `array`  | -        | The modalities of the response. If set for models that don’t support these configuration options, the system will return an error. Can be `TEXT` `IMAGE`.                                                    |
| `>generationConfig.temperature`        | `number` | -        | Controls the randomness of the output. Range in `0.0-1.0`.                                                                                                                                                   |

### Multimodal Input

<CodeGroup>
  ```json inlineData with image theme={null}
  {
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "inlineData": {
              "mimeType": "image/jpeg",
              "data": "base64-encoded-image-data"
            }
          },
          {
            "text": "a cat"
          }
        ]
      }
    ]
  }
  ```

  ```json inlineData with multiple images theme={null}
  {
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "inlineData": {
              "mimeType": "image/jpeg",
              "data": "base64-encoded-image-1-data"
            }
          },
          {
            "inlineData": {
              "mimeType": "image/png",
              "data": "base64-encoded-image-2-data"
            }
          },
          {
            "text": "Combine these two images into a seamless panorama with a mountain background."
          }
        ]
      }
    ]
  }
  ```

  ```json fileData with image theme={null}
  {
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "fileData": {
              "mimeType": "image/jpeg",
              "fileUri": "https://robohash.org/OYK.png"
            }
          },
          {
            "text": "a cat"
          }
        ]
      }
    ]
  }
  ```

  ```json fileData with multiple images theme={null}
  {
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "fileData": {
              "mimeType": "image/jpeg",
              "fileUri": "https://example.com/image1.jpg"
            }
          },
          {
            "fileData": {
              "mimeType": "image/png",
              "fileUri": "https://example.com/image2.png"
            }
          },
          {
            "text": "Remove the background from both images and blend them together with a sunset overlay."
          }
        ]
      }
    ]
  }
  ```
</CodeGroup>

| Field                         | Type     | Required                        | Range/Example                  | Description                                                                                                                  |
| :---------------------------- | :------- | :------------------------------ | :----------------------------- | :--------------------------------------------------------------------------------------------------------------------------- |
| `parts`                       | `array`  | ✅                               | `text` `inlineData` `fileData` | The content parts of the message, which can contain different types of content.                                              |
| `>parts.inlineData`           | `object` | -                               | -                              | Inline media content. If used, data must be base64-encoded.                                                                  |
| `>>parts.inlineData.mimeType` | `string` | ✅ Yes (if inline\_data is used) | `image/jpeg` `image/png`       | The IANA-standard MIME type of the source data. If the provided MIME type is not supported, the system will return an error. |
| `>>parts.inlineData.data`     | `string` | ✅ Yes (if inline\_data is used) | -                              | Base64-encoded media data.                                                                                                   |
| `>parts.fileData`             | `object` | -                               | -                              | File media content. If used, fileUri must be provided.                                                                       |
| `>>parts.fileData.mimeType`   | `string` | ✅ Yes (if file\_data is used)   | `image/jpeg` `image/png`       | The IANA-standard MIME type of the source data. If the provided MIME type is not supported, the system will return an error. |
| `>>parts.fileData.fileUri`    | `string` | ✅ Yes (if file\_data is used)   | -                              | The URI of the file to be processed.                                                                                         |

### Image Configuration

```json theme={null}
{
  "generationConfig": {
    "imageConfig": {
      "aspectRatio": "1:1",
      "imageSize": "1K"
    }
  }
}
```

| Field                      | Type     | Required | Range/Example                                                                                                                                                     | Description                                                                                                                                                                                                                                                     |
| :------------------------- | :------- | :------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `imageConfig`              | `object` | -        | -                                                                                                                                                                 | Configuration for image generation.                                                                                                                                                                                                                             |
| `>imageConfig.aspectRatio` | `string` | -        | `1:1` <br /> `2:3` <br />  `3:2` <br />  `3:4` <br />  `4:3` <br />  `9:16` <br />  `16:9` <br />  `21:9` <br />  `1:4` <br />  `4:1` <br />  `1:8` <br />  `8:1` | Configuration for image generation.                                                                                                                                                                                                                             |
| `>imageConfig.imageSize`   | `string` | -        | `0.5K` <br />  `1K` <br />  `2K` <br />  `4K`                                                                                                                     | Approximate size of the generated image. If not specified, the model will use the default value of 1K. 0.5K is only supported by Gemini 3.1 Flash Image Preview; 2K and 4K are only supported by Gemini 3.1 Flash Image Preview and Gemini 3 Pro Image Preview. |

### Model Comparison

| Feature              | Gemini 2.5 Flash Image | Gemini 3.1 Flash Image Preview | Gemini 3 Pro Image Preview    |
| :------------------- | :--------------------- | :----------------------------- | :---------------------------- |
| Use case             | Speed & efficiency     | Speed & high-volume            | Professional asset production |
| Supported sizes      | 1K                     | 0.5K, 1K, 2K, 4K               | 1K, 2K, 4K                    |
| Max reference images | 3                      | 14                             | 14                            |
| Max object images    | —                      | 10                             | 6                             |
| Max portrait images  | —                      | 4                              | 5                             |
| Extra aspect ratios  | —                      | 1:4, 4:1, 1:8, 8:1             | —                             |

**Note:**

* Gemini 3.1 Flash Image Preview: Optimized for speed and high-volume use cases. Supports 0.5K resolution and extra ultra-wide/tall aspect ratios (1:4, 4:1, 1:8, 8:1). Also supports Google Image Search Grounding.
* Gemini 3 Pro Image Preview: Optimized for professional asset production with advanced reasoning for complex creation tasks.
* Gemini 2.5 Flash Image: Supports a maximum of 3 reference images and 1K resolution only.

**Aspect Ratio & Image Size:**

* By default, the model keeps the output image the same size as the input image; otherwise it produces a 1:1 square. You can control the aspect ratio of the generated image with the `aspect_ratio` field under `image_config` in your request, as shown below:
