Processing model responses and error handling
In this exercise, you'll generate a response for a customer asking about updating their newsletter subscription. You'll also implement error handling to ensure the response is correctly parsed and truncated for concise display.
The json
library, bedrock
client, and request_body
have been pre-imported.
This exercise is part of the course
Introduction to Amazon Bedrock
Exercise instructions
- Check if the
'output'
key exists in the data dictionary. - Truncate the
'text'
response to the first 100 characters if it is longer.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
response = bedrock.invoke_model(modelId='amazon.nova-lite-v1:0', body=request_body)
data = json.loads(response['body'].read().decode())
# Check for the output key
if '____' in data:
# Truncate the response
response = data['output']['message']['content'][0]____
print(response)
else:
print('Key not found')