Adjusting creativity with temperature control
Adjust the temperature parameter to control the creativity of the Claude model to generate robot stories. Temperature control in language models is crucial because it determines how conservative or creative the model's responses will be. It helps you balance between getting consistent, reliable outputs for tasks (low temperature) versus generating creative content or brainstorming ideas (high temperature).
In this exercise, the boto3
and json
libraries, and the bedrock
client, have been pre-imported.
This exercise is part of the course
Introduction to Amazon Bedrock
Exercise instructions
- Generate two robot stories using a low temperature for the first output and a high temperature for the second output and observe how the outputs differ.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
def generate_story_with_temperature(bedrock, temperature):
messages = [{"role": "user",
"content": "Write a short story about a cooking robot teaching other robots to cook."}]
request_body=json.dumps({"anthropic_version": "bedrock-2023-05-31", "max_tokens": 100,
"temperature": temperature, "messages": messages})
response = bedrock.invoke_model(body=request_body, modelId='anthropic.claude-3-5-sonnet-20240620-v1:0')
response_body = json.loads(response.get('body').read().decode())
return response_body["content"][0]["text"]
# Test low and high temperature
low_temp = generate_story_with_temperature(bedrock, ____)
high_temp = generate_story_with_temperature(bedrock, ____)
print("Low temperature (more focused):", low_temp, "High temperature (more creative):", high_temp)