Gemini nativ

Inhalte streamen

Streamt die Inhaltsgenerierung im Google Gemini API-Format

POST
/v1beta/models/{model}:streamGenerateContent

SSE-Version von Gemini generateContent. Ereignisse können nur Metadaten oder Zwischeninhalte ohne finishReason enthalten. Der Stream endet mit natürlichem EOF und hängt keinen [DONE]-Marker an.

Pfadparameter

modelstringpatherforderlich

Modellname (z. B. gemini-2.5-pro, gemini-3.5-flash).

Abfrageparameter

keystringquery

API-Key (Alternative zur Header-Authentifizierung).

Anfrage-Body

Gleich wie Inhalte generieren.

Die Unterstützung von generationConfig.candidateCount, Tools, Medientypen und anderen optionalen Feldern hängt vom ausgewählten Modell ab.

Antwort

Gibt einen Stream von JSON-Objekten zurück, die jeweils eine Teilantwort enthalten.

Anfrage

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);

Vision-Eingabebeispiel

Streaming-Visionsanfragen verwenden dieselbe contents[].parts[]-Struktur wie der nicht-Streaming-Endpunkt.

{
  "contents": [
    {
      "role": "user",
      "parts": [
        { "text": "Please describe this image." },
        {
          "inline_data": {
            "mime_type": "image/jpeg",
            "data": "/9j/4AAQSkZJRgABAQ..."
          }
        }
      ]
    }
  ]
}

Antwort

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

Autorisierung

BearerAuth
AuthorizationBearer <token>

API-Key-Authentifizierung. Erstellen oder verwalten Sie API-Keys unter Dashboard > API > API Keys.

Ort: header

Pfadparameter

model*string

Modellname (z. B. gemini-2.5-pro)

Abfrageparameter

key?string

API-Schlüssel (Alternative zur Header-Authentifizierung)

Header

X-TokenLab-Delivery-Policy?string

Zustellungsrichtlinie pro Anfrage. Überschreibt die API-Key- und Workspace-Standardeinstellungen. Versucht automatisch zuerst TokenLab Verified und kann vor der Ausgabe, der Annahme der Anfrage oder der Erstellung persistenter Ressourcen einmalig auf Official umstellen.

Zulässige Werte

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

Anfragekörper

application/json

Native Gemini GenerateContent-Anfrage. ProtoJSON lowerCamelCase und originale proto snake_case-Namen werden beide akzeptiert und beibehalten, einschließlich gemischter Anfragen. Wenn beide Schreibweisen eines Feldes vorhanden sind, führt TokenLab keine Zusammenführung durch und wählt keine lokale Priorität. Unbekannte Felder werden nach bestem Bemühen weitergeleitet.

Antwort

text/event-stream

application/json

application/json

application/json

application/json

application/json