TokenLab

Gemini 原生

串流生成內容

使用 Google Gemini API 格式串流生成內容

POST
/v1beta/models/{model}:streamGenerateContent

Gemini generateContent 的 SSE 版本。事件可能只有 metadata,也可能是沒有 finishReason 的中間內容。串流在自然 EOF 時結束,不附加 [DONE] 標記。

路徑參數

modelstringpath必填

模型名稱(例如:gemini-2.5-pro、gemini-3.5-flash)。

查詢參數

keystringquery

API 金鑰(標頭驗證的替代方案)。

請求主體

與 生成內容 相同。

generationConfig.candidateCount、工具、媒體類型及其他可選欄位是否可用,以所選模型為準。

回應

返回 JSON 物件串流,每個物件包含部分回應。

請求

cURL
curl -N -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
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:
    for candidate in chunk.candidates:
        for part in candidate.content.parts:
            if part.text:
                print(part.text, end="")
JavaScript
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, { stream: true }));
}
Go
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
$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[] 結構。

{
  "contents": [
    {
      "role": "user",
      "parts": [
        { "text": "請描述這張圖片。" },
        {
          "inline_data": {
            "mime_type": "image/jpeg",
            "data": "/9j/4AAQSkZJRgABAQ..."
          }
        }
      ]
    }
  ]
}

回應

Stream Chunk
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {"text": "Once upon a time"}
        ]
      }
    }
  ]
}

授權

BearerAuth
AuthorizationBearer <token>

API Key 驗證。請在 Dashboard > API > API Keys 建立或管理 API 金鑰。

位置: header

路徑參數

model*string

模型名稱 (例如 gemini-2.5-pro)

查詢參數

key?string

API 金鑰 (標頭驗證的替代方案)

請求標頭

X-TokenLab-Delivery-Policy?string

單次請求傳遞策略。會覆寫 API key 與 Workspace 的預設值。系統會自動優先嘗試 TokenLab Verified,並可能在輸出、請求接受或建立持久性資源前切換至 Official 模式一次。

可選值

  • "auto"
  • "verified"
  • "official"

請求主體

application/json

原生的 Gemini GenerateContent 請求。ProtoJSON 的 lowerCamelCase 與原始 proto 的 snake_case 名稱皆可接受並會被保留,包含混合請求。若同一欄位同時存在兩種拼寫,TokenLab 不會合併它們或選擇本機優先順序。未知欄位將以盡力而為的方式轉發。

回應

text/event-stream

application/json

application/json

application/json

application/json

application/json