開始使用免費開始

實作流量限制處理

TrailBlaze 是一個以 AI 驅動的冒險旅遊訂位平台,最近新開發的聊天助理在每次推出新機票優惠時,行程相關問題就暴增。 你將撰寫一個輔助函式,透過加入指數退避來因應 Bedrock 節流(throttling)。

已預先載入 jsontimeboto3 函式庫。bedrock 用戶端與 model_id 也已預先載入。

本練習屬於課程

Amazon Bedrock 入門

檢視課程

練習說明

  • 在 API 請求字串中補上 prompt。
  • 實作指數退避。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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."))
編輯並執行程式碼