메인 콘텐츠로 건너뛰기

개요

스트리밍을 사용하면 생성되는 동안 부분 출력을 받을 수 있어, 체감 지연 시간과 사용자 경험이 개선됩니다. 새로운 OpenAI 스타일 통합의 경우, 먼저 Responses streaming을 사용하는 것을 권장합니다. 프레임워크가 여전히 Chat Completions streaming을 사용한다면, LemonData는 해당 호환 경로도 지원합니다.

권장: Responses Streaming

curl https://api.lemondata.cc/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
  }'

Chat Completions 스트리밍

프레임워크가 여전히 /v1/chat/completions의 SSE 청크를 기대하는 경우에도 동작합니다:
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 이벤트

웹 앱 패턴

async function streamChat(message) {
  const response = await fetch('https://api.lemondata.cc/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;
      }
    }
  }
}

모범 사례

SDK 또는 앱이 이미 이를 지원한다면 /v1/responses를 사용하세요. 호환성이 중요한 통합에는 /v1/chat/completions 스트리밍을 유지하세요.
전체 응답을 기다리기보다 delta 청크가 도착하는 대로 UI 또는 터미널에 추가하세요.
네트워크 끊김과 업스트림 연결 해제를 일반적인 실패 모드로 간주하고, 장시간 실행되는 세션에서는 신중하게 재연결하세요.