เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Implementing rate limit handling

TrailBlaze, an AI-powered adventure-travel booking platform, has recently developed a chat assistant that is getting a surge of itinerary questions whenever new flight deals drop. You’ll build a helper function that copes with Bedrock throttling by adding exponential back-off.

The json, time and boto3 libraries are preloaded. The bedrock client and model_id have also been preloaded.

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Introduction to Amazon Bedrock

ดูคอร์ส

คำแนะนำการฝึกหัด

  • Complete the API request string with the prompt.
  • Implement exponential backoff.

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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."))
แก้ไขและรันโค้ด