> ## 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 generateContent API 生成内容。

Gemini 原生路径。流式请用 [`POST /v1beta/models/{model}:streamGenerateContent`](/zh/api-reference/gemini/stream-generate-content)。

<RequestExample>
  ```bash cURL theme={"dark"}
  curl "https://api.pipellm.ai/v1beta/models/gemini-3-flash-preview:generateContent" \
    -H "Content-Type: application/json" \
    -H "x-goog-api-key: $PIPELLM_API_KEY" \
    -d '{
      "contents": [{"role": "user", "parts": [{"text": "你好"}]}]
    }'
  ```

  ```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"},
  )
  print(client.models.generate_content(
      model="gemini-3-flash-preview",
      contents="你好",
  ).text)
  ```
</RequestExample>

<ParamField path="model" type="string" required>
  Gemini 模型 ID，例如 `gemini-3-flash-preview`。
</ParamField>

<ParamField body="contents" type="array" required>
  对话轮次。

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

    <ParamField body="parts" type="array" required>
      这一轮的内容块。

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

        <ParamField body="inline_data" type="object">
          内联媒体。使用 `mime_type`（例如 `image/png`）和 `data`（base64）。图像模型的生成结果也在这里。
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="generationConfig" type="object">
  可选采样配置。

  <Expandable title="generationConfig 字段">
    <ParamField body="temperature" type="number">
      采样温度。
    </ParamField>

    <ParamField body="maxOutputTokens" type="integer">
      最大输出 token 数。
    </ParamField>

    <ParamField body="topP" type="number">
      核采样。
    </ParamField>

    <ParamField body="topK" type="integer">
      Top-k 采样。
    </ParamField>
  </Expandable>
</ParamField>

## Endpoint

```
POST https://api.pipellm.ai/v1beta/models/{model}:generateContent
```

<Note>
  这条 free route 只接受 Gemini 原生格式请求，并只路由到 Gemini 平台。如果你想
  保留 Gemini 格式去调用 OpenAI 或 Anthropic 模型，请使用
  [Gemini Format Converter](/zh/converter/gemini-format)。
</Note>

## 安装 SDK

```bash theme={"dark"}
pip install google-genai
```

## 代码示例

<Tabs>
  <Tab title="cURL">
    ```bash theme={"dark"}
    curl "https://api.pipellm.ai/v1beta/models/gemini-3-flash-preview:generateContent" \
      -H "Content-Type: application/json" \
      -H "x-goog-api-key: $PIPELLM_API_KEY" \
      -d '{
        "contents": [
          {
            "role": "user",
            "parts": [
              {"text": "Why is the sky blue?"}
            ]
          }
        ]
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={"dark"}
    import os
    from google import genai

    client = genai.Client(
      api_key=os.getenv('PIPELLM_API_KEY'),
      http_options={'base_url': 'https://api.pipellm.ai'}
    )

    response = client.models.generate_content(
      model='gemini-3-flash-preview',
      contents='Why is the sky blue?'
    )

    print(response.text)
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={"dark"}
    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-flash-preview',
      contents: 'Why is the sky blue?'
    });

    console.log(response.text);
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={"dark"}
    package main

    import (
      "context"
      "os"
      "github.com/google/generative-ai-go/genai"
      "google.golang.org/api/option"
    )

    func main() {
      ctx := context.Background()
      client, _ := genai.NewClient(ctx,
        option.WithAPIKey(os.Getenv("PIPELLM_API_KEY")),
        option.WithEndpoint("https://api.pipellm.ai"),
      )
      defer client.Close()

      model := client.GenerativeModel("gemini-3-flash-preview")
      resp, _ := model.GenerateContent(ctx,
        genai.Text("Why is the sky blue?"),
      )
    }
    ```
  </Tab>
</Tabs>

## 请求格式

```json theme={"dark"}
{
  "contents": [
    {
      "role": "user",
      "parts": [
        {"text": "Your message here"}
      ]
    }
  ],
  "generationConfig": {
    "temperature": 0.7,
    "maxOutputTokens": 1024
  }
}
```

## 响应格式

```json theme={"dark"}
{
  "candidates": [
    {
      "content": {
        "parts": [
          {"text": "The sky appears blue because..."}
        ],
        "role": "model"
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 10,
    "candidatesTokenCount": 50,
    "totalTokenCount": 60
  }
}
```

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

  <Expandable title="candidates[]">
    <ResponseField name="content" type="object">
      `role` 为 `model`。`parts` 里是 `text` 和/或 `inline_data`。
    </ResponseField>

    <ResponseField name="finishReason" type="string">
      通常是 `STOP`。
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usageMetadata" type="object">
  `promptTokenCount`、`candidatesTokenCount`、`totalTokenCount`。
</ResponseField>

## 错误

错误信封与 [错误](/zh/api-reference/errors) 相同。使用 `x-goog-api-key`。原生 Gemini 路由在请求体不是 Gemini 格式时返回 `400`。

<AccordionGroup>
  <Accordion title="400 invalid_request_error">
    缺少 `contents`、未知模型 ID，或协议不匹配。

    ```json theme={"dark"}
    {
      "error": {
        "type": "invalid_request_error",
        "code": "400",
        "message": "The 'model' field is required but was not provided in the request"
      }
    }
    ```
  </Accordion>

  <Accordion title="401 authentication_error">
    缺少或无效的 `x-goog-api-key`。

    ```json theme={"dark"}
    {
      "error": {
        "type": "authentication_error",
        "code": "401",
        "message": "Incorrect API key provided. Please visit https://console.pipellm.ai/account/api-keys to find your API key."
      }
    }
    ```
  </Accordion>

  <Accordion title="402 insufficient_balance">
    ```json theme={"dark"}
    {
      "error": {
        "type": "insufficient_balance",
        "code": "402",
        "message": "Insufficient balance. Please recharge your account at https://console.pipellm.ai/billing."
      }
    }
    ```
  </Accordion>

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

    ```json theme={"dark"}
    {
      "error": {
        "type": "rate_limit_error",
        "code": "429",
        "message": "Rate limit exceeded. Your current limit is 120 requests per minute (approximately 2.00 requests per second). Please visit https://console.pipellm.ai/billing to upgrade your plan for higher limits."
      }
    }
    ```
  </Accordion>
</AccordionGroup>

## 相关文档

<Columns cols={3}>
  <Card title="路由与协议" icon="route" href="/zh/guides/routing-protocols">
    查看原生路由约束和 converter 路由
  </Card>

  <Card title="Gemini 概述" icon="sparkles" href="/zh/api-reference/gemini/overview">
    查看 Header、模型和路由族说明
  </Card>

  <Card title="Gemini Format Converter" icon="shuffle" href="/zh/converter/gemini-format">
    保留 Gemini 格式，调用其他协议族模型
  </Card>
</Columns>


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