How to beginner · 3 min read

How to set temperature in Claude API

Quick answer
To set the temperature in the Claude API, use the max_tokens and temperature parameters in the client.messages.create() call. The temperature parameter controls randomness, where lower values produce more focused responses and higher values increase creativity.

PREREQUISITES

  • Python 3.8+
  • Anthropic API key
  • pip install anthropic>=0.20

Setup

Install the anthropic Python package and set your API key as an environment variable.

  • Install the SDK: pip install anthropic>=0.20
  • Set environment variable: export ANTHROPIC_API_KEY='your_api_key' (Linux/macOS) or set ANTHROPIC_API_KEY=your_api_key (Windows)
bash
pip install anthropic>=0.20

Step by step

Use the temperature parameter in the client.messages.create() method to control the randomness of Claude's responses. Values range from 0 (deterministic) to 1 (more creative). Here's a complete example:

python
import os
import anthropic

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=300,
    temperature=0.7,
    system="You are a helpful assistant.",
    messages=[{"role": "user", "content": "Explain the benefits of setting temperature."}]
)

print(response.content[0].text)
output
The temperature parameter controls the randomness of the AI's responses. Lower values make the output more focused and deterministic, while higher values increase creativity and variability.

Common variations

You can adjust temperature for different use cases:

  • Low temperature (0-0.3): For precise, factual answers.
  • Medium temperature (0.4-0.7): Balanced creativity and accuracy.
  • High temperature (0.8-1.0): For creative writing or brainstorming.

Also, you can use other Claude models by changing the model parameter, e.g., claude-3-opus-20240229.

Troubleshooting

If you get unexpected repetitive or generic responses, try lowering the temperature value. If responses seem too random or off-topic, reduce temperature below 0.7. Ensure your API key is correctly set in os.environ["ANTHROPIC_API_KEY"] to avoid authentication errors.

Key Takeaways

  • Set temperature in client.messages.create() to control response randomness.
  • Lower temperature values yield more focused, deterministic answers.
  • Higher temperature values increase creativity and variability in responses.
Verified 2026-04 · claude-3-5-sonnet-20241022, claude-3-opus-20240229
Verify ↗