Menu
CoddyTech

API 오류 처리하기

Coddy AI Engineering 여정의 코드에서 모델 호출하기 섹션에 포함된 레슨. 22개 중 12번째.

요청이 실패할 수 있으며, 실패할 경우 SDK는 예외를 발생시킵니다. 각 HTTP 오류에는 고유한 클래스가 있습니다: BadRequestError (400, 요청 자체가 잘못됨), AuthenticationError (401, 잘못된 키), NotFoundError (404, 예: 존재하지 않는 모델 ID), RateLimitError (429, 너무 많은 요청) 및 InternalServerError (500). 이들은 모두 APIStatusError의 서브클래스이며, status_code와 서버의 body를 포함합니다.

try:
    response = client.messages.create(
        model="claude-opus-5",
        max_tokens=999999,
        messages=[{"role": "user", "content": "Hi"}],
    )
except anthropic.BadRequestError as e:
    print(e.status_code)
    print(e.body["error"]["message"])
except anthropic.APIStatusError as e:
    print("Other API error:", e.status_code)

이것은 400과 메시지를 출력하며, 메시지에는 해당 모델의 제한이 128000이라고 나와 있습니다. 구체적인 클래스를 먼저 배치하세요. Python은 일치하는 첫 번째 except를 실행하며, APIStatusError는 이들 모두와 일치합니다.

SDK는 예외를 발생시키기 전에 429 또는 5xx 오류를 자체적으로 두 번 재시도합니다(이를 변경하려면 클라이언트에서 max_retries를 설정하세요). 400이나 404는 동일한 요청을 다시 보내도 똑같이 실패하므로 절대 재시도되지 않습니다.

challenge icon

챌린지

중급

프로그램이 비정상 종료되는 대신 요청 실패를 보고하도록 만드세요. 시작 코드는 모델 id, max_tokens 수, 질문을 읽어옵니다.

  1. 해당 model 및 max_tokens로 질문을 전송하세요. 정상적으로 작동하면 Answer: 와 답변 텍스트를 출력하세요.
  2. anthropic.NotFoundError 발생 시, Unknown model: <model>을 출력하세요.
  3. anthropic.BadRequestError 발생 시, Bad request (<status code>): <message>를 출력하세요. 여기서 메시지는 e.body["error"]["message"]입니다.
  4. 기타 모든 anthropic.APIStatusError 발생 시, API error <status code>를 출력하세요.

예를 들어, 입력 claude-opus-5-5, 200000, Hi에 대해 프로그램은 다음과 같이 출력합니다:

Bad request (400): max_tokens: 200000 > 128000, which is the maximum allowed number of output tokens for claude-opus-5-5

직접 해보기

import coddy_ai as anthropic  # 프로덕션 환경: import anthropic

client = anthropic.Anthropic()

model = input()
max_tokens = int(input())
question = input()

# 이 model과 max_tokens를 사용하여 질문을 전송합니다.
# 정상적으로 작동하면 "Answer: <text>"를 출력하고, 과제 지시사항에 따라 에러를 처리하세요.
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

코드에서 모델 호출하기의 모든 레슨

직접 연습해 보세요: 온라인 Python 컴파일러