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

# Hướng dẫn nhanh Gemini image API: Tạo ảnh Nano Banana với CometAPI

> Tạo ảnh với các model ảnh Gemini thông qua CometAPI, bao gồm các họ model Nano Banana, và lưu đầu ra inlineData bằng curl, Python hoặc Node.js.

## Những gì bạn sẽ xây dựng

Bạn sẽ gọi route `generateContent` của Gemini image thông qua CometAPI, yêu cầu đầu ra là hình ảnh từ các model ảnh Gemini bao gồm các họ model Nano Banana, bỏ qua các phần ảnh `thought` trung gian, và lưu ảnh `inlineData` cuối cùng.

## Điều kiện tiên quyết

* Một API key CometAPI được lưu trong `COMETAPI_KEY`
* Python 3.10+ với `requests`, hoặc Node.js 18+
* Một model ID ảnh Gemini. Tài liệu tham chiếu API được duy trì sử dụng `gemini-3.1-flash-image-preview` làm ví dụ text-to-image.

## API key, base URL, xác thực

Sử dụng route Gemini image thông qua CometAPI:

```text theme={null}
https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent
```

Xác thực bằng `x-goog-api-key`:

```text theme={null}
x-goog-api-key: $COMETAPI_KEY
```

## Ví dụ mã

Sử dụng các tab bên dưới để xem các ví dụ có thể sao chép cho cURL, Python và Node.js.

<CodeGroup>
  ```bash cURL theme={null}
  curl -s -X POST \
    "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent" \
    -H "x-goog-api-key: $COMETAPI_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "contents": [
        {
          "parts": [
            {
              "text": "A Monarch butterfly anatomical sketch on textured parchment"
            }
          ]
        }
      ],
      "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"],
        "imageConfig": {
          "aspectRatio": "1:1",
          "imageSize": "4K"
        }
      }
    }'
  ```

  ```python Python theme={null}
  import base64
  import os
  import requests

  response = requests.post(
      "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent",
      headers={
          "x-goog-api-key": os.environ["COMETAPI_KEY"],
          "Content-Type": "application/json",
      },
      json={
          "contents": [
              {
                  "parts": [
                      {
                          "text": "A Monarch butterfly anatomical sketch on textured parchment"
                      }
                  ]
              }
          ],
          "generationConfig": {
              "responseModalities": ["TEXT", "IMAGE"],
              "imageConfig": {"aspectRatio": "1:1", "imageSize": "4K"},
          },
      },
      timeout=120,
  )
  response.raise_for_status()

  parts = response.json()["candidates"][0]["content"]["parts"]
  for part in reversed(parts):
      if part.get("thought") is True:
          continue
      inline_data = part.get("inlineData")
      if inline_data:
          image_bytes = base64.b64decode(inline_data["data"])
          mime_type = inline_data.get("mimeType", "image/png")
          extension = "jpg" if mime_type == "image/jpeg" else "png"
          with open(f"nano-banana-result.{extension}", "wb") as file:
              file.write(image_bytes)
          break
  else:
      raise RuntimeError("No final image part found")
  ```

  ```javascript Node.js theme={null}
  import fs from "node:fs/promises";

  const response = await fetch(
    "https://api.cometapi.com/v1beta/models/gemini-3.1-flash-image-preview:generateContent",
    {
      method: "POST",
      headers: {
        "x-goog-api-key": process.env.COMETAPI_KEY,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        contents: [
          {
            parts: [
              {
                text: "A Monarch butterfly anatomical sketch on textured parchment",
              },
            ],
          },
        ],
        generationConfig: {
          responseModalities: ["TEXT", "IMAGE"],
          imageConfig: { aspectRatio: "1:1", imageSize: "4K" },
        },
      }),
    },
  );

  if (!response.ok) {
    throw new Error(await response.text());
  }

  const body = await response.json();
  const parts = body.candidates[0].content.parts;
  const finalImage = [...parts]
    .reverse()
    .find((part) => part.thought !== true && part.inlineData);

  if (!finalImage) {
    throw new Error("No final image part found");
  }

  const mimeType = finalImage.inlineData.mimeType || "image/png";
  const extension = mimeType === "image/jpeg" ? "jpg" : "png";
  await fs.writeFile(
    `nano-banana-result.${extension}`,
    Buffer.from(finalImage.inlineData.data, "base64"),
  );
  ```
</CodeGroup>

## Giải thích luồng

Việc tạo ảnh Gemini là đồng bộ trên route này. Phản hồi sử dụng cấu trúc gốc của Gemini là `candidates[].content.parts[]`. Các phần có thể bao gồm văn bản, ảnh được tạo, và các phần ảnh trung gian trong đó `thought` là `true`.

Khi lưu kết quả, hãy lặp qua các phần ảnh, bỏ qua `thought: true`, và lưu ảnh `inlineData` còn lại cuối cùng.

## Các tham số phổ biến

| Parameter                             | Use                                                                                                 |
| ------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `model` path segment                  | model ID ảnh Gemini trong đường dẫn URL.                                                            |
| `contents`                            | Prompt và các phần ảnh đầu vào tùy chọn.                                                            |
| `generationConfig.responseModalities` | Bao gồm `IMAGE` khi bạn cần đầu ra hình ảnh.                                                        |
| `generationConfig.imageConfig`        | Các tùy chọn hình ảnh như tỷ lệ khung hình và kích thước ảnh khi được model đã chọn hỗ trợ.         |
| `tools`                               | Các công cụ Gemini tùy chọn. Chỉ thêm khi tài liệu tham chiếu API mô tả quy trình làm việc đã chọn. |

## Khắc phục sự cố / FAQ

<AccordionGroup>
  <Accordion title="Phản hồi chứa các ảnh thought">
    Không lưu các phần mà `thought` là `true`. Đây là các ảnh trung gian, không phải đầu ra cuối cùng.
  </Accordion>

  <Accordion title="Yêu cầu chỉ trả về văn bản">
    Kiểm tra rằng `generationConfig.responseModalities` có bao gồm `IMAGE`, và model đã chọn hỗ trợ đầu ra hình ảnh.
  </Accordion>

  <Accordion title="Tôi cần image-to-image">
    Sử dụng các phần yêu cầu `inline_data` như được hiển thị trong hướng dẫn Gemini image, và giữ nguyên logic phân tích ảnh cuối cùng.
  </Accordion>
</AccordionGroup>

## Các bước tiếp theo

* Đọc [tài liệu tham chiếu Gemini image API](/api/image/gemini/gemini-generates-image).
* Xem thêm ví dụ trong [Sử dụng các model ảnh Gemini](/api/image/gemini/generate-image-guide).
* Tìm các model ảnh khả dụng trong [Models](/vi/overview/models).
* Ước tính chi phí với [Ước tính chi phí yêu cầu trước khi gọi model](/vi/guides/how-to-estimate-cost-before-calling-a-model).
