Get startedGet started for free

Making a conversation memory-aware

You're building a streamlined chatbot that needs to maintain conversation context with Amazon Bedrock's Claude model. The bot should efficiently manage message history and format the conversation in a way Claude can understand, using only the most recent context.

The boto3 and json libraries, and the ConversationManager class you defined in the previous exercise, have been preloaded.

This exercise is part of the course

Introduction to Amazon Bedrock

View Course

Exercise instructions

  • Use the add_message() method to store the user's input.
  • Send only the last two messages from the history to Claude using the correct message format.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

conversation = ConversationManager()

user_input = "Tell me about AWS services."

# Add the user input
conversation.____
# Send only the last two messages from conversation history
messages = ____

request_body = json.dumps({"anthropic_version": "bedrock-2023-05-31", "max_tokens": 200, "temperature": 0.2, "messages": messages})
response = conversation.bedrock.invoke_model(modelId="anthropic.claude-3-5-sonnet-20240620-v1:0", body=request_body)
completion = json.loads(response['body'].read().decode())["content"][0]["text"]

conversation.add_message("assistant", completion)
print(completion)
Edit and Run Code