huggingface_hub
AGENTS.md4k starsChanged 8 months agoApache-2.0View on GitHub
Python client library for the Hugging Face Hub. Source code is in src/huggingface_hub/, tests in tests/. Always run make style then make quality before committing.
Trending
Quiet this year.thin dataabout the whole repository
Who's talking about huggingface/huggingface_hub
- lllyasviel/IC-Light“【ImportError和推理Error】能打开可视化页面,但是推理图片时报 error 的一种可能的解决方法”GitHub · Dec 10, 2024 · 20 reactions
- kpu/kenlm“[WIP] Proof of concept of integration with Hugging Face Hub”GitHub · Sep 28, 2021 · 9 reactions
- huggingface/huggingface.js“PoC: `InferenceClient` is also a `McpClient`”GitHub · Apr 11, 2025 · 7 reactions
- huggingface/text-generation-inference“Implement logit_bias correctly”GitHub · Dec 28, 2024 · 7 reactions
- huggingface/diffusers“[FEAT] DDUF format”GitHub · Nov 27, 2024 · 7 reactions
The biggest 5 of 11 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 11
Talked about on GitHub (11 times).
On GitHub · 11
- Dec 10, 2024【ImportError和推理Error】能打开可视化页面,但是推理图片时报 error 的一种可能的解决方法 — lllyasviel/IC-Light20 reactions · 4 comments
- Sep 28, 2021[WIP] Proof of concept of integration with Hugging Face Hub — kpu/kenlm9 reactions · 1 comment
- Apr 11, 2025PoC: `InferenceClient` is also a `McpClient` — huggingface/huggingface.js7 reactions · 8 comments
- Dec 28, 2024Implement logit_bias correctly — huggingface/text-generation-inference7 reactions · 4 comments
- Nov 27, 2024[FEAT] DDUF format — huggingface/diffusers7 reactions · 18 comments
6 more on GitHub
- Dec 5, 2023Harmonize HF environment variables + deprecate use_auth_token — huggingface/diffusers7 reactions · 6 comments
- Dec 27, 2020huggingface model hub integration — espnet/espnet6 reactions · 17 comments
- May 21, 2024Use shard saving from huggingface_hub — huggingface/accelerate5 reactions · 5 comments
- Nov 11, 2023[Bug]: interpreted classes cannot inherit from compiled traits — dosisod/refurb5 reactions · 12 comments
- Mar 17, 2022feat: Added docTR as library filter — huggingface/hub-docs4 reactions · 2 comments
- Dec 15, 2021Use espnet/kan-bayashi_ljspeech_vits model via inference api — huggingface/api-inference-community4 reactions
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.
Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository2 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- hf-release-notesSkill
The file
We split this AGENTS.md into the rules it gives an agent
12 rules. About 0 are common, 4 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 78
Use pipe-separated aliases: @app.command("list | ls") registers both list and ls.
- Very specific: line 79
Use standard verb names: ls/list, info, create, set, delete, update.
- Very specific: line 102
Destructive operations: should use out.confirm() with a yes: Annotated[bool, typer.Option("-y", "--yes", help="Answer Yes to prompt …
- Very specific: line 108
Guides: update the CLI guide docs/sources/en/guides/cli.md when adding / updating CLI commands.
- Very specific: line 110
CLI tests: add tests in tests/test_cli.py.
- Very specific: line 120
If CI fails on type checks that pass locally, the likely cause is a newer ty version or a mypy-only diagnostic.
- Very specific: line 124
Commit message prefix: use [Area] prefix matching the scope, e.g.
- Distinctive: line 132
No premature abstractions.
- Distinctive: line 133
Don't implement features until they're actually needed.
- Distinctive: line 134
Don't accept parameters without a use case.
- Very specific: line 135
No redundant try/except - don't catch errors already handled up the call stack.
- Distinctive: line 136
Prefer strictness now, relax later.
≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Agent Guide for huggingface_hub
Project overview
Python client library for the Hugging Face Hub. Source code is in src/huggingface_hub/, tests in tests/.
Setup
- Virtualenv:
.venv(everything pre-installed in editable mode with dev extras). - Activate:
source .venv/bin/activate(or prefix commands with.venv/bin/python).
Key commands
| Command | What it does |
make style | Auto-format code (ruff format + fix), update generated files (static imports, __all__, async client, CLI reference) |
make quality | Check formatting, linting, generated files, and type-check (ty check src) |
pytest tests/test_<module>.py | Run a specific test file |
pytest tests/test_<module>.py -k "test_name" | Run a single test |
pytest tests/ | Run all tests (slow, many require network/auth) |
Always run make style then make quality before committing.
Code structure
Core modules (src/huggingface_hub/)
__init__.py— Public API surface. Static imports are auto-generated byutils/check_static_imports.py; runmake styleto update.hf_api.py— MainHfApiclass (~11k lines). Repo CRUD, uploads, downloads, discussions, PRs, collections, and more. Most Hub operations live here.file_download.py—hf_hub_download, caching logic, ETag/metadata resolution, xet download support._snapshot_download.py—snapshot_download(download an entire repo)._commit_api.py— Low-level commit operations (CommitOperationAdd,CommitOperationDelete,CommitOperationCopy), LFS upload handling._commit_scheduler.py— Background scheduled commits._upload_large_folder.py— Chunked upload for very large folders (deprecated;upload_foldernow handles large/resumable uploads).hf_file_system.py—HfFileSystem(fsspec-based POSIX-like filesystem for Hub repos).hub_mixin.py—ModelHubMixinbase class for ML framework integration (save/load to Hub).repocard.py/repocard_data.py—RepoCard,ModelCard,DatasetCardand their metadata.community.py—Discussion,DiscussionCommentand event deserialization.lfs.py— Git LFS batch upload utilities._login.py—login(),logout(),notebook_login(), token management._inference_endpoints.py— Inference endpoint CRUD and scaling._jobs_api.py— Training jobs API._space_api.py— Space runtime/hardware/storage types._webhooks_server.py/_webhooks_payload.py— Webhook server and payload definitions.constants.py— All environment-variable-driven constants (timeouts, cache paths, endpoints).errors.py— Custom exception hierarchy (HfHubHTTPError,RepositoryNotFoundError, etc.).
Inference (src/huggingface_hub/inference/)
_client.py—InferenceClient(very large, 40+ task methods). Async version is auto-generated byutils/generate_async_inference_client.py._generated/— Auto-generated type definitions for all inference tasks. Do not edit by hand; regenerate withutils/generate_inference_types.py._providers/— Provider adapters (24+):hf_inference,openai,cohere,together,fireworks,cerebras,fal,replicate, etc. Each maps the unified API to a provider's HTTP API._mcp/— Model Context Protocol integration (agent, client, CLI).
Utilities (src/huggingface_hub/utils/)
_http.py— HTTP client factory,http_backoff/http_stream_backoffretry helpers, header building._auth.py— Token retrieval from env/files/credential helpers._cache_manager.py— Cache browsing and deletion (scan-cache,delete-cacheCLI)._validators.py— Input validation decorators (@validate_hf_hub_args)._runtime.py— Runtime detection (is torch/tf/xet/etc. available?)._deprecation.py—@_deprecate_arguments,@_deprecate_methoddecorators._headers.py—build_hf_headers(user-agent, auth)._pagination.py— Paginated API response helpers.tqdm.py— Custom progress bar wrappers.- Other:
_datetime.py,_dotenv.py,_git_credential.py,_subprocess.py,_telemetry.py,sha.py,_xet.py, ...
CLI (src/huggingface_hub/cli/)
Entry point: hf.py (Typer app). Subcommands split into modules: auth.py, repos.py, spaces.py, models.py, datasets.py, buckets.py, jobs.py, collections.py, webhooks.py, etc.
Adding CLI commands
Structure & naming conventions:
- Commands are organized as Typer groups registered in
hf.py(e.g.app.add_typer(spaces_cli, name="spaces")). - Each module creates its app with
typer_factory(help="...")and defines commands with@app.command("name"). - Use pipe-separated aliases:
@app.command("list | ls")registers bothlistandls. - Use standard verb names:
ls/list,info,create,set,delete,update. - For sub-resources with multiple operations, create a nested subgroup:
volumes_cli = typer_factory(...)thenspaces_cli.add_typer(volumes_cli, name="volumes")→ giveshf spaces volumes ls/set/delete. Seerepos.pyfor examples (tag_cli,branch_cli).
Reusable option types (from _cli_utils.py — import and use these, don't reinvent):
TokenOpt,RepoIdArg,RepoTypeOpt,RevisionOpt— standard auth/repo options.SearchOpt,AuthorOpt,FilterOpt,LimitOpt— list/search options.FormatWithAutoOpt/FormatOpt— output format (auto|json|human|quiet|agent).VolumesOpt+parse_volumes()—-v/--volumeflag withhf://[TYPE/]SOURCE:/MOUNT_PATH[:ro]syntax.get_hf_api(token=token)— creates anHfApiinstance with token.api_object_to_dict(obj)— converts dataclass API objects to dicts for output.
Output (from _output.py — use the out singleton):
Convention: stderr for prompts/warnings, stdout for data. Warnings go to stderr even in quiet/json modes.
out.table(items)— list results (auto-formats as padded table / TSV / JSON depending on--format).out.dict(data)— single-item detail view.out.result("Message", key=value, ...)— success summary with green checkmark.out.confirm("Prompt?", yes=yes)— confirmation for destructive operations. Pair with a-y/--yesflag.out.hint("...")— actionable follow-up suggestion. Try to add hints when adding new commands or refactoring a command. Hints should preferably reuse the input args to be specific to the current use case. Example:out.hint(f"Use 'hf buckets ls {bucket_id}' to list files from the bucket.")after a bucket creation.out.text(),out.warning(),out.error()— free-form output.
Destructive operations should use out.confirm() with a yes: Annotated[bool, typer.Option("-y", "--yes", help="Answer Yes to prompt automatically.")] parameter.
Errors: raise CLIError("message") for user-facing errors. Never wrap API calls with try/except for RepositoryNotFoundError, RevisionNotFoundError, etc. (already done globally)
Generated docs: make style auto-regenerates docs/source/en/package_reference/cli.md via utils/generate_cli_reference.py. Don't edit that file by hand.
Guides: update the CLI guide docs/sources/en/guides/cli.md when adding / updating CLI commands. If the command is specific to a topic which has its own guide in docs/sources/en/guides, add a mention in the guide as well, using the same tone as the existing guide.
CLI tests: add tests in tests/test_cli.py. Try to group tests into classes when relevant. Do not add a test for each specific use case / parameter set. Usually testing the 1-2 main use cases is enough.
Type checking: local vs CI
Locally, make quality runs ty check src using whatever version of ty is installed in the virtualenv. CI (.github/workflows/python-quality.yml) runs uvx ty check src (always the latest ty release) and mypy src. This means CI may flag errors that do not appear locally — this is intentional.
ty: The local version is whatever the developer has installed — it won't update on its own, so newtyreleases don't unexpectedly break the workflow. Developers can update it at will. CI always uses the latest version to catch issues early.mypy: Historically the project's type checker. It is kept in CI (untiltyreaches a stable release) but not run locally viamake qualitybecause it takes 1–2 minutes, which slows down the development loop.
If CI fails on type checks that pass locally, the likely cause is a newer ty version or a mypy-only diagnostic. Fix the reported errors rather than downgrading the checker.
Commits & PRs
- Commit message prefix: use
[Area]prefix matching the scope, e.g.[CLI] Add ...,[CLI] Fix ...,[Inference] .... - PR title: short (under 70 chars), same
[Area]prefix convention. - PR description: keep it casual. Include a
## Summarywith a few bullet points and real CLI/code examples from manual testing (copy-paste terminal output). No need for a formal "Test plan" section. Call out breaking changes explicitly if any. It is important to document any decision taken in the PR or instructions provided in the prompt while working on the PR, ideally with the rationale behind it.
Code conventions
Simplicity is the #1 priority
- No premature abstractions. No unnecessary generalization.
- Don't implement features until they're actually needed.
- Don't accept parameters without a use case.
- No redundant
try/except- don't catch errors already handled up the call stack. - Prefer strictness now, relax later.
Follow Python 3.10+ idioms
match/caseoverif/elifchains when dispatching on a value.str | NonenotOptional[str].- f-strings over
.format()or%. - Walrus operator (
:=) when it improves readability. - Comprehensions over
map/filterwith lambdas.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

