연동

스트리밍

stream: true로 설정하면 생성되는 토큰을 SSE(Server-Sent Events)로 실시간 수신할 수 있습니다. 첫 토큰을 더 빨리 받을 수 있고, 긴 출력에서 클라이언트 타임아웃을 방지합니다.

curl https://api.link-io.cloud/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4.1-mini",
    "messages": [{"role": "user", "content": "Hello!"}],
    "stream": true
  }'

이벤트 형식

각 이벤트는 data: {JSON} 형식의 한 줄이며, 증분 텍스트는 choices[0].delta.content에 담깁니다. 스트림은 data: [DONE]으로 종료됩니다.

data: {"id":"chatcmpl-...","choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}

data: {"id":"chatcmpl-...","choices":[{"index":0,"delta":{"content":"Hel"}}]}

data: {"id":"chatcmpl-...","choices":[{"index":0,"delta":{"content":"lo!"},"finish_reason":"stop"}]}

data: [DONE]

스트림에서의 사용량

stream_options.include_usage를 설정하면 마지막 청크에 전체 요청의 usage가 포함됩니다.

stream = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[{"role": "user", "content": "Write a haiku about routers."}],
    stream=True,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:            # final chunk: empty choices, carries usage
        print("\n", chunk.usage)

알아두어야 할 점

  • 자체 리버스 프락시(예: Nginx)를 통해 스트림을 중계하는 경우 응답 버퍼링을 비활성화하세요(proxy_buffering off). 그렇지 않으면 콘텐츠가 마지막에 한꺼번에 도착합니다.
  • 스트림의 읽기 타임아웃은 요청 전체 시간이 아니라 청크 간 간격 기준으로 설정하세요.
  • 추론 모델은 첫 토큰이 나오기 전까지 한동안 사고할 수 있습니다. 정상적인 동작입니다.
  • Anthropic 형식의 스트림 이벤트는 Anthropic의 이벤트(message_start, content_block_delta 등)와 동일합니다. Anthropic 형식을 참고하세요.