← Back to dashboard
hugging-faceaifreshReader view (for NotebookLM)

Hugging Face Integration Guide

What is Hugging Face?

The real model

Model hub, Inference Providers, dedicated Endpoints, Datasets, Spaces — one ecosystem.

Two ways to call a model: *Inference Providers* (one HF token routing to ~18 serverless backends behind an OpenAI-compatible router at `router.huggingface.co/v1` — Chat Completions plus a beta Responses API — with `:fastest` / `:cheapest` / `:preferred` routing suffixes, pay-as-you-go) for prototyping and overflow, and *Inference Endpoints* (your own dedicated GPU, auto-scale-to-zero) for steady production. Models are addressed by `org/name` (e.g. `meta-llama/Llama-3.3-70B-Instruct`). The `transformers` library handles `AutoModel.from_pretrained()` for local inference. For codeAmani, HF is where you reach for fine-tunes, Swahili-capable models (Whisper, multilingual-e5, Gemma 4), and open vector embedders before paying a frontier provider.

Five Hugging Face primitives

If it's open, it's probably here. The Hub is the entry point — Endpoints are how it ships to prod.

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

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.

Current versions (verified 2026-10-20)

PackageRegistryVersionNotes
@huggingface/inferencenpm4.13.32InferenceClient (JS/TS)
@ai-sdk/huggingfacenpm2.0.74Vercel AI SDK provider (pairs with ai@7.0.146)
@huggingface/transformersnpm4.3.1transformers.js — in-browser/edge inference
@huggingface/hubnpm2.17.8Hub API from JS (repos, uploads)
huggingface_hubPyPI2.2.0New major (v2.0 on 2026-09-24) — ships the hf CLI
transformersPyPI5.20.2v5 — use dtype= (not torch_dtype=)
gradioPyPI6.30.0Gradio 6
spacesPyPI0.51.3@spaces.GPU for ZeroGPU

Official Documentation

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.

Bash
# 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

JSON
{
  "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:

ToolWhat it does
hf_fsFilesystem-style Hub access: ls hf://models/trending, search hf://models <query>, cat hf://models/<org>/<repo>/README.md, papers, docs
hub_repo_searchSearch models / datasets / Spaces
hub_repo_detailsModel/dataset/Space overview, dataset structure + preview
hf_whoamiShow 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

Bash
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

Bash
# 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.

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):

SuffixMeaning
(none) / :fastestDefault. Highest throughput (tokens/sec); auto-fails over if a provider is flagged down.
:cheapestLowest price per output token.
:preferredYour 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)

Bash
pip install -U huggingface_hub
hf auth login
Python
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)

Bash
npm install @huggingface/inference@4.13.32
TypeScript
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)

Bash
npm install ai@7.0.146 @ai-sdk/huggingface@2.0.74 zod
TypeScript
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

TypeScript
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)

Bash
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):

Bash
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)

RoleUse it for
fine-grainedProduction default. Scope to exact permissions + repos/orgs. For inference tick "Make calls to Inference Providers" (inference.serverless.write).
readLocal dev, downloading private/gated models
writePushing to repos (prefer fine-grained contributor instead — see below)
  • One token per app/environment so you can rotate one without breaking others.
  • Contributor permission (Oct 2026): fine-grained and service-account tokens can be granted contributor — create repos in chosen namespaces and write only to repos that token created. Ideal for CI, training jobs, and agents that publish checkpoints.
  • CI without stored secrets: Trusted Publishers exchange a GitHub/GitLab OIDC token for a short-lived Hub token.
  • Org policies (Team/Enterprise) may require admin approval (token sits Pending), deny, or revoke tokens, or reject non-fine-grained tokens with 403.
  • Leaked a token? Rotate at https://huggingface.co/settings/tokens. Found someone else's? POST https://huggingface.co/api/credentials/revoke (always returns 202).
  • Gated models (Llama, Tiny Aya, InkubaLM…): accept the license on the model page with the account that owns the token, or you get 403.

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

PlanPriceIncluded compute creditsOther
Free$0None — buy credits to use Inference ProvidersZeroGPU 5 min/day; host up to 2 ZeroGPU Spaces (verified email, account >30 days)
PRO$9 / mo$2 / month8× 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)

ModelCheapest live providerOthers
openai/gpt-oss-120bDeepInfra $0.037 → $0.17Novita $0.05→$0.25, Groq $0.15→$0.75, Cerebras $0.35→$0.75
google/gemma-4-31B-itNovita $0.14 → $0.40DeepInfra $0.20→$0.40
meta-llama/Llama-3.3-70B-InstructNovita $0.135 → $0.40 (12k ctx!)OVHcloud $0.74, Together $1.04 (131k ctx)
deepseek-ai/DeepSeek-R1Novita $0.70 → $2.50—

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

HardwareHourly
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

FlavorHourly
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).

FactValue (docs, 2026-10-20)
HardwareNVIDIA RTX Pro 6000 Blackwell — large (default) = half card / 48 GB / 1× quota; xlarge = full card / 96 GB / 2× quota
SDKGradio only (Gradio 4+). No Streamlit/Docker.
PyTorch2.8.0 → 2.13.0 supported
Python3.12.12 or 3.10.13
Default runtime cap60 s per call — raise with @spaces.GPU(duration=120) or a callable for dynamic duration
Daily quotaUnauthenticated 2 min · Free 5 min · PRO / Team 40 min · Enterprise 60 min
Reset24 h after your first GPU use (rolling, not midnight)
Beyond quotaPRO/Team/Enterprise: pre-paid credits at $1 per 10 min
Hosting limitsFree 2 Spaces (account >30 days, verified email) · PRO 10 · Team/Enterprise org 50
Check quotahf 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>.

1. The three files

Markdown
---
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.
Python
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

Bash
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

Python
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):

Bash
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:

VariablePurpose
HF_HOMERoot of the HF cache/config (default ~/.cache/huggingface)
HF_HUB_CACHEModel/dataset cache dir
HF_HUB_OFFLINE1 = use cached files only
HF_XET_HIGH_PERFORMANCE1 = faster Xet transfers (replaces removed HF_HUB_ENABLE_HF_TRANSFER)
HF_HUB_DISABLE_SHARED_BLOBS1 = opt out of cross-repo blob dedup (v1.32+)
HF_BILL_TOOrg 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).

ModelTaskLicenseSwahiliServingNotes
Qwen/Qwen2.5-3B-Instructchatother (Qwen license file — check commercial terms)general multilingualRouter (featherless-ai); ZeroGPUWhat the amani-swahili-chat Space runs (base model + system prompt, not fine-tuned)
google/gemma-4-31B-itchat (VLM)Apache-2.0multilingualRouter (novita, deepinfra)Strong cheap open default; earlier Gemma 2 27B was best open model on African benchmarks
CohereLabs/tiny-aya-global / -earth / -fire / -waterchatCC-BY-NC-4.0, gatedyes (67 langs)Router (cohere)Non-commercial — research/evals only
CohereLabs/aya-101seq2seqApache-2.0yes (101 langs)self-hostOlder mT5-based
CohereLabs/aya-expanse-32bchatCC-BY-NC-4.0noRouterExcludes Swahili — don't test it for Swahili
Sunbird/Sunflower-14B / -32BchatApache-2.0, gatedyes (Ugandan langs + Swahili)self-hostFrom Sunbird AI (Uganda)
Jacaranda/UlizaLlamaQA / chatnot stated on cardyes (Swahili-specialized, Llama-2 7B)self-hostNo published benchmarks
lelapa/InkubaLM-0.4Bsmall LMCC-BY-NC-4.0, gatedyes (+ 4 African langs)self-host / edgeTiny; eval needed
openai/whisper-large-v3 / -turboASRApache-2.0 / MITyesRouter (hf-inference, fal-ai, together, replicate, deepinfra)Best no-fine-tune STT baseline
facebook/mms-1b-allASRCC-BY-NC-4.0yesself-hostBest in low-data (≤50 h) fine-tunes
facebook/mms-tts-swhTTSCC-BY-NC-4.0yesself-hostOpen Swahili TTS — quality unverified (MOS-eval first)
facebook/seamless-m4t-v2-largespeech/text translationCC-BY-NC-4.0yesself-host
facebook/nllb-200-distilled-600MtranslationCC-BY-NC-4.0yes (swh_Latn)self-hostNon-commercial
google/madlad400-3b-mttranslationApache-2.0yesself-hostCommercial-friendly MT
intfloat/multilingual-e5-large (+ -instruct)embeddingsMITyesRouter (hf-inference, deepinfra)Default for Swahili RAG → pgvector/Pinecone
BAAI/bge-m3embeddingsMITmultilingualRouter (hf-inference, sentence-similarity task)
Davlan/afro-xlmr-large, castorini/afriberta_largeencodersMITyesself-hostClassification/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.

Bash
npm install @huggingface/transformers@4.3.1
TypeScript
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

  • HF embeddings → pgvector / Pinecone. client.featureExtraction({ model: "intfloat/multilingual-e5-large", inputs: "query: …" }) (e5 expects query: / passage: prefixes), then upsert into Supabase/Neon pgvector or Pinecone.
  • HF in the AI SDK fallback chain. @ai-sdk/huggingface (or the OpenAI-compatible router) as a cheap open-model tier behind Claude — absorbs overflow and degrades gracefully.
  • Gradio Space embedded in Next.js. <iframe> a ZeroGPU Space for a free GPU-backed demo (visitor quota applies).
  • HF Datasets → Postgres. load_dataset(...), transform, COPY into Postgres for app queries or fine-tune provenance.
  • Jobs / Sandboxes (hf jobs run, hf sandbox create) for one-off GPU batch work billed against credits.

Automation Workflows

Slash Command: quick open-model answer

.claude/commands/hf-ask.md:

Markdown
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

YAML
# .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 CaseApproach
Open-model chatInferenceClient.chatCompletion / @ai-sdk/huggingface / OpenAI SDK + router
Agentic tools, remote MCP, structured outputRouter Responses API (beta)
Hub exploration from Claude CodeHF MCP server (hf_fs, hub_repo_search, hub_repo_details)
Space deploymenthf repos create --sdk gradio + hf upload
EmbeddingsfeatureExtraction (e5 / bge-m3)
Swahili speech-to-textautomaticSpeechRecognition with openai/whisper-large-v3
Image generationtextToImage (FLUX.1-dev via fal-ai / replicate / wavespeed)

SkillUse it for
huggingface-skills:hf-cliScripting the hf CLI
huggingface-skills:huggingface-spaces / :huggingface-gradioBuilding & shipping Spaces / Gradio apps
huggingface-skills:huggingface-zerogpuZeroGPU-backed demos
huggingface-skills:huggingface-lora-space-builderLoRA fine-tune + Space in one go
huggingface-skills:trl-training / :train-sentence-transformersFine-tuning LLMs / embedders
huggingface-skills:transformers-jsBrowser/edge inference
huggingface-skills:huggingface-datasetsDataset loading & curation

codeAmani notes

  • AI routing: HF is the open-models slot. Complex reasoning and code gen stay on Claude; structured output/function calling on OpenAI. Use HF for open weights, fine-tunes, Swahili/multilingual embeddings and ASR, cheap overflow tiers, and free ZeroGPU demos.
  • Secrets: HF_TOKEN is server-side only (Vercel env / Hazina vault / Space secrets). One fine-grained token per app; inference-only tokens get just "Make calls to Inference Providers". Never NEXT_PUBLIC_ it.
  • Budget reality: PRO's included credit is $2/month, not a free tier — wire a spending limit and track usage at https://huggingface.co/settings/inference-providers/overview. Use billTo: "codeAmani-labs" once the org is on Team.
  • Live Space: codeAmani-labs/amani-swahili-chat — Qwen2.5-3B-Instruct, @spaces.GPU(duration=90), Gradio pinned 6.17.3. Keep examples/app.py in sync with it.
  • Payments: HF/Inference Providers are billed by card on the HF account. Product payments stay Stripe by default; M-Pesa (Daraja) only for Kenya-targeted projects.
  • African market: For Kenya-targeted apps, prefer server-side inference over shipping large browser models on 2G/3G; reuse multilingual-e5 for Swahili search; verify every model's license (many Swahili assets are CC-BY-NC); Swahili TTS is gated on a MOS eval before any voice pipeline ships.

Troubleshooting

IssueFix
401 UnauthorizedRe-login (hf auth login) or check HF_TOKEN
402 Payment RequiredOut of credits — buy credits or upgrade (free accounts have no included credits)
403 on a modelGated: accept the license with the token's account; or org token policy (pending / fine-grained only)
4xx when pinning a providerThe model may not be served by that provider — drop the :provider suffix or check /v1/models
ImportError after upgrading huggingface_hubv2 removed deprecated APIs + moved to httpx2 — see the v2 migration guide
huggingface-cli: command not foundRemoved 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 callModel moved to GPU lazily — move it to cuda at module scope
MCP server not connectingUse ?login OAuth or check the Bearer header; curl https://huggingface.co/mcp should return 200