How to set temperature in OpenAI API
Quick answer
Set the
temperature parameter in the OpenAI API's chat.completions.create method to control randomness in responses. A lower temperature (e.g., 0.0) makes output more deterministic, while a higher value (up to 2.0) increases creativity.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official OpenAI Python SDK and set your API key as an environment variable.
- Install SDK:
pip install openai - Set environment variable in your shell:
export OPENAI_API_KEY='your_api_key_here'
pip install openai Step by step
Use the temperature parameter in the chat.completions.create call to adjust randomness. Values range from 0.0 (most deterministic) to 2.0 (most creative). Here's a complete example:
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a creative poem about spring."}],
temperature=0.7
)
print(response.choices[0].message.content) output
A gentle breeze whispers through the trees, Spring awakens with vibrant ease. Blossoms dance in morning light, Nature's canvas, pure delight.
Common variations
You can adjust temperature for different use cases:
- Low temperature (0.0 - 0.3): Use for precise, factual answers.
- Medium temperature (0.4 - 0.7): Balanced creativity and coherence.
- High temperature (0.8 - 2.0): More creative, diverse outputs.
Also, you can use other models like gpt-4o-mini or async calls with the same parameter.
| Temperature range | Effect |
|---|---|
| 0.0 - 0.3 | Deterministic, factual responses |
| 0.4 - 0.7 | Balanced creativity and coherence |
| 0.8 - 2.0 | Creative and diverse outputs |
Troubleshooting
If you get repetitive or dull responses, increase the temperature. If output is too random or off-topic, lower it. Ensure your API key is set correctly in os.environ["OPENAI_API_KEY"] to avoid authentication errors.
Key Takeaways
- Set
temperatureinchat.completions.createto control output randomness. - Use lower temperatures for factual answers and higher for creative text.
- Always source your API key from
os.environfor security. - The
temperatureparameter accepts values from 0.0 to 2.0. - Adjust temperature based on your application's need for creativity versus precision.