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

# 流式生成内容

> 使用 Google Gemini API 格式流式传输内容生成

Gemini `generateContent` 接口的流式版本。返回服务器发送事件（Server-Sent Events）。

## 路径参数

<ParamField path="model" type="string" required>
  模型名称（例如，`gemini-2.5-pro`，`gemini-3.5-flash`）。
</ParamField>

## 查询参数

<ParamField query="key" type="string">
  API 密钥（标头身份验证的替代方案）。
</ParamField>

## 请求正文

与 [生成内容](/api-reference/gemini/generate-content) 相同。

流式请求请省略 `generationConfig.candidateCount` 或保持为 `1`；更大的值会被拒绝，而不会静默丢弃额外候选结果。

## 响应

返回一个 JSON 对象流，每个对象包含部分响应内容。

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST "https://api.tokenlab.sh/v1beta/models/gemini-2.5-pro:streamGenerateContent?key=sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "contents": [
        {
          "parts": [{"text": "Tell me a story"}]
        }
      ]
    }'
  ```

  ```python Python theme={null}
  import google.generativeai as genai

  genai.configure(
      api_key="sk-your-api-key",
      transport="rest",
      client_options={"api_endpoint": "api.tokenlab.sh"}
  )

  model = genai.GenerativeModel("gemini-2.5-pro")
  response = model.generate_content("Tell me a story", stream=True)

  for chunk in response:
      print(chunk.text, end="")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'https://api.tokenlab.sh/v1beta/models/gemini-2.5-pro:streamGenerateContent?key=sk-your-api-key',
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        contents: [{ parts: [{ text: 'Tell me a story' }] }]
      })
    }
  );

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    console.log(decoder.decode(value));
  }
  ```

  ```go Go theme={null}
  package main

  import (
      "bufio"
      "bytes"
      "encoding/json"
      "fmt"
      "net/http"
  )

  func main() {
      payload := map[string]interface{}{
          "contents": []map[string]interface{}{
              {"parts": []map[string]string{{"text": "Tell me a story"}}},
          },
      }

      jsonData, _ := json.Marshal(payload)
      req, _ := http.NewRequest("POST",
          "https://api.tokenlab.sh/v1beta/models/gemini-2.5-pro:streamGenerateContent?key=sk-your-api-key",
          bytes.NewBuffer(jsonData))
      req.Header.Set("Content-Type", "application/json")

      client := &http.Client{}
      resp, _ := client.Do(req)
      defer resp.Body.Close()

      scanner := bufio.NewScanner(resp.Body)
      for scanner.Scan() {
          fmt.Println(scanner.Text())
      }
  }
  ```

  ```php PHP theme={null}
  <?php
  $payload = [
      'contents' => [
          ['parts' => [['text' => 'Tell me a story']]]
      ]
  ];

  $ch = curl_init('https://api.tokenlab.sh/v1beta/models/gemini-2.5-pro:streamGenerateContent?key=sk-your-api-key');

  curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
      CURLOPT_POSTFIELDS => json_encode($payload),
      CURLOPT_WRITEFUNCTION => function($ch, $data) {
          echo $data;
          return strlen($data);
      }
  ]);

  curl_exec($ch);
  curl_close($ch);
  ```

  ## 图片输入示例

  流式视觉请求与非流式端点使用完全相同的 `contents[].parts[]` 结构。

  ```json theme={null}
  {
    "contents": [
      {
        "role": "user",
        "parts": [
          { "text": "请描述这张图片。" },
          {
            "inline_data": {
              "mime_type": "image/jpeg",
              "data": "/9j/4AAQSkZJRgABAQ..."
            }
          }
        ]
      }
    ]
  }
  ```
</RequestExample>

<ResponseExample>
  ```json Stream Chunk theme={null}
  {
    "candidates": [
      {
        "content": {
          "role": "model",
          "parts": [
            {"text": "Once upon a time"}
          ]
        }
      }
    ]
  }
  ```
</ResponseExample>
