C.W.K.
Stream
Lesson 05 of 07 · published

Streaming — token 단위 delivery

~22 min · streaming, delta, async-iter

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

Streaming 은 magic 이 아니라 UX 야. 사용자는 첫 200ms 를 느껴. Non-streaming 3 초 호출은 broken 처럼 느껴지고, streaming 4 초인데 첫 token 이 300ms 에 오면 instant 처럼 느껴져. 사용자 향 텍스트는 항상 stream.

Sync vs Async iter

Sync 는 for chunk in stream:, async 는 async for chunk in stream:. 매 chunk 의 텍스트는 chunk.choices[0].delta.content — None 가능성 항상 체크 (첫 chunk 는 role 만, 마지막 chunk 는 finish_reason 만).

Stream 은 항상 close

Stream object 는 HTTP connection 을 들고 있어. with stream: / async with stream: 쓰거나 try/finally 에서 stream.close(). 여기서 leak 은 3 주 후 'production 이 connection cap 왜 친 거야' 가 됨.

stream 안 할 때

Backend pipeline 이 final string 만 필요하면 stream 안 해. 사람 눈이 wire 를 안 보면 streaming overhead (per-chunk 파싱, accumulator state) 가 buy 하는 게 0.

Code

Sync 'for chunk in stream' streaming·python
stream = client.chat.completions.create(
    model="gpt-5.4",
    messages=[{"role": "user", "content": "Write a haiku about autumn."}],
    stream=True,
)

for chunk in stream:
    delta = chunk.choices[0].delta
    if delta.content:
        print(delta.content, end="", flush=True)
print()  # newline at end
Async 'async for chunk in stream' streaming·python
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI()

async def stream_response():
    stream = await client.responses.create(
        model="gpt-5.4",
        input="Describe the solar system.",
        stream=True,
    )
    async for event in stream:
        if event.type == "response.output_text.delta":
            print(event.delta, end="", flush=True)

asyncio.run(stream_response())

External links

Exercise

500-word 응답 streaming 해서 first-token latency, last-token latency, total wall time 셋 다 측정. 셋을 plot. Stream=False 로 같은 프롬프트 비교.

Progress

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

댓글 0

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

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