How to set temperature in DeepSeek API
Quick answer
To set the temperature in the DeepSeek API, include the
temperature parameter in the chat.completions.create method call. This controls the randomness of the output, where lower values produce more focused responses and higher values increase creativity.PREREQUISITES
Python 3.8+DeepSeek API keypip install openai>=1.0
Setup
Install the openai Python package and set your DeepSeek API key as an environment variable.
- Install the package:
pip install openai - Set environment variable in your shell:
export DEEPSEEK_API_KEY='your_api_key'
pip install openai Step by step
Use the OpenAI client with base_url set to DeepSeek's API endpoint. Pass the temperature parameter to control response randomness.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["DEEPSEEK_API_KEY"], base_url="https://api.deepseek.com")
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "Write a creative story about a robot."}],
temperature=0.7
)
print(response.choices[0].message.content) output
Once upon a time, in a world where robots dreamed, there was one who longed to explore the stars...
Common variations
You can adjust the temperature value between 0 and 1 to control creativity. Use temperature=0 for deterministic output or values closer to 1 for more diverse responses. You can also change the model to deepseek-reasoner for reasoning tasks.
response = client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": "Explain quantum computing simply."}],
temperature=0.2
)
print(response.choices[0].message.content) output
Quantum computing uses quantum bits that can be in multiple states at once, allowing faster problem solving for certain tasks.
Troubleshooting
If you receive errors about invalid parameters, verify that temperature is a float between 0 and 1. Also, ensure your base_url is set correctly to https://api.deepseek.com and your API key is valid.
Key Takeaways
- Set
temperatureinchat.completions.createto control output randomness in DeepSeek. - Use values near 0 for focused, deterministic responses and near 1 for creative, diverse outputs.
- Always specify
base_url="https://api.deepseek.com"when using DeepSeek with the OpenAI SDK. - Validate your API key and parameter ranges to avoid request errors.