EnvironmentError
huggingface_hub.utils._errors.EnvironmentError
Stack trace
huggingface_hub.utils._errors.EnvironmentError: token required to access private model
File "/usr/local/lib/python3.9/site-packages/huggingface_hub/utils/_errors.py", line 45, in raise_for_status
raise EnvironmentError("token required to access private model")
File "/usr/local/lib/python3.9/site-packages/huggingface_hub/hf_api.py", line 123, in model_info
raise_for_status(response)
File "/usr/local/lib/python3.9/site-packages/huggingface_hub/hf_api.py", line 456, in model_info
return self._request(
File "/usr/local/lib/python3.9/site-packages/huggingface_hub/hf_api.py", line 400, in _request
raise EnvironmentError("token required to access private model") Why it happens
This error occurs because the Huggingface Hub requires an authentication token to access private models. Without setting the HF_TOKEN environment variable or passing a valid token, the API refuses access and raises this EnvironmentError.
Detection
Check for EnvironmentError exceptions when calling Huggingface Hub methods that fetch private models. Logging the exception message 'token required to access private model' helps identify missing authentication.
Causes & fixes
No HF_TOKEN environment variable set for authentication
Set the HF_TOKEN environment variable with a valid Huggingface access token before running the code.
Using Huggingface Hub API without passing the token parameter for private models
Pass the token explicitly to the API client or methods when accessing private models.
Expired or revoked Huggingface access token
Generate a new access token from Huggingface website and update the HF_TOKEN environment variable.
Code: broken vs fixed
from huggingface_hub import HfApi
api = HfApi()
model_info = api.model_info("private-user/private-model") # Raises EnvironmentError: token required import os
from huggingface_hub import HfApi
os.environ["HF_TOKEN"] = "your_valid_token_here" # Set your token securely
api = HfApi(token=os.environ["HF_TOKEN"])
model_info = api.model_info("private-user/private-model") # Works with token
print(model_info.modelId) Workaround
Catch EnvironmentError and prompt the user to set the HF_TOKEN environment variable or provide a token dynamically before retrying the request.
Prevention
Always store and load Huggingface access tokens securely in environment variables or secret managers and pass them explicitly when accessing private models.