skills.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. # Copyright 2025 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains commands to manage skills for AI assistants.
  15. Usage:
  16. # install the hf-cli skill in common .agents/skills directory (either in current directory or user-level)
  17. hf skills add
  18. hf skills add --global
  19. # install the hf-cli skill for Claude (project-level, in current directory)
  20. hf skills add --claude
  21. # install globally (user-level)
  22. hf skills add --claude --global
  23. # install to a custom directory
  24. hf skills add --dest=~/my-skills
  25. # overwrite an existing skill
  26. hf skills add --claude --force
  27. """
  28. import os
  29. import shutil
  30. from pathlib import Path
  31. from typing import Annotated
  32. import typer
  33. from click import Command, Context, Group
  34. from typer.main import get_command
  35. from huggingface_hub.errors import CLIError
  36. from . import _skills
  37. from ._cli_utils import typer_factory
  38. DEFAULT_SKILL_ID = "hf-cli"
  39. _SKILL_DESCRIPTION = (
  40. "Hugging Face Hub CLI (`hf`) for downloading, uploading, and managing"
  41. " models, datasets, spaces, buckets, repos, papers, jobs, and more on the Hugging Face Hub."
  42. " Use when: handling authentication;"
  43. " managing local cache;"
  44. " managing Hugging Face Buckets;"
  45. " running or scheduling jobs on Hugging Face infrastructure;"
  46. " managing Hugging Face repos;"
  47. " discussions and pull requests;"
  48. " browsing models, datasets and spaces;"
  49. " reading, searching, or browsing academic papers;"
  50. " managing collections;"
  51. " querying datasets;"
  52. " configuring spaces;"
  53. " setting up webhooks;"
  54. " or deploying and managing HF Inference Endpoints."
  55. " Make sure to use this skill whenever the user mentions"
  56. " 'hf', 'huggingface', 'Hugging Face', 'huggingface-cli', or 'hugging face cli',"
  57. " or wants to do anything related to the Hugging Face ecosystem and to AI and ML in general."
  58. " Also use for cloud storage needs like training checkpoints, data pipelines, or agent traces."
  59. " Use even if the user doesn't explicitly ask for a CLI command."
  60. " Replaces the deprecated `huggingface-cli`."
  61. )
  62. _SKILL_YAML_PREFIX = f"""\
  63. ---
  64. name: hf-cli
  65. description: "{_SKILL_DESCRIPTION}"
  66. ---
  67. Install: `curl -LsSf https://hf.co/cli/install.sh | bash -s`.
  68. The Hugging Face Hub CLI tool `hf` is available. IMPORTANT: The `hf` command replaces the deprecated `huggingface-cli` command.
  69. Use `hf --help` to view available functions. Note that auth commands are now all under `hf auth` e.g. `hf auth whoami`.
  70. """
  71. _SKILL_TIPS = """
  72. ## Mounting repos as local filesystems
  73. To mount Hub repositories or buckets as local filesystems — no download, no copy, no waiting — use `hf-mount`. Files are fetched on demand. GitHub: https://github.com/huggingface/hf-mount
  74. Install: `curl -fsSL https://raw.githubusercontent.com/huggingface/hf-mount/main/install.sh | sh`
  75. Some command examples:
  76. - `hf-mount start repo openai-community/gpt2 /tmp/gpt2` — mount a repo (read-only)
  77. - `hf-mount start --hf-token $HF_TOKEN bucket myuser/my-bucket /tmp/data` — mount a bucket (read-write)
  78. - `hf-mount status` / `hf-mount stop /tmp/data` — list or unmount
  79. ## Tips
  80. - Use `hf <command> --help` for full options, descriptions, usage, and real-world examples
  81. - Authenticate with `HF_TOKEN` env var (recommended) or with `--token`
  82. """
  83. CENTRAL_LOCAL = Path(".agents/skills")
  84. CENTRAL_GLOBAL = Path("~/.agents/skills")
  85. CLAUDE_LOCAL = Path(".claude/skills")
  86. CLAUDE_GLOBAL = Path("~/.claude/skills")
  87. # Flags worth explaining in the common-options glossary. Self-explanatory flags
  88. # (--namespace, --yes, --private, …) are omitted even if they appear frequently.
  89. _COMMON_FLAG_ALLOWLIST = {"--token", "--quiet", "--type", "--format", "--revision"}
  90. # Keep token out of inline command signatures to encourage env based auth.
  91. _INLINE_FLAG_EXCLUDE = {"--token"}
  92. _COMMON_FLAG_HELP_OVERRIDES: dict[str, str] = {
  93. "--format": "Output format: `--format json` (or `--json`) or `--format table` (default).",
  94. "--token": "Use a User Access Token. Prefer setting `HF_TOKEN` env var instead of passing `--token`.",
  95. }
  96. skills_cli = typer_factory(help="Manage skills for AI assistants.")
  97. def _format_params(cmd: Command) -> str:
  98. """Format required params: positional as UPPER_CASE, options as ``--name TYPE``."""
  99. parts = []
  100. for p in cmd.params:
  101. if not p.required or p.human_readable_name == "--help":
  102. continue
  103. if p.name and p.name.startswith("_"):
  104. continue
  105. long_name = next((o for o in getattr(p, "opts", []) if o.startswith("--")), None)
  106. if long_name is not None:
  107. type_name = getattr(p.type, "name", "").upper() or "VALUE"
  108. parts.append(f"{long_name} {type_name}")
  109. elif p.name:
  110. parts.append(p.human_readable_name)
  111. return " ".join(parts)
  112. def _collect_leaf_commands(group: Group, ctx: Context, path_parts: list[str]) -> list[tuple[list[str], Command]]:
  113. """Recursively walk a Click Group, returning (full_path_parts, cmd) for every leaf command."""
  114. leaves: list[tuple[list[str], Command]] = []
  115. sub_ctx = Context(group, parent=ctx, info_name=path_parts[-1])
  116. for name in group.list_commands(sub_ctx):
  117. cmd = group.get_command(sub_ctx, name)
  118. if cmd is None or cmd.hidden:
  119. continue
  120. child_path = [*path_parts, name]
  121. if isinstance(cmd, Group):
  122. leaves.extend(_collect_leaf_commands(cmd, sub_ctx, child_path))
  123. else:
  124. leaves.append((child_path, cmd))
  125. return leaves
  126. def _iter_optional_params(cmd: Command):
  127. """Yield (param, long_name, short_name) for each optional, non-internal param."""
  128. for p in cmd.params:
  129. if p.required or p.human_readable_name == "--help":
  130. continue
  131. if p.name and p.name.startswith("_"):
  132. continue
  133. long_name = None
  134. short_name = None
  135. for opt in getattr(p, "opts", []):
  136. if opt.startswith("--"):
  137. long_name = long_name or opt
  138. elif opt.startswith("-"):
  139. short_name = opt
  140. if long_name:
  141. yield p, long_name, short_name
  142. def _get_flag_names(cmd: Command, *, exclude: set[str] | None = None) -> list[str]:
  143. """Return long-form flag names (--foo) for optional, non-internal params.
  144. Boolean flags are bare (``--dry-run``). Value-taking options include a
  145. type hint (``--include TEXT``, ``--max-workers INTEGER``).
  146. """
  147. flags: list[str] = []
  148. for p, long_name, _short in _iter_optional_params(cmd):
  149. if exclude and long_name in exclude:
  150. continue
  151. if getattr(p, "is_flag", False):
  152. flags.append(long_name)
  153. else:
  154. type_name = getattr(p.type, "name", "").upper() or "VALUE"
  155. flags.append(f"{long_name} {type_name}")
  156. return flags
  157. def _compute_common_flags(
  158. leaf_commands: list[tuple[list[str], Command]],
  159. ) -> dict[str, tuple[str, str]]:
  160. """Collect display info for flags in the allowlist."""
  161. flag_info: dict[str, tuple[str, str]] = {}
  162. for _path, cmd in leaf_commands:
  163. for p, long_name, short_name in _iter_optional_params(cmd):
  164. if long_name not in _COMMON_FLAG_ALLOWLIST:
  165. continue
  166. # Prefer the version with a short form (e.g. "-q / --quiet" over just "--quiet")
  167. if long_name not in flag_info or (short_name and " / " not in flag_info[long_name][0]):
  168. display = f"{short_name} / {long_name}" if short_name else long_name
  169. help_text = (getattr(p, "help", None) or "").split("\n")[0].strip()
  170. flag_info[long_name] = (display, help_text)
  171. return flag_info
  172. def _render_leaf(path_parts: list[str], cmd: Command) -> str:
  173. """Render a single leaf command as a markdown list entry."""
  174. help_text = (cmd.help or "").split("\n")[0].strip()
  175. params = _format_params(cmd)
  176. parts = ["hf", *path_parts] + ([params] if params else [])
  177. entry = f"- `{' '.join(parts)}` — {help_text}"
  178. flags = _get_flag_names(cmd, exclude=_INLINE_FLAG_EXCLUDE)
  179. if flags:
  180. entry += f" `[{' '.join(flags)}]`"
  181. return entry
  182. def build_skill_md() -> str:
  183. # Lazy import to avoid circular dependency (hf.py imports skills_cli from this module)
  184. from huggingface_hub import __version__
  185. from huggingface_hub.cli.hf import app
  186. click_app = get_command(app)
  187. ctx = Context(click_app, info_name="hf")
  188. top_level: list[tuple[list[str], Command]] = []
  189. groups: list[tuple[str, Group]] = []
  190. for name in sorted(click_app.list_commands(ctx)): # type: ignore[attr-defined]
  191. cmd = click_app.get_command(ctx, name) # type: ignore[attr-defined]
  192. if cmd is None or cmd.hidden:
  193. continue
  194. if isinstance(cmd, Group):
  195. groups.append((name, cmd))
  196. else:
  197. top_level.append(([name], cmd))
  198. group_leaves: list[tuple[str, list[tuple[list[str], Command]]]] = []
  199. all_leaf_commands: list[tuple[list[str], Command]] = list(top_level)
  200. for name, group in groups:
  201. leaves = _collect_leaf_commands(group, ctx, [name])
  202. group_leaves.append((name, leaves))
  203. all_leaf_commands.extend(leaves)
  204. common_flags = _compute_common_flags(all_leaf_commands)
  205. # wrap in list to widen list[LiteralString] -> list[str] for `ty`
  206. lines: list[str] = list(_SKILL_YAML_PREFIX.splitlines())
  207. lines.append("")
  208. lines.append(f"Generated with `huggingface_hub v{__version__}`. Run `hf skills add --force` to regenerate.")
  209. lines.append("")
  210. lines.append("## Commands")
  211. lines.append("")
  212. for path_parts, cmd in top_level:
  213. lines.append(_render_leaf(path_parts, cmd))
  214. groups_dict = dict(groups)
  215. for name, leaves in group_leaves:
  216. group_cmd = groups_dict[name]
  217. help_text = (group_cmd.help or "").split("\n")[0].strip()
  218. lines.append("")
  219. lines.append(f"### `hf {name}` — {help_text}")
  220. lines.append("")
  221. for path_parts, cmd in leaves:
  222. lines.append(_render_leaf(path_parts, cmd))
  223. if common_flags:
  224. lines.append("")
  225. lines.append("## Common options")
  226. lines.append("")
  227. for long_name, (display, help_text) in sorted(common_flags.items()):
  228. help_text = _COMMON_FLAG_HELP_OVERRIDES.get(long_name, help_text)
  229. if help_text:
  230. lines.append(f"- `{display}` — {help_text}")
  231. else:
  232. lines.append(f"- `{display}`")
  233. lines.extend(_SKILL_TIPS.splitlines())
  234. return "\n".join(lines)
  235. def _remove_existing(path: Path, force: bool) -> None:
  236. """Remove existing file/directory/symlink if force is True, otherwise raise an error."""
  237. if not (path.exists() or path.is_symlink()):
  238. return
  239. if not force:
  240. raise CLIError(f"Skill already exists at {path}.\nRe-run with --force to overwrite.")
  241. if path.is_dir() and not path.is_symlink():
  242. shutil.rmtree(path)
  243. else:
  244. path.unlink()
  245. def _install_to(skills_dir: Path, skill_name: str, force: bool) -> Path:
  246. """Install a marketplace skill into a skills directory. Returns the installed path."""
  247. skill = _skills.get_marketplace_skill(skill_name)
  248. try:
  249. return _skills.install_marketplace_skill(skill, skills_dir, force=force)
  250. except FileExistsError as exc:
  251. raise CLIError(f"{exc}\nRe-run with --force to overwrite.") from exc
  252. def _create_symlink(agent_skills_dir: Path, skill_name: str, central_skill_path: Path, force: bool) -> Path:
  253. """Create a relative symlink from agent directory to the central skill location."""
  254. agent_skills_dir = agent_skills_dir.expanduser().resolve()
  255. agent_skills_dir.mkdir(parents=True, exist_ok=True)
  256. link_path = agent_skills_dir / skill_name
  257. _remove_existing(link_path, force)
  258. link_path.symlink_to(os.path.relpath(central_skill_path, agent_skills_dir))
  259. return link_path
  260. def _resolve_update_roots(
  261. *,
  262. claude: bool,
  263. global_: bool,
  264. dest: Path | None,
  265. ) -> list[Path]:
  266. if dest is not None:
  267. if claude or global_:
  268. raise CLIError("--dest cannot be combined with --claude or --global.")
  269. return [dest.expanduser().resolve()]
  270. roots: list[Path] = [CENTRAL_GLOBAL if global_ else CENTRAL_LOCAL]
  271. if claude:
  272. roots.append(CLAUDE_GLOBAL if global_ else CLAUDE_LOCAL)
  273. return [root.expanduser().resolve() for root in roots]
  274. @skills_cli.command("preview")
  275. def skills_preview() -> None:
  276. """Print the generated `hf-cli` SKILL.md to stdout."""
  277. print(build_skill_md())
  278. @skills_cli.command(
  279. "add",
  280. examples=[
  281. "hf skills add",
  282. "hf skills add huggingface-gradio --dest=~/my-skills",
  283. "hf skills add --global",
  284. "hf skills add --claude",
  285. "hf skills add huggingface-gradio --claude --global",
  286. ],
  287. )
  288. def skills_add(
  289. name: Annotated[
  290. str,
  291. typer.Argument(help="Marketplace skill name.", show_default=False),
  292. ] = DEFAULT_SKILL_ID,
  293. claude: Annotated[bool, typer.Option("--claude", help="Install for Claude.")] = False,
  294. global_: Annotated[
  295. bool,
  296. typer.Option(
  297. "--global",
  298. "-g",
  299. help="Install globally (user-level) instead of in the current project directory.",
  300. ),
  301. ] = False,
  302. dest: Annotated[
  303. Path | None,
  304. typer.Option(
  305. help="Install into a custom destination (path to skills directory).",
  306. ),
  307. ] = None,
  308. force: Annotated[
  309. bool,
  310. typer.Option(
  311. "--force",
  312. help="Overwrite existing skills in the destination.",
  313. ),
  314. ] = False,
  315. ) -> None:
  316. """Download a Hugging Face skill and install it for an AI assistant.
  317. Default location is in the current directory (.agents/skills) or user-level (~/.agents/skills).
  318. If `--claude` is specified, the skill is also symlinked into Claude's legacy skills directory.
  319. """
  320. if dest is not None:
  321. if claude or global_:
  322. raise CLIError("--dest cannot be combined with --claude or --global.")
  323. skill_dest = _install_to(dest, name, force)
  324. print(f"Installed '{name}' to {skill_dest}")
  325. return
  326. # Install to central location
  327. central_path = CENTRAL_GLOBAL if global_ else CENTRAL_LOCAL
  328. central_skill_path = _install_to(central_path, name, force)
  329. print(f"Installed '{name}' to central location: {central_skill_path}")
  330. if claude:
  331. agent_target = CLAUDE_GLOBAL if global_ else CLAUDE_LOCAL
  332. link_path = _create_symlink(agent_target, name, central_skill_path, force)
  333. print(f"Created symlink: {link_path}")
  334. @skills_cli.command(
  335. "upgrade",
  336. examples=[
  337. "hf skills upgrade",
  338. "hf skills upgrade hf-cli",
  339. "hf skills upgrade huggingface-gradio --dest=~/my-skills",
  340. "hf skills upgrade --claude",
  341. ],
  342. )
  343. def skills_upgrade(
  344. name: Annotated[
  345. str | None,
  346. typer.Argument(help="Optional installed skill name to upgrade.", show_default=False),
  347. ] = None,
  348. claude: Annotated[bool, typer.Option("--claude", help="Upgrade skills installed for Claude.")] = False,
  349. global_: Annotated[
  350. bool,
  351. typer.Option(
  352. "--global",
  353. "-g",
  354. help="Use global skills directories instead of the current project.",
  355. ),
  356. ] = False,
  357. dest: Annotated[
  358. Path | None,
  359. typer.Option(
  360. help="Upgrade skills in a custom skills directory.",
  361. ),
  362. ] = None,
  363. ) -> None:
  364. """Upgrade installed Hugging Face marketplace skills."""
  365. roots = _resolve_update_roots(claude=claude, global_=global_, dest=dest)
  366. results = _skills.apply_updates(roots, selector=name)
  367. if not results:
  368. print("No installed skills found.")
  369. return
  370. for result in results:
  371. detail = f" ({result.detail})" if result.detail else ""
  372. print(f"{result.name}: {result.status}{detail}")