處理 API 回應與錯誤

Amazon Bedrock 入門

Nikhil Rangarajan

Data Scientist

管理速率限制

  • 實作指數退避策略
  • 以智慧重試最佳化 API 使用
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))
Amazon Bedrock 入門

批次處理回應

  • 高效率處理多筆請求
  • 安全處理批次回應
  • 維持最佳效能
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]]
Amazon Bedrock 入門

回應後處理

  • 驗證回應結構
  • 載入並解析回應主體
  • 檢查預期鍵值
  • 確保資料品質一致
def postprocess_response(response):

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

錯誤復原

  • 實作後援策略:主要模型出問題時的備案
  • 處理模型特定錯誤
  • 確保生產等級可靠性
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")
Amazon Bedrock 入門

一起來練習吧!

Amazon Bedrock 入門

Preparing Video For Download...