Model-Fallbacks implementieren
Um einen 24/7‑Betrieb zu gewährleisten, muss TrailBlaze auf ein leichteres Modell zurückgreifen, wenn Claude nicht verfügbar ist. Implementiere einen Fallback von Claude auf Nova Text Lite bei auftretenden Problemen, damit die Reise-App durchgehend funktioniert.
Die Bibliotheken json und boto3 sowie der bedrock-Client sind vorab geladen.
Diese Übung ist Teil des Kurses
Einführung in Amazon Bedrock
Anleitung zur Übung
- Fasse den primären Aufruf des Claude-Modells in einen
try-Block. - Behandle im
except-Block Fehler mitClientErrorund rufe das Modell Nova Text Lite auf.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
def process_with_fallback(prompt):
# Handle errors with a try-except block
____:
response = bedrock.invoke_model(
modelId="anthropic.claude-3-5-sonnet-20240620-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="amazon.nova-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?"))