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

Streaming output — partial JSON과 pipeline

~14 min · outputs, streaming

Level 0수련생
0 XP0/100 lessons0/14 achievements
0/120 XP to next level120 XP to go0% complete

Streaming이 parsing 문제 바꿔

Structured output stream하면 partial JSON 받아: {"verdict": "app… 등등. naïve json.loads()가 모든 chunk에 실패. Pipeline은 done까지 buffer하거나 streaming JSON parser로 incremental parse 필요.

왜 stream

  • UX — 8초 후가 아니라 200ms 안에 user한테 뭐 보여줘.
  • Pipelining — 마지막 후가 아니라 첫 complete field 후 downstream work 시작.
  • Cancellation — user가 navigate away하거나 verifier가 reject하자마자 request kill.

Streaming specific failure mode

  • JSON output 중간 truncation (max_tokens, network drop).
  • 조각으로 도착하는 tool call (start, delta, stop).
  • Output 토큰이랑 별도로 streaming하는 reasoning 토큰.
  • Cancellation race — consumer disconnect하면 너의 코드가 cancellation wire 안 하면 계속 돌아.

Code

Streaming JSON 안전하게·python
import json_stream

buffer = []
with client.messages.stream(
    model="claude-opus-4-7",
    messages=[...],
    response_format={"type": "json_object"},
) as stream:
    for delta in stream.text_stream:
        buffer.append(delta)
        # incremental: try to parse, ignore JSONDecodeError
        try:
            partial = json_stream.loads("".join(buffer))
            on_partial(partial)  # update UI as fields arrive
        except Exception:
            pass
final = json.loads("".join(buffer))

External links

Exercise

non-streaming structured-output endpoint를 streaming으로 convert. UI가 도착하는 field display하게. Cancellation 테스트: 200ms 안에 request가 토큰 billing 멈추는지 확인.

Progress

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

댓글 0

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

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