본문 바로가기
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 응답은 순서대로 오는 chunk 로 이루어져. 첫 chunk 에는 보통 delta.role: "assistant" 만 들어 있고, 중간 chunk 의 delta.content 에 새 텍스트가 담겨. 마지막 chunk 는 빈 content 와 finish_reason 을 보낸 뒤 literal data: [DONE] 으로 끝나.

delta.content 는 비어 있을 수 있어

첫 chunk 가 role 만, 마지막 chunk 가 finish_reason 만 담는 건 정상 동작이야. 텍스트를 이어 붙이기 전에 if chunk.choices[0].delta.content: 처럼 값이 있는지 확인해.

tool-calling stream 은 arguments 를 나눠 보내

도구를 사용할 때는 delta.tool_calls[i].function.arguments 에 JSON fragment 가 도착해. 각 fragment 는 완성된 JSON 이 아니므로 모두 이어 붙인 뒤 parsing 해야 해. 다음 lesson 에서 자세히 구현할 거야.

lifecycle 을 그려두면 디버깅이 쉬워져

role, content, finish_reason, [DONE] 이 어느 순서로 오는지 그려봐. content 가 None 인 이유와 stream 이 끝난 시점을 바로 찾을 수 있어.

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 를 출력해. role 이 나타나는 곳, content 가 처음 채워지는 곳, finish_reason 이 도착하는 곳, [DONE] 위치를 기록하고 lifecycle 을 그려.

Progress

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

댓글 0

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

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