ValueError
ollama.client.ValueError
Stack trace
Traceback (most recent call last):
File "app.py", line 12, in <module>
response = client.chat(model="llama2", messages=messages, temperature=1.5) # Invalid temperature
File "ollama/client.py", line 45, in chat
raise ValueError("Temperature must be between 0.0 and 1.0")
ValueError: Temperature must be between 0.0 and 1.0 Why it happens
Ollama's client enforces that the temperature parameter controlling randomness must be within a valid range, typically 0.0 to 1.0. Passing a value outside this range triggers a ValueError to prevent invalid model behavior.
Detection
Validate the temperature parameter before calling the Ollama client or catch ValueError exceptions to log and correct invalid temperature values before retrying.
Causes & fixes
Temperature parameter set above 1.0 or below 0.0
Ensure the temperature value is a float between 0.0 and 1.0 inclusive before passing it to the Ollama client.
Temperature parameter passed as a string or non-numeric type
Convert or cast the temperature parameter to a float type before passing it to the Ollama client.
Using default temperature value from an uninitialized variable or config error
Initialize and validate configuration values for temperature explicitly to avoid passing invalid defaults.
Code: broken vs fixed
import ollama
messages = [{"role": "user", "content": "Hello"}]
response = ollama.chat(model="llama2", messages=messages, temperature=1.5) # Invalid temperature causes ValueError
print(response) import ollama
messages = [{"role": "user", "content": "Hello"}]
# Fixed: temperature set within valid range 0.0 to 1.0
response = ollama.chat(model="llama2", messages=messages, temperature=0.7)
print(response) Workaround
Wrap the call in try/except ValueError, and if caught, clamp the temperature value to the nearest valid boundary (0.0 or 1.0) before retrying the request.
Prevention
Implement input validation for all model parameters including temperature before calling Ollama APIs, and use typed configuration management to avoid invalid values.