Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install hf-cloud-python-env-setup@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin hf-cloud-python-env-setup v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install hf-cloud-python-env-setup

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/hf-cloud-python-env-setup/

Extract the ZIP to .github/skills/ in your repo. The folder name must match hf-cloud-python-env-setup for Copilot to auto-discover it.

Skill Files (4)

SKILL.md 6.5 KB
---
name: hf-cloud-python-env-setup
description: 'Set up an isolated Python environment for SageMaker / AWS work, with the right Python version and current boto3. Use this skill whenever Python code will be executed for a SageMaker deployment, training job, or any AWS automation — including when about to run `pip install`, when about to invoke `boto3`, when creating or activating a virtualenv, or when the user asks to "set up the environment". Never use system Python and never `pip install` into it. Always isolate. This skill prevents the most common failure modes: wrong Python version, dependency conflicts, and stale SDKs.'
---

# Python Environment Setup for SageMaker

Most SageMaker deployment failures that look like AWS problems are actually Python environment problems: wrong Python version, broken dependency resolution, stale SDK that doesn't know about a current API. This skill makes env setup boring and correct.

## Core rules

1. **Never use the system Python.** Always work inside an isolated environment.
2. **Pin the Python version, not the package versions.** Use 3.10, 3.11, or 3.12. Avoid 3.13+ — ML libraries lag on wheel availability and dependency resolution breaks in confusing ways.
3. **Install the latest of each package.** Don't defensively pin `boto3` or `awscli`. Newer ones have current API surfaces and security fixes. Only pin if the user explicitly requires a specific version.
4. **Check installed versions correctly.** Use `importlib.metadata.version("package-name")`, never `module.__version__`. The latter is inconsistent across packages.
5. **The bundled scripts use `boto3` directly.** The SageMaker Python SDK is a valid alternative — see "boto3 vs the SageMaker SDK" below.

## boto3 vs the SageMaker SDK

The bundled deploy scripts (`deploy.py`, `deploy_async.py`, `teardown.py`) use `boto3` directly and read image URIs from [AWS's published Deep Learning Containers catalog](https://aws.github.io/deep-learning-containers/reference/available_images/). That fits this workflow's explicit-stages design — each skill produces a concrete value (region, role ARN, image URI) that the next one consumes — and `boto3` is the stable underlying API client.

The SageMaker Python SDK (v3) is fine to use when the user prefers it or their project already does. Since [PR #5960](https://github.com/aws/sagemaker-python-sdk/pull/5960) (June 2026), `ModelBuilder` auto-routes HuggingFace models to the current containers (text-generation → HuggingFace vLLM, multimodal → vLLM-Omni, embeddings → TEI). Don't avoid the SDK over stale-image or wrong-container concerns — that routing is fixed.

Two specific SDK cases that still need care:

- **Generative rerankers**: the SDK routes the `text-ranking` task to TEI unconditionally, which is wrong for causal-LM rerankers like Qwen3-Reranker — those need vLLM (see `hf-cloud-serving-image-selection`). Pass the container explicitly for these models.
- **SSO assumed-role credentials**: v3 has had credential-resolution regressions in `ModelTrainer` / `FrameworkProcessor` under SSO profiles. If SDK calls fail with credential errors while `aws sts get-caller-identity` succeeds in the same shell, suspect this rather than your AWS config.

If you use the SDK, install it into the isolated env like everything else (`.venv/bin/python -m pip install sagemaker`). The bundled scripts don't require it.

## How to set up

The fastest path is the bundled script — it's Python, so it runs the same on Windows, macOS, and Linux:

```bash
python3 scripts/setup_env.py        # macOS / Linux
python  scripts/setup_env.py        # Windows (PowerShell / cmd)
```

This script detects `uv` and uses it if available (faster), falls back to the stdlib `venv` module, creates `.venv/` with Python 3.12 (override: `python3 setup_env.py .venv 3.11`), refuses unsupported Python versions, installs from the bundled `requirements.txt`, and is idempotent. It also prints the correct interpreter path for the host OS (see below).

Manual equivalent:

```bash
# Preferred: uv
uv venv --python 3.12 .venv
uv pip install --python .venv/bin/python --upgrade boto3 awscli   # Windows: .venv\Scripts\python.exe

# Fallback: stdlib venv
python3.12 -m venv .venv
.venv/bin/python -m pip install --upgrade pip boto3 awscli
```

After setup, **invoke the env's Python explicitly** rather than activating the venv. The interpreter path differs by platform:

```bash
.venv/bin/python deploy.py            # macOS / Linux
.venv\Scripts\python.exe deploy.py    # Windows
```

This works the same in scripts, interactive shells, and agent tool calls. The rest of this skill writes `.venv/bin/python` for brevity — on Windows substitute `.venv\Scripts\python.exe`.

## Verifying

```bash
.venv/bin/python scripts/check_versions.py
```

Prints versions of `boto3`, `botocore`, `awscli`. Uses `importlib.metadata.version()` so it works on every package, including ones without `__version__`. Pass arbitrary names: `... check_versions.py transformers huggingface_hub`.

## Deployment-specific extras

Default `requirements.txt` covers SageMaker orchestration. Some deployments need extras (`huggingface_hub` for model inspection, `transformers` for tokenizer validation). Add these to a deployment-specific requirements file in the project, install with the env's Python, don't pin unless there's a reason.

## Common pitfalls

**Mysterious `pip install` resolution errors**
Almost always Python 3.13+ trying to install packages without wheels yet, or installing into a polluted system Python. Recreate at 3.12: delete `.venv` and re-run `python3 setup_env.py .venv 3.12` (the script recreates the env when the version doesn't match, so you can also just re-run it).

**`pip install` succeeded but the script says "module not found"**
You installed into a different interpreter than the one running the script. Always invoke Python explicitly: `.venv/bin/python -m pip install ...` and `.venv/bin/python deploy.py`.

**Inline `python -c "..."` one-liners fail in PowerShell**
PowerShell's quoting rules mangle nested/escaped quotes in inline Python. Don't debug the quoting — write the snippet to a small `.py` file and run that. (All bundled helpers are files for exactly this reason.)

**boto3 call fails with "unknown parameter"**
Your boto3 is older than the API surface. Upgrade with `.venv/bin/python -m pip install --upgrade boto3`. Don't downgrade the script to match an old version.

**`sagemaker` (the SDK) installed but the bundled scripts fail**
The bundled scripts don't use the SDK — they only need `boto3`/`awscli` from `requirements.txt`. Installing `sagemaker` alongside is harmless, but it doesn't replace the requirements install.
requirements.txt 0.8 KB
# Core AWS dependencies for SageMaker deployment.
#
# No version pins. We want the latest of each — if scripts break against the
# latest, fix the script, not the version. Newer boto3/awscli have current
# API surfaces and security fixes.
#
# We do NOT depend on the SageMaker Python SDK (sagemaker / sagemaker-core /
# sagemaker-serve). The deployment scripts call boto3 directly, and image URIs
# are read from AWS's published catalog page rather than resolved via the SDK.
# See hf-cloud-python-env-setup SKILL.md ("Why no SageMaker SDK").
#
# Add per-deployment extras (huggingface_hub for model inspection, transformers
# for tokenizer validation) to a deployment-specific requirements file alongside
# this one. Do not pin versions here unless you have a documented reason.

boto3
awscli
scripts/
check_versions.py 0.7 KB
#!/usr/bin/env python
"""Report installed versions of key dependencies.

Uses importlib.metadata.version() (works for every installed package, unlike
the inconsistently-defined `module.__version__`).

Usage:
    python check_versions.py
    python check_versions.py boto3 botocore transformers
"""

import sys
from importlib.metadata import PackageNotFoundError, version

DEFAULT_PACKAGES = ["boto3", "botocore", "awscli"]


def main() -> int:
    packages = sys.argv[1:] if len(sys.argv) > 1 else DEFAULT_PACKAGES
    for pkg in packages:
        try:
            print(f"{pkg}=={version(pkg)}")
        except PackageNotFoundError:
            print(f"{pkg}: NOT INSTALLED")
    return 0


if __name__ == "__main__":
    sys.exit(main())
setup_env.py 4.9 KB
#!/usr/bin/env python3
"""Create an isolated Python environment for SageMaker work. Cross-platform.

Idempotent. Prefers uv, falls back to the stdlib venv module.

Handles the platform difference in venv layout: the interpreter lives at
`<venv>/bin/python` on macOS/Linux and `<venv>\\Scripts\\python.exe` on Windows.
The path it prints is the correct one for the host OS.

Usage:
    python setup_env.py [VENV_DIR=.venv] [PYTHON_VERSION=3.12]
"""

from __future__ import annotations

import os
import shutil
import subprocess
import sys
from pathlib import Path

# 3.10-3.12 is the safe zone for modern boto3 + awscli. 3.13+ may work but ML
# libs lag on wheel availability.
SUPPORTED_MIN = (3, 10)
SUPPORTED_MAX = (3, 12)

IS_WINDOWS = os.name == "nt"


def log(msg: str) -> None:
    print(f"[setup_env] {msg}", file=sys.stderr, flush=True)


def parse_version(v: str) -> tuple[int, int]:
    try:
        major, minor = (int(p) for p in v.split(".")[:2])
        return (major, minor)
    except ValueError:
        log(f"ERROR: invalid Python version '{v}' (expected e.g. 3.12)")
        sys.exit(1)


def venv_python(venv_dir: Path) -> Path:
    """Path to the interpreter inside a venv, per platform."""
    if IS_WINDOWS:
        return venv_dir / "Scripts" / "python.exe"
    return venv_dir / "bin" / "python"


def interpreter_version(python_path: Path) -> str | None:
    if not python_path.exists():
        return None
    proc = subprocess.run(
        [str(python_path), "-c",
         "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"],
        capture_output=True, text=True,
    )
    return proc.stdout.strip() if proc.returncode == 0 else None


def find_base_python(version: str) -> str | None:
    """Locate a base interpreter for the requested version for `python -m venv`."""
    # Try `pythonX.Y` (Unix) / `pythonX.Y.exe`, then the Windows `py` launcher.
    candidate = shutil.which(f"python{version}")
    if candidate:
        return candidate
    if IS_WINDOWS and shutil.which("py"):
        probe = subprocess.run(["py", f"-{version}", "--version"], capture_output=True, text=True)
        if probe.returncode == 0:
            return f"py -{version}"  # sentinel; expanded by caller
    return None


def main() -> int:
    venv_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(".venv")
    python_version = sys.argv[2] if len(sys.argv) > 2 else "3.12"

    ver = parse_version(python_version)
    if not (SUPPORTED_MIN <= ver <= SUPPORTED_MAX):
        lo = ".".join(map(str, SUPPORTED_MIN))
        hi = ".".join(map(str, SUPPORTED_MAX))
        log(f"ERROR: Python {python_version} outside supported range {lo}-{hi}")
        log("Use 3.10, 3.11, or 3.12.")
        return 1

    installer = "uv" if shutil.which("uv") else "venv"
    if installer == "venv":
        log("uv not found — falling back to python + venv. Consider: https://docs.astral.sh/uv/")

    py = venv_python(venv_dir)

    # Reuse existing env only if Python version matches.
    current = interpreter_version(py)
    if current == python_version:
        log(f"Env exists at {venv_dir} with Python {current} — reusing")
    else:
        if current is not None:
            log(f"Env at {venv_dir} uses Python {current} (wanted {python_version}) — recreating")
            shutil.rmtree(venv_dir)

        if installer == "uv":
            uv = shutil.which("uv")
            if subprocess.run([uv, "venv", "--python", python_version, str(venv_dir)]).returncode != 0:
                log("ERROR: `uv venv` failed.")
                return 1
        else:
            base = find_base_python(python_version)
            if not base:
                log(f"ERROR: python{python_version} not found on PATH.")
                log("Install via pyenv/asdf/brew/system package manager, the Windows installer, or install uv.")
                return 1
            base_cmd = base.split() if base.startswith("py ") else [base]
            if subprocess.run([*base_cmd, "-m", "venv", str(venv_dir)]).returncode != 0:
                log("ERROR: `python -m venv` failed.")
                return 1
        log(f"Created env at {venv_dir}")

    requirements = Path(__file__).resolve().parent.parent / "requirements.txt"
    if not requirements.is_file():
        log(f"ERROR: requirements.txt not found at {requirements}")
        return 1

    log(f"Installing from {requirements}")
    if installer == "uv":
        uv = shutil.which("uv")
        rc = subprocess.run(
            [uv, "pip", "install", "--python", str(py), "--upgrade", "-r", str(requirements)]
        ).returncode
    else:
        subprocess.run([str(py), "-m", "pip", "install", "--upgrade", "pip"])
        rc = subprocess.run(
            [str(py), "-m", "pip", "install", "--upgrade", "-r", str(requirements)]
        ).returncode
    if rc != 0:
        log("ERROR: dependency install failed.")
        return 1

    log(f"Done. Invoke directly: {py} <script>")
    return 0


if __name__ == "__main__":
    sys.exit(main())

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/huggingface/skills/blob/main/LICENSE