Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Introduction to Amazon Bedrock

Cursus bekijken

Oefeninstructies

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

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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."))
Code bewerken en uitvoeren