> ## 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.

# 스트리밍

> 실시간 스트리밍 응답 구현

## 개요

스트리밍을 사용하면 생성되는 동안 부분 출력을 받을 수 있어, 체감 지연 시간과 사용자 경험이 개선됩니다.

새로운 OpenAI 스타일 통합의 경우, 먼저 **Responses streaming**을 사용하는 것을 권장합니다. 프레임워크가 여전히 Chat Completions streaming을 사용한다면, TokenLab는 해당 호환 경로도 지원합니다.

## 권장: Responses Streaming

<CodeGroup>
  ```bash cURL theme={null}
  curl https://api.tokenlab.sh/v1/responses \
    -H "Authorization: Bearer sk-your-api-key" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "gpt-5.4",
      "input": "Write a short poem.",
      "stream": true
    }'
  ```

  ```python Python theme={null}
  from openai import OpenAI

  client = OpenAI(
      api_key="sk-your-api-key",
      base_url="https://api.tokenlab.sh/v1"
  )

  stream = client.responses.create(
      model="gpt-5.4",
      input="Write a short poem.",
      stream=True
  )

  for event in stream:
      if event.type == "response.output_text.delta":
          print(event.delta, end="", flush=True)
  ```

  ```javascript JavaScript theme={null}
  import OpenAI from 'openai';

  const client = new OpenAI({
    apiKey: 'sk-your-api-key',
    baseURL: 'https://api.tokenlab.sh/v1'
  });

  const stream = await client.responses.create({
    model: 'gpt-5.4',
    input: 'Write a short poem.',
    stream: true
  });

  for await (const event of stream) {
    if (event.type === 'response.output_text.delta') {
      process.stdout.write(event.delta);
    }
  }
  ```
</CodeGroup>

## Chat Completions 스트리밍

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

```python theme={null}
stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a short poem"}],
    stream=True
)

for chunk in stream:
    content = chunk.choices[0].delta.content
    if content:
        print(content, end="", flush=True)
```

## 스트림 종료 조건

일반적인 완료 조건:

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

## 웹 앱 패턴

```javascript theme={null}
async function streamChat(message) {
  const response = await fetch('https://api.tokenlab.sh/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk-your-api-key',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: message }],
      stream: true
    })
  });

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

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value);
    const lines = chunk.split('\\n').filter(line => line.startsWith('data: '));

    for (const line of lines) {
      const data = line.slice(6);
      if (data === '[DONE]') return;
      const parsed = JSON.parse(data);
      const content = parsed.choices?.[0]?.delta?.content;
      if (content) {
        document.getElementById('output').textContent += content;
      }
    }
  }
}
```

## 모범 사례

<AccordionGroup>
  <Accordion title="새로운 구축에는 Responses streaming을 우선 사용">
    SDK 또는 앱이 이미 이를 지원한다면 `/v1/responses`를 사용하세요. 호환성이 중요한 통합에는 `/v1/chat/completions` 스트리밍을 유지하세요.
  </Accordion>

  <Accordion title="출력을 점진적으로 flush">
    전체 응답을 기다리기보다 delta 청크가 도착하는 대로 UI 또는 터미널에 추가하세요.
  </Accordion>

  <Accordion title="연결 끊김 및 재시도 처리">
    네트워크 끊김과 업스트림 연결 해제를 일반적인 실패 모드로 간주하고, 장시간 실행되는 세션에서는 신중하게 재연결하세요.
  </Accordion>
</AccordionGroup>
