스트리밍 (SSE)
토큰을 실시간으로 흘려보내면 체감 지연이 크게 줄어듭니다(ChatGPT식). OpenAI 호환 stream: true.
클라이언트
stream = client.chat.completions.create(
model="qwen2.5-72b",
messages=[{"role": "user", "content": "긴 설명"}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="", flush=True)
const stream = await client.chat.completions.create({ model, messages, stream: true });
for await (const part of stream) process.stdout.write(part.choices[0]?.delta?.content ?? "");
원시 SSE 파싱 (SDK 없이)
- 각 줄이
data: {json}형식.data: [DONE]이면 종료. - 빈
delta(도구·역할만 있는 조각)는 건너뛰기.
⚠️ 프록시/게이트웨이 버퍼링 함정
스트림이 한 번에 몰려서 오면, 중간 프록시가 응답을 버퍼링하는 것입니다. 리버스 프록시에서:
Content-Type: text/event-stream을 그대로 패스스루.- 버퍼링 비활성: Nginx
proxy_buffering off;/ 헤더X-Accel-Buffering: no. - 애플리케이션 레벨에서 청크마다 flush.
프록시를 직접 만든다면, 응답 바디를 모으지 말고 바이트 단위로 즉시 전달하세요.
서버측 오케스트레이션 + 스트리밍
여러 단계(예: 추론 → 생성) 파이프라인에서도, 마지막 생성 단계만 스트리밍하면 사용자는 "생각 중… → 답변이 흘러나옴" 경험을 얻습니다. 중간 단계는 상태 표시로.
관련: 트러블슈팅 — 스트리밍