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

SDK quirk — retry, streaming, cancellation

~12 min · providers, sdk

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

SDK가 prompt의 일부

SDK가 retry, streaming, cancellation, tool loop를 non-uniform한 방식으로 다뤄서 다른 SDK로 wrap되면 prompt가 다르게 행동. Cross-provider 코드의 production bug 가장 흔해.

Retry behavior

  • 대부분 SDK가 transient error에 exponential backoff로 retry. Default 다양.
  • 429에 retry는 보통 fine; tool call 동안 5xx에 retry는 side-effect double-execute 가능.
  • Non-idempotent operation에 SDK retry 비활성; idempotency key로 application 코드에 retry handle.

Streaming

  • Event shape 달라 — Anthropic의 content_block_delta가 OpenAI의 choices[0].delta 아니야.
  • Tool-call streaming이 argument piecewise emit; accumulate 필요.
  • Stream 중 error에 careful handling 필요 — 'connection closed'를 success로 trust X.

Cancellation

  • Stream close가 대부분 provider에서 billing 멈춰 — 진짜 close해야.
  • async generator 통한 asyncio cancellation이 Python에 known landmine; 각 chunk에 await, async generator를 asyncio.wait_for X.
  • Tool call 박힌 agent loop에 cancellation이 active tool에 propagate해야, 안 그러면 cleanup 결제 계속.

Code

Explicit cancellation 박힌 streaming (Python)·python
async def stream_response(req):
    async with client.messages.stream(**req) as stream:
        try:
            async for event in stream:
                yield event
        except asyncio.CancelledError:
            await stream.close()  # explicit close → server stops billing
            raise

External links

Exercise

한 provider에 cancellation 테스트. 긴 streaming call trigger, mid-stream cancel, (log / console에서) 토큰 billing 멈춘 거 verify. 안 멈췄으면 explicit close handling 추가.

Progress

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

댓글 0

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

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