TokenLab

핵심 가이드

스트리밍

실시간 스트리밍 응답 구현

개요

스트리밍은 출력을 순차적으로 반환합니다. 모델의 accepted_request_formats에 openai_responses가 있으면 Responses를 사용할 수 있습니다. 기존 Chat Completions 클라이언트는 같은 형식을 유지할 수 있습니다.

권장: Responses Streaming

curl https://api.tokenlab.sh/v1/responses \
  -H "Authorization: Bearer sk-your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.6-terra",
    "input": "Write a short poem.",
    "stream": true
  }'

Responses 및 Gemini streaming 경계

Responses SSE는 공개된 이벤트 이름, 순서, 필드를 유지합니다. 출력 이후 연결이 끊긴 응답은 미완성이며 자동으로 다시 시작되지 않습니다.

Responses WebSocket은 response.create를 사용하며 항상 스트리밍됩니다. background와 response.cancel은 지원하지 않습니다. 연결당 한 번에 하나의 응답을 처리하고 최대 60분 동안 유지됩니다. generate: false는 이어가기 ID를 생성하며 모델 출력이나 모델 비용을 만들지 않습니다.

Gemini SSE는 네이티브 청크를 반환합니다. 중간 이벤트는 finishReason이 없을 수 있고 Chat의 [DONE] 없이 자연스럽게 끝날 수 있습니다.

Chat Completions 스트리밍

프레임워크가 여전히 /v1/chat/completions의 SSE 청크를 기대하는 경우에도 동작합니다:

import os
from openai import OpenAI

with OpenAI(
    api_key=os.environ["TOKENLAB_API_KEY"],
    base_url="https://api.tokenlab.sh/v1",
    timeout=30.0,
    max_retries=0,
) as client:
    finish_reason = None
    with client.chat.completions.create(
        model="gpt-5.6-terra",
        messages=[{"role": "user", "content": "Write a short poem."}],
        stream=True,
        stream_options={"include_usage": True},
    ) as stream:
        for chunk in stream:
            if not chunk.choices:
                continue
            choice = chunk.choices[0]
            if choice.delta.content:
                print(choice.delta.content, end="", flush=True)
            if choice.finish_reason:
                finish_reason = choice.finish_reason
    if finish_reason != "stop":
        raise RuntimeError(f"Stream ended without a complete text answer: {finish_reason}")

스트림 종료 조건

일반적인 완료 조건:

  • Responses API 스트림의 경우 response.completed
  • Chat Completions 스트림의 경우 finish_reason: "stop"
  • token 제한에 도달했을 때 finish_reason: "length"
  • 모델이 도구를 사용하려고 할 때의 tool/function call 이벤트

웹 앱 패턴

SDK 스트림 처리는 서버에서 실행하세요. 브라우저는 인증된 자체 백엔드를 호출하고 TokenLab 키는 서버 환경에 보관합니다. 텍스트 조각을 브라우저로 전달하고 사용자가 중지하거나 연결을 끊으면 상위 스트림을 취소하세요. SSE 이벤트는 SDK로 파싱하세요. 네트워크 청크 하나가 완전한 이벤트 하나인 것은 아닙니다.

모범 사례

이 페이지의 내용