시작하기무료로 시작하기

요청률 제한 처리 구현하기

AI 기반 모험 여행 예약 플랫폼인 TrailBlaze에서는 새로운 항공권 특가가 나올 때마다 일정 관련 문의가 급증하고 있어, 최근에 개발한 채팅 도우미가 많은 질문을 받고 있어요. 여러분은 지수 백오프를 추가해 Bedrock의 제한(스로틀링)에 대응하는 보조 함수를 만들게 됩니다.

json, time, boto3 라이브러리는 미리 로드되어 있습니다. bedrock 클라이언트와 model_id도 미리 로드되어 있어요.

이 연습은 강의의 일부입니다

Amazon Bedrock 입문

강의 보기

연습 안내

  • 프롬프트를 사용해 API 요청 문자열을 완성하세요.
  • 지수 백오프를 구현하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

def smart_retry(prompt, max_attempts=3):
  base_delay = 0.5
  
  for attempt in range(max_attempts):
    try:
      # Complete the API request string with the prompt
      response = bedrock.invoke_model(
        modelId=model_id,
        body=json.dumps({"anthropic_version": "bedrock-2023-05-31", "max_tokens": 100,
                         "messages": [{"role": "user", "content": [{"type": "text", "text": ____}]}]}))
      return json.loads(response["body"].read().decode())["content"][0]["text"]
    
    except Exception as e:
      if "ThrottlingException" in str(e):
        # Implement exponential backoff
        time.sleep(____)
      else: raise e
  return "Max retries exceeded"

print(smart_retry("Tell me about hiking in Patagonia."))
코드 편집 및 실행