Hugging Face Integration Guide

Technology: hugging-face · Category: ai · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/hugging-face

Insight:

Hugging Face is home for open-weight and fine-tuned models. Its Inference Providers router (router.huggingface.co/v1) puts ~18 providers (Together, Cerebras, Groq, Fireworks…) behind one HF token and OpenAI-compatible Chat Completions and Responses endpoints, with :fastest / :cheapest / :preferred routing and no markup. It is pay-as-you-go: PRO ($9/mo) includes only $2/month of compute credits and free accounts get none, so budget real spend. Reach for it for open weights, Swahili/multilingual models, cheap embeddings, and free ZeroGPU demos — not for frontier reasoning (that stays on Claude).

██╗  ██╗██╗   ██╗ ██████╗  ██████╗ ██╗███╗   ██╗ ██████╗     ███████╗ █████╗  ██████╗███████╗
██║  ██║██║   ██║██╔════╝ ██╔════╝ ██║████╗  ██║██╔════╝     ██╔════╝██╔══██╗██╔════╝██╔════╝
███████║██║   ██║██║  ███╗██║  ███╗██║██╔██╗ ██║██║  ███╗    █████╗  ███████║██║     █████╗
██╔══██║██║   ██║██║   ██║██║   ██║██║██║╚██╗██║██║   ██║    ██╔══╝  ██╔══██║██║     ██╔══╝
██║  ██║╚██████╔╝╚██████╔╝╚██████╔╝██║██║ ╚████║╚██████╔╝    ██║     ██║  ██║╚██████╗███████╗
╚═╝  ╚═╝ ╚═════╝  ╚═════╝  ╚═════╝ ╚═╝╚═╝  ╚═══╝ ╚═════╝     ╚═╝     ╚═╝  ╚═╝ ╚═════╝╚══════╝

Hugging Face Integration Guide

Focus: Using Hugging Face models, Spaces (incl. ZeroGPU), Inference Providers, and the official HF MCP server inside Claude Code sessions and codeAmani apps.

Overview

Hugging Face hosts 1,000,000+ open-source models, datasets, and Spaces. From inside Claude Code you can run models through Inference Providers (one HF token routing to Together, Cerebras, Groq, Fireworks, Novita and ~13 others behind an OpenAI-compatible router), deploy Gradio apps to Spaces (free GPU via ZeroGPU), manage repos and datasets with the hf CLI, and explore the Hub through the official HF MCP server.

Here is the big picture — the Hub sits at the center, and Claude Code reaches it through two friendly paths that feed straight into your app.

flowchart LR
  Hub["Hugging Face Hub<br/>models · datasets · Spaces"]
  CC["Claude Code"]
  MCP["HF MCP server"]
  CLI["hf CLI"]
  Inf["Inference Providers"]
  Local["Local weights<br/>download · offline"]
  App["Your app"]
  CC --> MCP
  CC --> CLI
  MCP --> Hub
  CLI --> Hub
  Hub -->|"serverless"| Inf
  Hub -->|"download"| Local
  Inf --> App
  Local --> App

Current versions (verified 2026-10-20)

Package Registry Version Notes
@huggingface/inference npm 4.13.32 InferenceClient (JS/TS)
@ai-sdk/huggingface npm 2.0.74 Vercel AI SDK provider (pairs with ai@7.0.146)
@huggingface/transformers npm 4.3.1 transformers.js — in-browser/edge inference
@huggingface/hub npm 2.17.8 Hub API from JS (repos, uploads)
huggingface_hub PyPI 2.2.0 New major (v2.0 on 2026-09-24) — ships the hf CLI
transformers PyPI 5.20.2 v5 — use dtype= (not torch_dtype=)
gradio PyPI 6.30.0 Gradio 6
spaces PyPI 0.51.3 @spaces.GPU for ZeroGPU

Official Documentation

Resource URL
HF Hub Docs https://huggingface.co/docs/hub
Inference Providers https://huggingface.co/docs/inference-providers
Inference Providers pricing https://huggingface.co/docs/inference-providers/pricing
Responses API (beta) https://huggingface.co/docs/inference-providers/guides/responses-api
Live model catalog https://huggingface.co/inference/models
ZeroGPU https://huggingface.co/docs/hub/spaces-zerogpu
User access tokens https://huggingface.co/docs/hub/security-tokens
HF MCP Server https://huggingface.co/docs/hub/en/hf-mcp-server
huggingface_hub / hf CLI https://huggingface.co/docs/huggingface_hub/guides/cli
huggingface_hub v2 migration https://huggingface.co/docs/huggingface_hub/main/en/concepts/migration_v2
AI SDK provider https://ai-sdk.dev/providers/ai-sdk-providers/huggingface
Gradio https://www.gradio.app/docs

Docs pages are served as Markdown — append .md (e.g. …/docs/hub/spaces-zerogpu.md). There is no sitemap.xml for /docs/inference-providers; use the sidebar of the index page.


MCP Server Setup

Hugging Face hosts the official MCP server at https://huggingface.co/mcp (Streamable HTTP). It exposes Hub search/inspection tools plus any MCP-enabled Gradio Space you add in https://huggingface.co/settings/mcp.

# OAuth (no token on disk) — start `claude`, then follow the login prompt
claude mcp add hf-mcp-server -t http "https://huggingface.co/mcp?login"

# …or with a token header (use a fine-grained READ token)
claude mcp add hf-mcp-server -t http https://huggingface.co/mcp \
  -H "Authorization: Bearer ${HF_TOKEN}"

.mcp.json Configuration

{
  "mcpServers": {
    "huggingface": {
      "type": "http",
      "url": "https://huggingface.co/mcp",
      "headers": {
        "Authorization": "Bearer ${HF_TOKEN}"
      }
    }
  }
}

Tools you get

The tool set is configured per account at https://huggingface.co/settings/mcp (built-in tools + Spaces you pin), so the list varies. On the codeAmani connector (checked 2026-10-20) the built-ins are:

Tool What it does
hf_fs Filesystem-style Hub access: ls hf://models/trending, search hf://models <query>, cat hf://models/<org>/<repo>/README.md, papers, docs
hub_repo_search Search models / datasets / Spaces
hub_repo_details Model/dataset/Space overview, dataset structure + preview
hf_whoami Show the authenticated account
(Space tools) Each MCP-enabled Gradio Space you add appears as its own tool (image gen, ASR, …)

Older guides listed tools like search_models / run_space / upload_file — those names are not what the server exposes today. Write/creation tools (repo creation, Jobs) appear only when authenticated and enabled. Add ?no_image_content=true to the URL to strip image blocks from Gradio tool output.


CLI Integration (hf)

The hf CLI ships with huggingface_hub (now v2.x). huggingface-cli and the singular hf repo command group were removed in v2.0 — use hf and hf repos.

Installation + auth

curl -LsSf https://hf.co/cli/install.sh | bash   # standalone installer (recommended)
# or: pip install -U huggingface_hub   |   uvx hf ...   |   brew install hf
hf auth login                   # interactive; stores the token in ~/.cache/huggingface/token
hf auth login --token "$HF_TOKEN"   # non-interactive (CI)
hf auth whoami

Key commands

# Discover models served by Inference Providers
hf models ls --warm --search gemma --json
hf models ls --inference-provider groq --sort downloads

# Download / upload
hf download Qwen/Qwen2.5-3B-Instruct                 # to the local cache
hf download hf://datasets/<org>/<name>@main/data/     # hf:// URIs work too
hf upload <user>/my-model ./model-dir .

# Repos (note: plural `repos`; Space SDK flag is --sdk)
hf repos create my-space --repo-type space --sdk gradio

# Spaces lifecycle
hf spaces secrets add <user>/my-space -s HF_TOKEN=...   # write-only secrets
hf spaces variables add <user>/my-space -e MODEL_ID=Qwen/Qwen2.5-3B-Instruct
hf spaces restart <user>/my-space && hf spaces wait <user>/my-space
hf spaces zero-gpu quota                              # remaining ZeroGPU seconds (v2.1.1+)

# Agent skills for Claude Code / Codex / Cursor (installed to .agents/skills + .claude/skills)
hf skills add

Inference Providers (serverless)

Hugging Face's serverless inference is Inference Providers: one HF token, one router (https://router.huggingface.co/v1), and automatic routing across partner providers. HF passes provider rates through with no markup.

sequenceDiagram
  participant App as "Your code"
  participant Router as "router.huggingface.co"
  participant Prov as "Provider (Groq / Together / Novita / …)"
  App->>Router: "POST /v1/chat/completions or /v1/responses (HF token)"
  Router->>Prov: "route by policy (:fastest / :cheapest / :preferred / named)"
  Prov-->>Router: "tokens"
  Router-->>App: "OpenAI-shaped response"

Providers in the docs table (18): Baseten, Cerebras, Cohere, DeepInfra, Fal AI, Featherless AI, Fireworks, Groq, HF Inference, Novita, Nscale, OVHcloud AI Endpoints, Public AI, Replicate, Scaleway, Together, WaveSpeedAI, Z.ai. The JS client's type also knows humain-ai, openrouter, and openai — see NOTES for the discrepancy. Check GET https://router.huggingface.co/v1/models (public, no token) for live per-provider status, pricing (USD per 1M tokens), context length, latency, throughput, and tool/structured-output support.

Routing — append to the model id (works everywhere, incl. the OpenAI SDK and Claude Code):

Suffix Meaning
(none) / :fastest Default. Highest throughput (tokens/sec); auto-fails over if a provider is flagged down.
:cheapest Lowest price per output token.
:preferred Your order at hf.co/settings/inference-providers.
:groq, :together, :novita, … Pin one provider (deterministic, no failover).

In the native clients you can instead pass provider: "groq" (or "auto"); the policies are suffix-only.

Endpoints on the router: /v1/chat/completions (OpenAI Chat Completions), /v1/responses (OpenAI Responses API, beta — tools, remote MCP, structured outputs, reasoning effort), and an Anthropic-compatible surface used by the Claude Code integration below. Embeddings, text-to-image, ASR, etc. are not on /v1 — use the typed InferenceClient methods.

Python (huggingface_hub 2.x)

pip install -U huggingface_hub
hf auth login
import os
from huggingface_hub import InferenceClient

client = InferenceClient(api_key=os.environ["HF_TOKEN"])

# Chat completion — default policy is :fastest
completion = client.chat.completions.create(
    model="openai/gpt-oss-120b",
    messages=[{"role": "user", "content": "Explain async/await in one sentence."}],
)
print(completion.choices[0].message.content)

# Cost control: cheapest provider for a batch job
completion = client.chat.completions.create(
    model="openai/gpt-oss-120b:cheapest",
    messages=[{"role": "user", "content": "Habari!"}],
)

# Bill a Team/Enterprise org instead of yourself
org_client = InferenceClient(bill_to="codeAmani-labs")

v2 notes: InferenceClient(token=True/False) booleans are gone — pass a token string or None; text_generation(stop_sequences=...) → stop=...; HTTP errors now come from httpx2 (catch huggingface_hub.errors.HfHubHTTPError, or from huggingface_hub.utils import httpx).

JavaScript / TypeScript (@huggingface/inference 4.13.32)

npm install @huggingface/inference@4.13.32
import { InferenceClient } from "@huggingface/inference";

const client = new InferenceClient(process.env.HF_TOKEN);

const chat = await client.chatCompletion({
  model: "openai/gpt-oss-120b",          // or "openai/gpt-oss-120b:cheapest"
  messages: [{ role: "user", content: "What is a transformer?" }],
  // provider: "groq",                   // pin one provider instead of a policy
});
console.log(chat.choices[0]?.message.content);

Full typed examples (streaming, embeddings, text-to-image, ASR, error classes, billTo): examples/inference.ts. The JS client exposes chatCompletion / chatCompletionStream — not client.chat.completions.create (that shape is Python-only, despite one JS snippet on the pricing page).

Vercel AI SDK (@ai-sdk/huggingface 2.0.74)

npm install ai@7.0.146 @ai-sdk/huggingface@2.0.74 zod
import { createHuggingFace } from "@ai-sdk/huggingface";
import { generateText } from "ai";

const huggingFace = createHuggingFace({ apiKey: process.env.HF_TOKEN ?? "" });

const { text } = await generateText({
  model: huggingFace("openai/gpt-oss-120b:cheapest"),
  prompt: "Andika sentensi moja kuhusu M-Pesa.",
});

The provider defaults to https://router.huggingface.co/v1 and reads HUGGINGFACE_API_KEY if you don't pass apiKey. huggingFace(id) uses the Responses API; providerOptions.huggingface supports reasoningEffort, instructions, strictJsonSchema, metadata. See examples/ai-sdk.ts.

Drop-in OpenAI replacement

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://router.huggingface.co/v1",
  apiKey: process.env.HF_TOKEN,
});

const completion = await client.chat.completions.create({
  model: "deepseek-ai/DeepSeek-R1:cheapest",
  messages: [{ role: "user", content: "Hello!" }],
});
// client.responses.create({ model, instructions, input }) also works (beta).

REST (curl)

curl https://router.huggingface.co/v1/chat/completions \
  -H "Authorization: Bearer $HF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"model": "openai/gpt-oss-120b:fastest", "messages": [{"role": "user", "content": "Jambo!"}]}'

Run Claude Code on open models (optional)

HF documents pointing Claude Code at the router (Anthropic-compatible) — useful for cheap experiments, not for codeAmani production work (Claude stays primary per AI routing):

hf extensions install hf-claude && hf claude      # interactive model/provider picker
# manual: export ANTHROPIC_BASE_URL="https://router.huggingface.co"
#         export ANTHROPIC_AUTH_TOKEN="$HF_TOKEN"; export ANTHROPIC_DEFAULT_SONNET_MODEL="zai-org/GLM-5.1"

Tokens (use fine-grained)

Role Use it for
fine-grained Production default. Scope to exact permissions + repos/orgs. For inference tick "Make calls to Inference Providers" (inference.serverless.write).
read Local dev, downloading private/gated models
write Pushing to repos (prefer fine-grained contributor instead — see below)

Pricing breakdown

Verified 2026-10-20 against https://huggingface.co/pricing and https://huggingface.co/docs/inference-providers/pricing. Provider per-token rates: GET /v1/models.

Account plans

Plan Price Included compute credits Other
Free $0 None — buy credits to use Inference Providers ZeroGPU 5 min/day; host up to 2 ZeroGPU Spaces (verified email, account >30 days)
PRO $9 / mo $2 / month 8× ZeroGPU quota (40 min/day) + highest queue priority, host up to 10 ZeroGPU Spaces, 10× private storage, Spaces Dev Mode
Team $20 / user / mo $2 / seat / month (shared) SSO, audit logs, resource groups, token policies, up to 50 ZeroGPU Spaces
Enterprise $50 / user / mo $2 / seat / month (shared) SCIM, highest limits, usage API, 60 min/day ZeroGPU

Included credits are general compute credits: Inference Providers, Inference Endpoints, upgraded Spaces hardware, ZeroGPU beyond quota, and Jobs. They apply only to HF-routed requests — if you set a custom provider key in HF settings, that provider bills you directly and credits don't apply. Team/Enterprise orgs must send X-HF-Bill-To: <org> (or bill_to= / billTo) to draw from org credits.

HF Inference (the provider formerly "Inference API (serverless)") bills compute-time × hardware price and is now mostly CPU tasks (embeddings, classification, ranking, small models).

Sample router prices (USD / 1M tokens, input → output, 2026-10-20)

Model Cheapest live provider Others
openai/gpt-oss-120b DeepInfra $0.037 → $0.17 Novita $0.05→$0.25, Groq $0.15→$0.75, Cerebras $0.35→$0.75
google/gemma-4-31B-it Novita $0.14 → $0.40 DeepInfra $0.20→$0.40
meta-llama/Llama-3.3-70B-Instruct Novita $0.135 → $0.40 (12k ctx!) OVHcloud $0.74, Together $1.04 (131k ctx)
deepseek-ai/DeepSeek-R1 Novita $0.70 → $2.50 —

Inference Endpoints (dedicated, scale-to-zero, AWS per-hour per instance)

Hardware Hourly
CPU Intel Sapphire Rapids (1 vCPU) from $0.03
NVIDIA T4 $0.50
NVIDIA L4 $0.80
NVIDIA L40S $1.80
NVIDIA A100 80GB $2.50
NVIDIA RTX PRO 6000 96GB (new) $2.75
NVIDIA H100 $4.50
NVIDIA H200 $5.00
NVIDIA B200 $9.25

Multi-GPU scales linearly (e.g. 8× H100 = $36/hr). Also: Inf2 Neuron from $0.75, TPU v5e from $1.20 (GCP).

Spaces hardware

Flavor Hourly
CPU Basic (2 vCPU / 16 GB) Free
ZeroGPU (RTX Pro 6000 Blackwell, up to 96 GB) Free (daily quota)
CPU Upgrade (8 vCPU / 32 GB) $0.03
T4 small / medium $0.40 / $0.60
L4 / 4× L4 $0.80 / $3.80
L40S / 4× / 8× $1.80 / $8.30 / $23.50
A10G small / large $1.00 / $1.50
A100 large / 4× A100 $2.50 / $10.00

Storage

$12 / TB / mo public, $18 / TB / mo private; volume tiers down to $8 / $12 at 500 TB+. Egress/CDN included.

HF-open vs frontier (the codeAmani calculus)

PRO's $2/month will not carry production traffic — budget pay-as-you-go. For low-to-mid volume, open models via the router are still far cheaper per token than frontier APIs: pin :cheapest for batch jobs, :fastest for interactive UX. When traffic is steady and high, a dedicated Inference Endpoint (scale-to-zero) beats per-token pricing. For free public demos, a ZeroGPU Space.


ZeroGPU (free GPU Spaces)

codeAmani runs codeAmani-labs/amani-swahili-chat on ZeroGPU (Qwen2.5-3B-Instruct, streamed bilingual chat).

Fact Value (docs, 2026-10-20)
Hardware NVIDIA RTX Pro 6000 Blackwell — large (default) = half card / 48 GB / 1× quota; xlarge = full card / 96 GB / 2× quota
SDK Gradio only (Gradio 4+). No Streamlit/Docker.
PyTorch 2.8.0 → 2.13.0 supported
Python 3.12.12 or 3.10.13
Default runtime cap 60 s per call — raise with @spaces.GPU(duration=120) or a callable for dynamic duration
Daily quota Unauthenticated 2 min · Free 5 min · PRO / Team 40 min · Enterprise 60 min
Reset 24 h after your first GPU use (rolling, not midnight)
Beyond quota PRO/Team/Enterprise: pre-paid credits at $1 per 10 min
Hosting limits Free 2 Spaces (account >30 days, verified email) · PRO 10 · Team/Enterprise org 50
Check quota hf spaces zero-gpu quota or huggingface_hub.get_zero_gpu_quota() (GPU-seconds)

Quota is per account tier of whoever calls the Space (the docs give PRO users 8× quota "when using any ZeroGPU Spaces"), so anonymous visitors get the 2-min tier regardless of the owner's plan. Remaining quota also sets queue priority — visitors low on quota wait longer. Shorter duration= values improve priority.

Gotchas (see examples/app.py, which mirrors the live Space):

  1. Load the model and call .to("cuda") at module level; real CUDA only exists inside @spaces.GPU (a CUDA emulation mode covers module scope). Lazy-loading inside the decorated call is much slower.
  2. The decorated function runs in a separate process — args/yields must be picklable.
  3. No torch.compile — use PyTorch ahead-of-time compilation (AoTI, torch 2.8+) at build time.
  4. xlarge doubles quota burn and queues longer — only for >48 GB models.
  5. cache_examples=True runs examples at startup and burns GPU — keep it off.
  6. Pin sdk_version in the README YAML (latest Gradio is 6.30.0); suggested_hardware is only a hint for people who duplicate — select ZeroGPU in Settings → Hardware.
  7. transformers 5.x: from_pretrained(..., dtype=torch.bfloat16) (not torch_dtype=), and apply_chat_template(..., return_dict=True) then generate(**inputs).
  8. Embedding the Space on a codeAmani page means each visitor spends their own (often 2-min anonymous) quota — fine for demos, not a production chat backend.

Deploy a Space

A Space is a Git repo Hugging Face builds and runs. With the Gradio SDK, three files do the work: README.md (YAML config), app.py, requirements.txt. Push it and the app is live at https://huggingface.co/spaces/<user>/<space>.

flowchart LR
  CC["Claude Code"]
  Files["README.md · app.py<br/>requirements.txt"]
  Repo["Space repo<br/>git on the Hub"]
  Build["Space build<br/>install deps · launch"]
  Live["Live app<br/>App tab"]
  CC --> Files
  Files -->|"hf upload"| Repo
  Repo --> Build
  Build --> Live

1. The three files

---
title: Swahili Helper
emoji: 🇰🇪
colorFrom: green
colorTo: blue
sdk: gradio
sdk_version: 6.30.0
python_version: "3.12"
app_file: app.py
pinned: false
short_description: Swahili chat demo
---

# Swahili Helper
A small Gradio demo running on Hugging Face Spaces.
import gradio as gr

def greet(name: str) -> str:
    return f"Habari, {name}!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text", title="Swahili Helper")

if __name__ == "__main__":
    demo.launch()

requirements.txt lists extra deps (Gradio itself comes from sdk_version).

2. Create + push from the CLI

hf repos create swahili-helper --repo-type space --sdk gradio
hf upload <user>/swahili-helper ./swahili-helper .
hf spaces wait <user>/swahili-helper        # exits non-zero on BUILD_ERROR

…or with the Python SDK

import os
from huggingface_hub import HfApi

api = HfApi(token=os.environ["HF_TOKEN"])
api.create_repo(repo_id="<user>/swahili-helper", repo_type="space", space_sdk="gradio", exist_ok=True)
api.upload_folder(repo_id="<user>/swahili-helper", repo_type="space", folder_path="./swahili-helper")

Secrets: Settings → Variables and secrets, or hf spaces secrets add. Never commit HF_TOKEN into app.py. Persistent data: Spaces' disk is ephemeral — mount a Volume or Bucket (hf spaces volumes set).


Environment Variables

Secrets (store in the vault / Vercel env — never commit):

HF_TOKEN=hf_...
# Only if you rely on @ai-sdk/huggingface's default env lookup (no explicit apiKey option)
HUGGINGFACE_API_KEY=hf_...

Non-secret settings:

Variable Purpose
HF_HOME Root of the HF cache/config (default ~/.cache/huggingface)
HF_HUB_CACHE Model/dataset cache dir
HF_HUB_OFFLINE 1 = use cached files only
HF_XET_HIGH_PERFORMANCE 1 = faster Xet transfers (replaces removed HF_HUB_ENABLE_HF_TRANSFER)
HF_HUB_DISABLE_SHARED_BLOBS 1 = opt out of cross-repo blob dedup (v1.32+)
HF_BILL_TO Org to bill when using the hf claude extension

HUGGING_FACE_HUB_TOKEN is the legacy alias of HF_TOKEN; standardize on HF_TOKEN.


Swahili & African-language models worth knowing

Checked on the Hub 2026-10-20. "Router" = served by Inference Providers today. Benchmark in-house before depending on any of these (see research-and-development/reports/2026-06-22-swahili-ai-models.md).

Model Task License Swahili Serving Notes
Qwen/Qwen2.5-3B-Instruct chat other (Qwen license file — check commercial terms) general multilingual Router (featherless-ai); ZeroGPU What the amani-swahili-chat Space runs (base model + system prompt, not fine-tuned)
google/gemma-4-31B-it chat (VLM) Apache-2.0 multilingual Router (novita, deepinfra) Strong cheap open default; earlier Gemma 2 27B was best open model on African benchmarks
CohereLabs/tiny-aya-global / -earth / -fire / -water chat CC-BY-NC-4.0, gated yes (67 langs) Router (cohere) Non-commercial — research/evals only
CohereLabs/aya-101 seq2seq Apache-2.0 yes (101 langs) self-host Older mT5-based
CohereLabs/aya-expanse-32b chat CC-BY-NC-4.0 no Router Excludes Swahili — don't test it for Swahili
Sunbird/Sunflower-14B / -32B chat Apache-2.0, gated yes (Ugandan langs + Swahili) self-host From Sunbird AI (Uganda)
Jacaranda/UlizaLlama QA / chat not stated on card yes (Swahili-specialized, Llama-2 7B) self-host No published benchmarks
lelapa/InkubaLM-0.4B small LM CC-BY-NC-4.0, gated yes (+ 4 African langs) self-host / edge Tiny; eval needed
openai/whisper-large-v3 / -turbo ASR Apache-2.0 / MIT yes Router (hf-inference, fal-ai, together, replicate, deepinfra) Best no-fine-tune STT baseline
facebook/mms-1b-all ASR CC-BY-NC-4.0 yes self-host Best in low-data (≤50 h) fine-tunes
facebook/mms-tts-swh TTS CC-BY-NC-4.0 yes self-host Open Swahili TTS — quality unverified (MOS-eval first)
facebook/seamless-m4t-v2-large speech/text translation CC-BY-NC-4.0 yes self-host
facebook/nllb-200-distilled-600M translation CC-BY-NC-4.0 yes (swh_Latn) self-host Non-commercial
google/madlad400-3b-mt translation Apache-2.0 yes self-host Commercial-friendly MT
intfloat/multilingual-e5-large (+ -instruct) embeddings MIT yes Router (hf-inference, deepinfra) Default for Swahili RAG → pgvector/Pinecone
BAAI/bge-m3 embeddings MIT multilingual Router (hf-inference, sentence-similarity task)
Davlan/afro-xlmr-large, castorini/afriberta_large encoders MIT yes self-host Classification/NER fine-tune bases

License check is mandatory: many of the best Swahili assets (NLLB, MMS, Seamless, Tiny Aya, InkubaLM) are CC-BY-NC — fine for evals, not for a paid product.


transformers.js — models in the browser / on the edge

@huggingface/transformers (4.3.1) runs ONNX models client-side via WebGPU/WASM — no server, no per-call cost, offline after first load. For Kenya-targeted projects on 2G/3G this skips the round-trip entirely — but the model download itself is the cost, so use small quantized models and cache them.

npm install @huggingface/transformers@4.3.1
import { pipeline } from "@huggingface/transformers";

const embedder = await pipeline("feature-extraction", "Xenova/multilingual-e5-small");
const out = await embedder("query: Bei ya unga ni shilingi ngapi?", { pooling: "mean", normalize: true });
const vector: number[] = Array.from(out.data as Float32Array);

Apply HF to the rest of the stack


Automation Workflows

Slash Command: quick open-model answer

.claude/commands/hf-ask.md:

Answer the question in $ARGUMENTS with an open model via Inference Providers.
Write the question to a temp file first (never interpolate it into the command), then run:

```bash
python - "$TMPFILE" <<'PY'
import os, sys
from huggingface_hub import InferenceClient
q = open(sys.argv[1], encoding="utf-8").read()
c = InferenceClient(api_key=os.environ["HF_TOKEN"])
r = c.chat.completions.create(model="openai/gpt-oss-120b:cheapest",
                              messages=[{"role": "user", "content": q}], max_tokens=400)
print(r.choices[0].message.content)
PY
```

CI/CD: publish an eval or checkpoint

# .github/workflows/evaluate-model.yml
name: Evaluate Fine-tuned Model
on:
  push:
    paths: ['models/**']
jobs:
  evaluate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with: { python-version: '3.12' }
      - run: pip install "huggingface_hub>=2.2" evaluate datasets
      - name: Run evaluation
        env:
          HF_TOKEN: ${{ secrets.HF_TOKEN }}   # fine-grained, `contributor` permission
        run: python scripts/evaluate.py

Prefer Trusted Publishers (OIDC) over a stored HF_TOKEN secret where possible. Pin Actions by SHA per the supply-chain policy.


Common Use Cases

Use Case Approach
Open-model chat InferenceClient.chatCompletion / @ai-sdk/huggingface / OpenAI SDK + router
Agentic tools, remote MCP, structured output Router Responses API (beta)
Hub exploration from Claude Code HF MCP server (hf_fs, hub_repo_search, hub_repo_details)
Space deployment hf repos create --sdk gradio + hf upload
Embeddings featureExtraction (e5 / bge-m3)
Swahili speech-to-text automaticSpeechRecognition with openai/whisper-large-v3
Image generation textToImage (FLUX.1-dev via fal-ai / replicate / wavespeed)

Skill Use it for
huggingface-skills:hf-cli Scripting the hf CLI
huggingface-skills:huggingface-spaces / :huggingface-gradio Building & shipping Spaces / Gradio apps
huggingface-skills:huggingface-zerogpu ZeroGPU-backed demos
huggingface-skills:huggingface-lora-space-builder LoRA fine-tune + Space in one go
huggingface-skills:trl-training / :train-sentence-transformers Fine-tuning LLMs / embedders
huggingface-skills:transformers-js Browser/edge inference
huggingface-skills:huggingface-datasets Dataset loading & curation

codeAmani notes


Troubleshooting

Issue Fix
401 Unauthorized Re-login (hf auth login) or check HF_TOKEN
402 Payment Required Out of credits — buy credits or upgrade (free accounts have no included credits)
403 on a model Gated: accept the license with the token's account; or org token policy (pending / fine-grained only)
4xx when pinning a provider The model may not be served by that provider — drop the :provider suffix or check /v1/models
ImportError after upgrading huggingface_hub v2 removed deprecated APIs + moved to httpx2 — see the v2 migration guide
huggingface-cli: command not found Removed in v2 — use hf
ZeroGPU "quota exceeded" Wait for the 24 h rolling reset, log in (anonymous = 2 min), or add credits (PRO)
ZeroGPU Space slow first call Model moved to GPU lazily — move it to cuda at module scope
MCP server not connecting Use ?login OAuth or check the Bearer header; curl https://huggingface.co/mcp should return 200

Official docs: