스트리밍 출력
요청에 "stream": true를 설정하면 응답이 Server-Sent Events(SSE) 방식으로 분할 반환되며,
채팅 인터페이스의 타이핑 효과 및 긴 응답 시나리오에 적합합니다.
요청
curl https://api.4allapi.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $AIPROXY_KEY" \ -d '{ "model": "gpt-5.6", "messages": [{"role": "user", "content": "写一首关于星空的短诗"}], "stream": true, "stream_options": {"include_usage": true} }'응답 스트림
각 이벤트는 data: 접두사가 붙은 JSON 한 줄이며, 증분 콘텐츠는
choices[0].delta.content에 포함됩니다. 스트림 종료 시 data: [DONE]이 전송됩니다:
data: {"choices":[{"delta":{"content":"夜"}}], ...}data: {"choices":[{"delta":{"content":"空"}}], ...}...data: {"choices":[],"usage":{"prompt_tokens":18,"completion_tokens":56,"total_tokens":74}}data: [DONE]SDK 예시(Python)
stream = client.chat.completions.create( model="gpt-5.6", messages=[{"role": "user", "content": "写一首关于星空的短诗"}], stream=True,)for chunk in stream: delta = chunk.choices[0].delta.content if chunk.choices else None if delta: print(delta, end="", flush=True)주의사항
- 스트리밍 연결의 읽기 타임아웃은 60초 이상으로 설정하는 것을 권장하며, 긴 응답을 처리하는 추론 모델의 경우 더 늘리는 것이 적절합니다;
- 클라이언트가 연결을 중단한 후에도 이미 생성된 부분은 실제 사용량에 따라 과금됩니다;
- 프록시/게이트웨이를 통해 전달할 때는 응답 버퍼링을 비활성화해야 합니다(예: nginx의
proxy_buffering off). 그렇지 않으면 스트리밍 효과가 사라집니다.