ImportError: cannot import name 'HfApi' from 'transformers'
Fixes `from transformers import HfApi` by importing from huggingface_hub. Use when the error names HfApi. Not for other missing names or a missing huggingface_hub install.
TL;DR: Import it from huggingfacehub instead: `from huggingfacehub import HfApi`. HfApi never lived in transformers in recent versions; old tutorials and code samples still show the old import. Install/upgrade huggingface_hub if needed.
The error:
ImportError: cannot import name 'HfApi' from 'transformers' (.../transformers/__init__.py)Fix
Replace
from transformers import HfApiwithfrom huggingface_hub import HfApiExpected: no ImportErrorIf that fails,
python -m pip install -U huggingface_hubExpected: Successfully installed huggingface_hubVerify:
python -c "from huggingface_hub import HfApi; print('ok')"Expected: prints ok
When this applies
- cannot import name 'HfApi' from 'transformers'
- code copied from an old tutorial using the transformers import
When this does not apply
- No module named 'huggingface_hub' (install it)
- other names failing to import from transformers (check the real module)
Version compatibility
transformers 4.x any recent version. HfApi moved to huggingface_hub years ago; very old transformers (3.x) did re-export it.
Why it happens
HfApi is the Hub client and lives in the huggingface_hub package. transformers stopped re-exporting it, so the old import path raises ImportError while the new one works.
Edge cases
- Other moved names:
from huggingface_hub import HfFolder, login, snapshot_download. - transformers pins a minimum huggingface_hub version; upgrading both together avoids weirdness.
- If a third-party library does the old import, upgrade the library or pin transformers to a version that still re-exports.