TokenLab

Gemini 네이티브

콘텐츠 생성 스트리밍

Google Gemini API 형식을 사용하여 콘텐츠 생성을 스트리밍합니다.

POST
/v1beta/models/{model}:streamGenerateContent

Gemini generateContent의 SSE 버전입니다. 이벤트에는 메타데이터만 있거나 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": "Please describe this image." },
        {
          "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 키 인증입니다. Dashboard > API > API Keys에서 API 키를 생성하거나 관리하십시오.

위치: header

경로 매개변수

model*string

모델 이름 (예: gemini-2.5-pro)

쿼리 매개변수

key?string

API 키 (헤더 인증의 대안)

헤더

X-TokenLab-Delivery-Policy?string

요청별 전송 정책입니다. API 키 및 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