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

# 用 Gemini 生成图像

> 用 Gemini 图像模型生成和编辑图像。

Gemini 图像模型不走 `/v1/images/*`。它和文本模型一样通过 `generateContent` 生成图像，图像字节以 inline part 的形式，和模型输出的文本一起返回。

GPT 图像模型请改用 [`POST /v1/images/generations`](/zh/api-reference/image/generations)。

完整的文生图、图生图示例见 [Nano Banana](/zh/use-cases/nano-banana)。

<Info>
  模型 ID 会随时间变化。用 [`GET /v1/models`](/zh/api-reference/list-models) 查询你的账户当前可用的模型。
</Info>

## 端点

| 模式 | 路径 |
| - | - |
| 非流式 | `POST /v1beta/models/{model}:generateContent` |
| 流式 | `POST /v1beta/models/{model}:streamGenerateContent` |

和所有 Gemini 路由一样，用 `x-goog-api-key` 认证。见 [Gemini 总览](/zh/api-reference/gemini/overview)。

<ParamField body="contents" type="array" required>
  对话轮次。文生图只需一个 user 轮次、一个文本 part；图生图则在同一轮次里追加源图的 inline part。

  <Expandable title="contents[]">
    <ParamField body="role" type="string">
      `user` 或 `model`。
    </ParamField>

    <ParamField body="parts" type="array" required>
      文本 part 和图像 inline part 的混合。

      <Expandable title="parts[]">
        <ParamField body="text" type="string">
          提示词文本。
        </ParamField>

        <ParamField body="inlineData" type="object">
          源图，由 `mimeType`（例如 `image/png`）和 base64 的 `data` 组成。
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="generationConfig" type="object">
  Gemini 标准生成配置。图像模型还接受尺寸相关的控制项，但各模型支持的宽高比和分辨率不同，依赖具体取值前请先确认该模型的能力。
</ParamField>

<RequestExample>
  ```bash cURL theme={"dark"}
  curl https://api.pipellm.ai/v1beta/models/gemini-3-pro-image:generateContent \
    -H "x-goog-api-key: $PIPELLM_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "contents": [{
        "role": "user",
        "parts": [{"text": "A red bicycle leaning against a cafe window, morning light"}]
      }]
    }'
  ```

  ```python Python theme={"dark"}
  import os
  from google import genai

  client = genai.Client(
      api_key=os.environ["PIPELLM_API_KEY"],
      http_options={"base_url": "https://api.pipellm.ai"},
  )

  response = client.models.generate_content(
      model="gemini-3-pro-image",
      contents="A red bicycle leaning against a cafe window, morning light",
  )

  for part in response.parts:
      if part.inline_data is not None:
          part.as_image().save("bicycle.png")
  ```

  ```typescript TypeScript theme={"dark"}
  import fs from "node:fs";
  import { GoogleGenAI } from "@google/genai";

  const ai = new GoogleGenAI({
    apiKey: process.env.PIPELLM_API_KEY,
    httpOptions: { baseUrl: "https://api.pipellm.ai" },
  });

  const response = await ai.models.generateContent({
    model: "gemini-3-pro-image",
    contents: "A red bicycle leaning against a cafe window, morning light",
  });

  for (const part of response.candidates[0].content.parts) {
    if (part.inlineData) {
      fs.writeFileSync("bicycle.png", Buffer.from(part.inlineData.data, "base64"));
    }
  }
  ```
</RequestExample>

<ResponseExample>
  ```json theme={"dark"}
  {
    "candidates": [{
      "content": {
        "role": "model",
        "parts": [
          { "text": "Here is the bicycle scene you asked for." },
          {
            "inlineData": {
              "mimeType": "image/png",
              "data": "iVBORw0KGgoAAAANSUhEUgAA..."
            }
          }
        ]
      },
      "finishReason": "STOP"
    }],
    "usageMetadata": {
      "promptTokenCount": 12,
      "candidatesTokenCount": 1290,
      "totalTokenCount": 1302
    }
  }
  ```
</ResponseExample>

<ResponseField name="candidates" type="array">
  生成结果。

  <Expandable title="candidates[]">
    <ResponseField name="content.parts" type="array">
      交错排列的输出。每个 part 要么是 `text`，要么是 `inlineData`，不会同时有。一次响应里两种可以各有多个，所以要遍历全部 part，不要只读 `parts[0]`。
    </ResponseField>

    <ResponseField name="content.parts[].inlineData.mimeType" type="string">
      例如 `image/png`。
    </ResponseField>

    <ResponseField name="content.parts[].inlineData.data" type="string">
      Base64 编码的图像字节。
    </ResponseField>

    <ResponseField name="finishReason" type="string">
      成功时为 `STOP`。因安全策略中止时不会返回图像 part。
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usageMetadata" type="object">
  Token 用量。生成的图像按图像输出 token 计费，这部分是费用的主要来源，见 [价格](/zh/api-reference/model-pricing)。
</ResponseField>

## 解析响应

两个习惯能省掉不少麻烦：

* **遍历每一个 part。** 让模型生成带插图的说明时，文本和图像 part 是交错的。只取第一个 part 会静默丢内容。
* **要能接受纯文本响应。** 提示词因安全策略被拒时，响应仍是 `200`，只有文本 part，没有 `inlineData`。解码前先确认图像 part 存在。

Gemini 生成的图像带有 SynthID 水印。

## 错误

Gemini 路由返回 Gemini 的错误结构，不是 OpenAI 那套。完整映射见 [错误处理](/zh/api-reference/errors)。

<AccordionGroup>
  <Accordion title="400 INVALID_ARGUMENT">
    `contents` 结构有误、inline part 的 `mimeType` 不受支持，或尺寸取值模型不接受。
  </Accordion>

  <Accordion title="401 UNAUTHENTICATED">
    缺少或填错 `x-goog-api-key`。
  </Accordion>

  <Accordion title="429 RESOURCE_EXHAUSTED">
    见 [速率限制](/zh/api-reference/rate-limits)。
  </Accordion>
</AccordionGroup>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.