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

Error Handling — retry 룰

~22 min · errors, retries, exceptions

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

Retry 는 시간이 고쳐줄 에러만. RetryableRateLimitError (429), APIConnectionError (network blip), 5xx server error. Non-retryable — 400 (bad request), 401 (auth), 404, 422. Non-retryable retry 는 같은 벽 다시 치는 거.

tenacity 가 right primitive

@retry(retry=retry_if_exception_type((openai.RateLimitError, openai.APIConnectionError)), wait=wait_exponential_jitter(initial=1, max=20), stop=stop_after_attempt(5)) — 합리적 default. 401 도 retry 박는 코드는 같은 벽 5 번 치고 끝.

Exception class 정확히 보기

SDK 는 APIError 를 base 로 하고 그 아래 APIStatusError, RateLimitError, APIConnectionError 등을 둬. Bare except Exception 은 KeyboardInterrupt 까지 잡아서 디버깅을 망쳐. 정확한 class 로 잡아.

Logging 을 retry hook 에

매 retry 마다 attempt 번호와 실제 wait 를 log. Production 에서 'why is it slow' 답이 나옴 — '실제로 5 번 retry 중이었어' 가 가장 흔한 답.

Code

APIStatusError vs APIError 잡기·python
import openai
from openai import OpenAI

client = OpenAI()

try:
    response = client.responses.create(
        model="gpt-5.4", input="Hello!",
    )
except openai.AuthenticationError as e:
    print(f"Auth error: {e}")         # 401
except openai.PermissionDeniedError:
    print("Permission denied")        # 403
except openai.NotFoundError:
    print("Model not found")          # 404
except openai.BadRequestError as e:
    print(f"Bad request: {e.message}") # 400
except openai.RateLimitError as e:
    retry = e.response.headers.get("retry-after")
    print(f"Rate limited, retry after: {retry}")  # 429
except openai.InternalServerError:
    print("Server error")             # 500+
except openai.APIConnectionError as e:
    print(f"Connection error: {e.__cause__}")
except openai.APITimeoutError:
    print("Request timed out")
tenacity 로 retry policy·text
openai.APIError
├── openai.APIConnectionError
│   └── openai.APITimeoutError
├── openai.APIStatusError
│   ├── openai.BadRequestError           (400)
│   ├── openai.AuthenticationError       (401)
│   ├── openai.PermissionDeniedError     (403)
│   ├── openai.NotFoundError             (404)
│   ├── openai.RateLimitError            (429)
│   └── openai.InternalServerError       (500+)

External links

Exercise

retry_chat(messages) — RateLimitError, APIConnectionError, 5xx 에 retry, exponential jitter, max 5 attempt. Request spam 으로 일부러 429 trigger 해서 backoff 가 진짜 wait 하는지 검증.

Progress

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

댓글 0

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

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