Handling API responses and errors

Introduction to Amazon Bedrock

Nikhil Rangarajan

Data Scientist

Managing rate limits

  • Implement exponential backoff strategy
  • Optimize API usage with smart retries
def backoff_retry(max_retries=3, 
                  init_delay=1):

for attempt in range(max_retries): try: response = bedrock.invoke_model()
# Retries when we have an exception except Exception as e: if "ThrottlingException" in str(e): # Exponential backoff time.sleep(base_delay * (2 ** attempt))
Introduction to Amazon Bedrock

Batch processing responses

  • Process multiple requests efficiently
  • Handle batch responses safely
  • Maintain optimal performance
def process_batch(prompts, batch=5):
  results = []
  for i in range(0, len(prompts), 
                 batch):
    responses = [invoke_model(p) for p 
                 in prompts[i:i+batch]]
Introduction to Amazon Bedrock

Response postprocessing

  • Validate response structure
  • Load and parse the response body
  • Check for expected key
  • Ensure consistent data quality
def postprocess_response(response):

data=json.loads(response['body'] .read())
if 'content' in data: return data['content'].strip()
return None
Introduction to Amazon Bedrock

Error recovery

  • Implement fallback strategies - a backup plan when primary model encounters issues
  • Handle model-specific errors
  • Ensure production-grade reliability
try:
    response = bedrock.invoke_model(modelId="anthropic.claude-3-5-sonnet-v2:0", 
        body=json.dumps(request_body))

except ClientError: response = bedrock.invoke_model(modelId="amazon.nova-lite-v1:0")
Introduction to Amazon Bedrock

Let's practice!

Introduction to Amazon Bedrock

Preparing Video For Download...