การสร้างระบบ Fallback ระหว่างโมเดล
เพื่อให้บริการได้ตลอด 24/7 TrailBlaze ต้องสลับไปใช้โมเดลที่เบากว่าเมื่อ Claude ไม่พร้อมใช้งาน ให้ implement ระบบ fallback จาก Claude ไปยัง Nova Text Lite เมื่อเกิดปัญหาขึ้น เพื่อให้แอปท่องเที่ยวให้บริการได้อย่างต่อเนื่อง
ไลบรารี json และ boto3 รวมถึง bedrock client ถูกโหลดไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Amazon Bedrock เบื้องต้น
คำแนะนำการฝึกหัด
- ครอบการเรียกโมเดล Claude หลักด้วยบล็อก
try - ในบล็อก
exceptให้จัดการข้อผิดพลาดโดยใช้ClientErrorและเรียกโมเดล Nova Text Lite แทน
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
def process_with_fallback(prompt):
# Handle errors with a try-except block
____:
response = bedrock.invoke_model(
modelId="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
body=json.dumps({"anthropic_version": "bedrock-2023-05-31", "max_tokens": 100,
"messages": [{"role": "user", "content": [{"type": "text", "text": prompt}]}]}))
return json.loads(response["body"].read().decode())["content"][0]["text"]
except ____:
fallback = bedrock.invoke_model(
modelId="us.amazon.nova-2-lite-v1:0",
body=json.dumps({"messages": [{"role": "user", "content": [{"text": prompt}]}]}))
return json.loads(fallback["body"].read().decode())["output"]["message"]["content"][0]["text"]
print(process_with_fallback("What are the best destinations in Australia for kayaking?"))