C.W.K.
Stream
Lesson 02 of 06 · published

Chat Completions Streaming — delta 라이프사이클

~22 min · streaming, chat-completions, delta

Level 0Tokenizer
0 XP0/54 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Chat Completions streaming 은 sequence 의 chunk 로 와. 첫 chunk 보통 delta.role: "assistant" 만 — 'I'm starting' signal. Mid-stream chunks 는 delta.content 점진적. 마지막 chunk 는 finish_reason + 빈 content. 그 다음 literal data: [DONE] 으로 stream 종료.

delta.content 가 None/empty 가능

첫 chunk 는 role 만, 마지막 chunk 는 finish_reason 만 carry 가능. Concat 전 항상 체크. if chunk.choices[0].delta.content: 가 표준 가드.

Tool-calling stream 은 다른 shape

Tool 사용 시 delta.tool_calls[i].function.arguments 가 JSON fragment 로 도착 — 개별로는 valid JSON 아냐. Concat, 그 다음 parse — Function Call Streaming lesson 에서 자세히.

Lifecycle 외워두면 디버깅 쉬워

매 chunk 마다 어떤 필드가 나오는지 그려보면 — role, content, finish_reason, [DONE] — streaming 디버깅에서 'why is content None?' 같은 질문이 사라져.

Code

delta.content iteration·python
stream = client.chat.completions.create(
    model="gpt-5.4",
    messages=[{"role": "user", "content": "Count from 1 to 5."}],
    stream=True,
    stream_options={"include_usage": True},  # get usage in final chunk
)

full_text = ""
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        delta = chunk.choices[0].delta.content
        full_text += delta
        print(delta, end="", flush=True)
    # Last chunk with usage
    if chunk.usage:
        print(f"\\nTokens: {chunk.usage.total_tokens}")
print(f"\\nFull response: {full_text}")

External links

Exercise

받는 모든 chunk print. role 이 어디 나타나는지, content 가 처음 non-empty 되는 곳, finish_reason 도착하는 곳, [DONE] 위치 메모. 종이에 lifecycle 그려.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.