Xử lý phản hồi API và lỗi

Giới thiệu về Amazon Bedrock

Nikhil Rangarajan

Data Scientist

Quản lý giới hạn tốc độ

  • Triển khai backoff lũy thừa
  • Tối ưu gọi API với retry thông minh
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))
Giới thiệu về Amazon Bedrock

Xử lý phản hồi theo lô

  • Xử lý nhiều yêu cầu hiệu quả
  • Xử lý phản hồi theo lô an toàn
  • Duy trì hiệu năng tối ưu
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]]
Giới thiệu về Amazon Bedrock

Hậu xử lý phản hồi

  • Xác thực cấu trúc phản hồi
  • Tải và phân tích nội dung phản hồi
  • Kiểm tra khóa mong đợi
  • Đảm bảo chất lượng dữ liệu nhất quán
def postprocess_response(response):

data=json.loads(response['body'] .read())
if 'content' in data: return data['content'].strip()
return None
Giới thiệu về Amazon Bedrock

Khôi phục lỗi

  • Triển khai chiến lược dự phòng khi mô hình chính gặp sự cố
  • Xử lý lỗi đặc thù theo mô hình
  • Đảm bảo độ tin cậy cấp sản xuất
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")
Giới thiệu về Amazon Bedrock

Ayo berlatih!

Giới thiệu về Amazon Bedrock

Preparing Video For Download...