การรับมือกับ Rate Limit
TrailBlaze คือแพลตฟอร์มจองทริปผจญภัยที่ขับเคลื่อนด้วย AI ซึ่งเพิ่งเปิดตัวแชทผู้ช่วยสำหรับตอบคำถามเกี่ยวกับแผนการเดินทาง โดยในช่วงที่มีดีลตั๋วเครื่องบินใหม่ออกมา ยอดคำถามที่เข้ามามักพุ่งสูงขึ้นอย่างรวดเร็ว คุณจะสร้างฟังก์ชันช่วยที่รับมือกับการถูก Bedrock จำกัดอัตราการเรียก (throttling) ด้วยการใช้ exponential backoff
ไลบรารี json, time และ boto3 ถูกโหลดไว้ล่วงหน้าแล้ว รวมถึง bedrock client และ model_id ด้วย
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Amazon Bedrock เบื้องต้น
คำแนะนำการฝึกหัด
- ระบุสตริงคำขอ API ให้ครบด้วย prompt
- เพิ่มการทำงานแบบ exponential backoff
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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."))