Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Add Hugging Face inference provider (#985)

Ali Khokhard4683bf3f6d9
diff --git a/.env.example b/.env.example
index 97f4b4ed..4870ca87 100644
--- a/.env.example
+++ b/.env.example
@@ -38,6 +38,10 @@ OPENCODE_API_KEY=""
AI_GATEWAY_API_KEY=""
+# Hugging Face Inference Providers Config (OpenAI-compatible Chat Completions at router.huggingface.co/v1)
+HUGGINGFACE_API_KEY=""
+
+
# Z.ai Config (Anthropic-compatible Messages at api.z.ai/api/anthropic/v1)
ZAI_API_KEY=""
@@ -77,7 +81,7 @@ OLLAMA_BASE_URL="http://localhost:11434"
# All Claude model requests are mapped to these models, plain model is fallback
# Format: provider_type/model/name
-# Valid providers: "nvidia_nim" | "open_router" | "gemini" | "deepseek" | "mistral" | "mistral_codestral" | "opencode" | "opencode_go" | "vercel" | "wafer" | "kimi" | "minimax" | "cerebras" | "groq" | "fireworks" | "cloudflare" | "zai" | "lmstudio" | "llamacpp" | "ollama"
+# Valid providers: "nvidia_nim" | "open_router" | "gemini" | "deepseek" | "mistral" | "mistral_codestral" | "opencode" | "opencode_go" | "vercel" | "huggingface" | "wafer" | "kimi" | "minimax" | "cerebras" | "groq" | "fireworks" | "cloudflare" | "zai" | "lmstudio" | "llamacpp" | "ollama"
MODEL_OPUS=
MODEL_SONNET=
MODEL_HAIKU=
@@ -100,6 +104,7 @@ FCC_SMOKE_MODEL_MINIMAX=
FCC_SMOKE_MODEL_OPENCODE=
FCC_SMOKE_MODEL_OPENCODE_GO=
FCC_SMOKE_MODEL_VERCEL=
+FCC_SMOKE_MODEL_HUGGINGFACE=
FCC_SMOKE_MODEL_ZAI=
FCC_SMOKE_MODEL_FIREWORKS=
FCC_SMOKE_MODEL_CLOUDFLARE=
@@ -135,6 +140,7 @@ MINIMAX_PROXY=""
OPENCODE_PROXY=""
OPENCODE_GO_PROXY=""
VERCEL_AI_GATEWAY_PROXY=""
+HUGGINGFACE_PROXY=""
ZAI_PROXY=""
FIREWORKS_PROXY=""
CLOUDFLARE_PROXY=""
@@ -179,7 +185,6 @@ WHISPER_DEVICE="nvidia_nim"
# - For nvidia_nim: NVIDIA NIM model (e.g., "nvidia/parakeet-ctc-1.1b-asr", "openai/whisper-large-v3")
# - For nvidia_nim, default to "openai/whisper-large-v3" for best performance
WHISPER_MODEL="openai/whisper-large-v3"
-HF_TOKEN=""
# Telegram Config
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 0873bcdb..e460ac1f 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -371,9 +371,10 @@ where supported, and returning Anthropic SSE strings to the service layer.
Provider-specific inputs that do not apply to other upstreams, such as
Cloudflare's account ID, stay in that provider's factory/client instead of being
added to shared `ProviderConfig`.
-Gateway providers such as Vercel AI Gateway stay thin when their documented
-OpenAI-compatible Chat Completions behavior matches shared transport policy;
-provider-specific gateway options pass through request `extra_body`.
+Gateway providers such as Vercel AI Gateway and Hugging Face stay thin when
+their documented OpenAI-compatible Chat Completions behavior matches shared
+transport policy; provider-specific gateway options pass through request
+`extra_body`.
### Adding A Provider
diff --git a/README.md b/README.md
index 9b5c86a4..7ae1f9c6 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,7 @@ Free Claude Code routes Anthropic Messages API traffic from Claude Code (CLI and
- Drop-in proxy for Claude Code's Anthropic API calls (`/v1/messages`, `/v1/models`).
- Drop-in proxy for Codex via the OpenAI Responses API (`/v1/responses`).
- `fcc-claude` and `fcc-codex` launchers that read the current Admin UI port and auth token each time they start.
-- 20 provider backends: NVIDIA NIM, OpenRouter, Google AI Studio (Gemini), DeepSeek, Mistral La Plateforme, Mistral Codestral, OpenCode Zen, OpenCode Go, Vercel AI Gateway, Wafer, Kimi, MiniMax, Cerebras Inference, Groq, Fireworks AI, Cloudflare, Z.ai, LM Studio, llama.cpp, and Ollama.
+- 21 provider backends: NVIDIA NIM, OpenRouter, Google AI Studio (Gemini), DeepSeek, Mistral La Plateforme, Mistral Codestral, OpenCode Zen, OpenCode Go, Vercel AI Gateway, Hugging Face Inference Providers, Wafer, Kimi, MiniMax, Cerebras Inference, Groq, Fireworks AI, Cloudflare, Z.ai, LM Studio, llama.cpp, and Ollama.
- Per-model routing for Claude Code: send Opus, Sonnet, Haiku, and fallback traffic to different providers.
- Native Claude Code `/model` picker support through the proxy's `/v1/models` endpoint (see [Model Picker](#model-picker)).
- Native Codex `/model` picker support when launched through `fcc-codex`, using a generated local model catalog.
@@ -263,7 +263,19 @@ Vercel AI Gateway exposes an OpenAI-compatible endpoint at `https://ai-gateway.v
Browse models at [Vercel models and providers](https://vercel.com/docs/ai-gateway/models-and-providers).
-### 10. [Wafer](https://wafer.ai/)
+### 10. [Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers/)
+
+Create a Hugging Face token with Inference Providers permission at [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens), then paste it into `HUGGINGFACE_API_KEY` in the Admin UI.
+
+Set `MODEL` to a Hugging Face model slug such as `huggingface/openai/gpt-oss-120b:fastest`, `huggingface/Qwen/Qwen3-Coder-480B-A35B-Instruct:fastest`, or `huggingface/deepseek-ai/DeepSeek-R1:fastest`.
+
+Hugging Face routes through the OpenAI-compatible router at `https://router.huggingface.co/v1`. FCC uses the shared OpenAI-chat transport and preserves request `extra_body` for Hugging Face provider options.
+
+If your existing repo `.env` or `~/.fcc/.env` uses the old voice setting `HF_TOKEN`, `fcc-server`/`fcc-init` renames it to `HUGGINGFACE_API_KEY`. Explicit `FCC_ENV_FILE` files are not rewritten automatically; rename the key there manually.
+
+Browse models at [Hugging Face Inference Providers](https://huggingface.co/docs/inference-providers/).
+
+### 11. [Wafer](https://wafer.ai/)
Get a key from [wafer.ai](https://wafer.ai). In the Admin UI, paste it into `WAFER_API_KEY`, then set `MODEL` to a Wafer Pass model such as `wafer/DeepSeek-V4-Pro`.
@@ -276,7 +288,7 @@ Popular examples:
This provider uses Wafer's Anthropic-compatible endpoint at `https://pass.wafer.ai/v1/messages`.
-### 11. [Kimi](https://platform.moonshot.ai/)
+### 12. [Kimi](https://platform.moonshot.ai/)
Get a key at [platform.moonshot.ai/console/api-keys](https://platform.moonshot.ai/console/api-keys).
@@ -286,7 +298,7 @@ This provider calls Kimi's **Anthropic-compatible** Messages API (`https://api.m
Browse models at [platform.moonshot.ai](https://platform.moonshot.ai).
-### 12. [MiniMax](https://platform.minimax.io/)
+### 13. [MiniMax](https://platform.minimax.io/)
Get a key from [MiniMax](https://platform.minimax.io/user-center/basic-information/interface-key).
@@ -294,7 +306,7 @@ In the Admin UI, paste it into `MINIMAX_API_KEY`, then set `MODEL` to a MiniMax
This provider calls MiniMax's **Anthropic-compatible** Messages API (`https://api.minimax.io/anthropic/v1/messages`). `MiniMax-M3` is the recommended default because MiniMax documents controllable Anthropic thinking for that model; other MiniMax models remain discoverable through the provider model list.
-### 13. [Cerebras Inference](https://inference-docs.cerebras.ai/quickstart)
+### 14. [Cerebras Inference](https://inference-docs.cerebras.ai/quickstart)
Sign up and create an API key in the [Cerebras Cloud Console](https://cloud.cerebras.ai) (see [Quickstart](https://inference-docs.cerebras.ai/quickstart)).
@@ -302,7 +314,7 @@ In the Admin UI, set `CEREBRAS_API_KEY`, then route with `MODEL` such as `cerebr
Cerebras exposes an OpenAI-compatible API at `https://api.cerebras.ai/v1` ([OpenAI compatibility](https://inference-docs.cerebras.ai/resources/openai)). Non-standard request fields should go in `extra_body` when using the OpenAI client; see the same page. For reasoning models and parameters, see [Reasoning](https://inference-docs.cerebras.ai/capabilities/reasoning). This proxy follows other OpenAI-compat adapters for thinking via `reasoning_content` when Claude-style thinking is enabled.
-### 14. [Groq](https://console.groq.com/)
+### 15. [Groq](https://console.groq.com/)
Get an API key at [console.groq.com/keys](https://console.groq.com/keys).
@@ -314,7 +326,7 @@ Reasoning-heavy models expose extra knobs documented under [Groq reasoning](http
Browse models at [console.groq.com/docs/models](https://console.groq.com/docs/models).
-### 15. [Fireworks AI](https://fireworks.ai/)
+### 16. [Fireworks AI](https://fireworks.ai/)
Get an API key at [fireworks.ai/account/api-keys](https://fireworks.ai/account/api-keys).
@@ -324,7 +336,7 @@ Fireworks exposes an **Anthropic-compatible** Messages API at `https://api.firew
Browse models at [fireworks.ai/models](https://fireworks.ai/models).
-### 16. [Cloudflare](https://developers.cloudflare.com/workers-ai/)
+### 17. [Cloudflare](https://developers.cloudflare.com/workers-ai/)
Create a Cloudflare API token and copy your account ID from the Cloudflare dashboard.
@@ -332,7 +344,7 @@ In the Admin UI, set `CLOUDFLARE_API_TOKEN` and `CLOUDFLARE_ACCOUNT_ID`, then se
This provider calls Cloudflare's account-scoped **OpenAI-compatible** Chat Completions API at `https://api.cloudflare.com/client/v4/accounts/<account_id>/ai/v1/chat/completions`. Use literal Workers AI model IDs, including the `@cf/` prefix when the catalog model includes it.
-### 17. [Z.ai](https://z.ai/)
+### 18. [Z.ai](https://z.ai/)
Get an API key at [Z.ai/manage-apikey/apikey-list](https://z.ai/manage-apikey/apikey-list).
@@ -347,13 +359,13 @@ Popular examples:
Browse models at [Z.ai](https://z.ai).
-### 18. [LM Studio](https://lmstudio.ai/)
+### 19. [LM Studio](https://lmstudio.ai/)
Start LM Studio's local server and load a model. In the Admin UI, keep or update `LM_STUDIO_BASE_URL`, then set `MODEL` to the model identifier shown by LM Studio, prefixed with `lmstudio/`.
Prefer models with tool-use support for Claude Code workflows.
-### 19. [llama.cpp](https://github.com/ggml-org/llama.cpp)
+### 20. [llama.cpp](https://github.com/ggml-org/llama.cpp)
Start `llama-server` with an Anthropic-compatible `/v1/messages` endpoint and enough context for Claude Code requests.
@@ -361,7 +373,7 @@ In the Admin UI, keep or update `LLAMACPP_BASE_URL`, then set `MODEL` to the loc
For local coding models, context size matters. If llama.cpp returns HTTP 400 for normal Claude Code requests, increase `--ctx-size` and verify the model/server build supports the requested features.
-### 20. [Ollama](https://ollama.com/)
+### 21. [Ollama](https://ollama.com/)
Run Ollama and pull a model:
@@ -374,7 +386,7 @@ In the Admin UI, keep or update `OLLAMA_BASE_URL`, then set `MODEL` to the same
`OLLAMA_BASE_URL` is the Ollama server root; do not append `/v1`. Example model slugs include `ollama/llama3.1` and `ollama/llama3.1:8b`.
-### 21. Mix Providers By Model Tier
+### 22. Mix Providers By Model Tier
Each model tier can use a different provider by setting `MODEL_OPUS`, `MODEL_SONNET`, and `MODEL_HAIKU` in the Admin UI. Leave a tier blank to inherit `MODEL`. These tier overrides apply to Claude model names that contain `opus`, `sonnet`, or `haiku`. Codex uses the Admin `MODEL` default through `fcc-codex` unless a session requests a provider-prefixed slug directly.
@@ -571,7 +583,7 @@ Windows PowerShell:
Restart `fcc-server` after reinstalling.
-In the **Admin UI**, open **Messaging** and scroll to **Voice**. Turn on **Voice Notes**, choose **Whisper Device** (`cpu`, `cuda`, or `nvidia_nim`), set **Whisper Model**, and enter **Hugging Face Token** when your setup needs it. For **nvidia_nim** transcription, install the `voice` extra and set **NVIDIA NIM API Key** on the **Providers** view. The screenshot above shows the **Voice** block in the same view.
+In the **Admin UI**, open **Messaging** and scroll to **Voice**. Turn on **Voice Notes**, choose **Whisper Device** (`cpu`, `cuda`, or `nvidia_nim`), and set **Whisper Model**. For gated local Whisper models, set **Hugging Face API Key** on the **Providers** view. For **nvidia_nim** transcription, install the `voice` extra and set **NVIDIA NIM API Key** on the **Providers** view. The screenshot above shows the **Voice** block in the same view.
## How It Works
@@ -588,7 +600,7 @@ Important pieces:
- Responses requests convert to Anthropic Messages internally, then share the same model router, normalizer, and provider adapters.
- `fcc-codex` registers a custom `fcc` provider that points Codex at the local proxy's `/v1/responses` endpoint.
- Model routing resolves Claude model names to `MODEL_OPUS`, `MODEL_SONNET`, `MODEL_HAIKU`, or `MODEL`.
-- NIM, Gemini, DeepSeek, Mistral, Codestral, OpenCode Zen, OpenCode Go, Vercel AI Gateway, Cerebras, Groq, and Cloudflare use OpenAI chat streaming translated into Anthropic SSE.
+- NIM, Gemini, DeepSeek, Mistral, Codestral, OpenCode Zen, OpenCode Go, Vercel AI Gateway, Hugging Face, Cerebras, Groq, and Cloudflare use OpenAI chat streaming translated into Anthropic SSE.
- Wafer, OpenRouter, Kimi, MiniMax, Fireworks AI, Z.ai, LM Studio, llama.cpp, and Ollama use Anthropic Messages style transports where applicable (with provider-specific quirks and model-list URLs).
- The proxy normalizes thinking blocks, tool calls, token usage metadata, and provider errors into the shape each client expects.
- Request optimizations answer trivial Claude Code probes locally to save latency and quota.
diff --git a/api/admin_config/manifest.py b/api/admin_config/manifest.py
index d2f61b31..f1fe8241 100644
--- a/api/admin_config/manifest.py
+++ b/api/admin_config/manifest.py
@@ -338,15 +338,6 @@ _NON_PROVIDER_FIELDS: tuple[ConfigFieldSpec, ...] = (
default="openai/whisper-large-v3",
session_sensitive=True,
),
- ConfigFieldSpec(
- "HF_TOKEN",
- "Hugging Face Token",
- "voice",
- "secret",
- settings_attr="hf_token",
- secret=True,
- session_sensitive=True,
- ),
ConfigFieldSpec(
"FAST_PREFIX_DETECTION",
"Fast Prefix Detection",
@@ -565,6 +556,18 @@ _NON_PROVIDER_FIELDS: tuple[ConfigFieldSpec, ...] = (
"smoke",
advanced=True,
),
+ ConfigFieldSpec(
+ "FCC_SMOKE_MODEL_VERCEL",
+ "Smoke Vercel AI Gateway Model",
+ "smoke",
+ advanced=True,
+ ),
+ ConfigFieldSpec(
+ "FCC_SMOKE_MODEL_HUGGINGFACE",
+ "Smoke Hugging Face Model",
+ "smoke",
+ advanced=True,
+ ),
ConfigFieldSpec(
"FCC_SMOKE_MODEL_ZAI",
"Smoke Z.ai Model",
diff --git a/api/admin_config/provider_manifest.py b/api/admin_config/provider_manifest.py
index a88602a4..5d26edae 100644
--- a/api/admin_config/provider_manifest.py
+++ b/api/admin_config/provider_manifest.py
@@ -37,6 +37,13 @@ _PROVIDER_FIELD_OVERRIDES: dict[str, dict[str, Any]] = {
"ai-gateway.vercel.sh/v1."
),
},
+ "HUGGINGFACE_API_KEY": {
+ "label": "Hugging Face API Key",
+ "description": (
+ "Hugging Face token with Inference Providers permission; also used "
+ "for local Whisper model downloads when voice notes need gated models."
+ ),
+ },
"ZAI_API_KEY": {
"label": "Z.ai API Key",
"description": "Z.ai Coding Plan API key.",
diff --git a/api/runtime.py b/api/runtime.py
index e463f4d7..2c0b27fc 100644
--- a/api/runtime.py
+++ b/api/runtime.py
@@ -190,7 +190,7 @@ class AppRuntime:
voice_note_enabled=self.settings.voice_note_enabled,
whisper_model=self.settings.whisper_model,
whisper_device=self.settings.whisper_device,
- hf_token=self.settings.hf_token,
+ huggingface_api_key=self.settings.huggingface_api_key,
nvidia_nim_api_key=self.settings.nvidia_nim_api_key,
messaging_rate_limit=self.settings.messaging_rate_limit,
messaging_rate_window=self.settings.messaging_rate_window,
diff --git a/cli/entrypoints.py b/cli/entrypoints.py
index 64b8ef86..edfe49c1 100644
--- a/cli/entrypoints.py
+++ b/cli/entrypoints.py
@@ -2,6 +2,7 @@
import os
import shutil
+import sys
import threading
import time
import webbrowser
@@ -15,6 +16,10 @@ from cli.launchers.common import preflight_proxy
from cli.process_registry import (
kill_all_best_effort,
)
+from config.env_migrations import (
+ explicit_env_file_huggingface_warning,
+ migrate_owned_env_files,
+)
from config.env_template import load_env_template
from config.paths import (
config_dir_path,
@@ -33,6 +38,7 @@ def serve() -> None:
try:
while True:
_migrate_legacy_env_if_missing()
+ _migrate_config_env_keys()
settings = get_settings()
if not _run_supervised_server(
settings, open_admin_browser=not opened_admin_browser
@@ -111,6 +117,7 @@ def init() -> None:
env_file = managed_env_path()
migrated_from = _migrate_legacy_env_if_missing()
+ _migrate_config_env_keys()
if migrated_from is not None:
print(f"Config migrated from {migrated_from} to {env_file}")
print(
@@ -146,3 +153,12 @@ def _migrate_legacy_env_if_missing() -> Path | None:
return legacy_env
return None
+
+
+def _migrate_config_env_keys() -> tuple[Path, ...]:
+ """Apply dotenv key migrations before Settings loads config."""
+
+ migrated = migrate_owned_env_files()
+ if warning := explicit_env_file_huggingface_warning(os.environ):
+ print(warning, file=sys.stderr)
+ return migrated
diff --git a/config/env_migrations.py b/config/env_migrations.py
new file mode 100644
index 00000000..91279b92
--- /dev/null
+++ b/config/env_migrations.py
@@ -0,0 +1,129 @@
+"""One-time dotenv key migrations for FCC-owned config files."""
+
+import re
+from collections.abc import Mapping
+from dataclasses import dataclass
+from pathlib import Path
+
+from .env_files import explicit_env_path, repo_env_path
+from .paths import managed_env_path
+
+LEGACY_HUGGINGFACE_TOKEN_ENV = "HF_TOKEN"
+HUGGINGFACE_API_KEY_ENV = "HUGGINGFACE_API_KEY"
+
+_DOTENV_ASSIGNMENT_RE = re.compile(
+ r"^(?P<prefix>\s*(?:export\s+)?)(?P<key>[A-Za-z_][A-Za-z0-9_]*)(?P<suffix>\s*(?:=|$))"
+)
+
+
+@dataclass(frozen=True, slots=True)
+class EnvKeyMigration:
+ """A dotenv key rename migration."""
+
+ old_key: str
+ new_key: str
+
+
+HUGGINGFACE_TOKEN_MIGRATION = EnvKeyMigration(
+ old_key=LEGACY_HUGGINGFACE_TOKEN_ENV,
+ new_key=HUGGINGFACE_API_KEY_ENV,
+)
+
+
+def migrate_owned_env_files() -> tuple[Path, ...]:
+ """Apply key migrations to repo and managed dotenv files."""
+
+ return tuple(
+ path.resolve()
+ for path in _unique_paths((repo_env_path(), managed_env_path()))
+ if migrate_env_key_in_file(path, HUGGINGFACE_TOKEN_MIGRATION)
+ )
+
+
+def explicit_env_file_huggingface_warning(
+ env: Mapping[str, str] | None = None,
+) -> str | None:
+ """Return a warning when an explicit env file still uses ``HF_TOKEN``."""
+
+ path = explicit_env_path(env)
+ if path is None or not path.is_file():
+ return None
+ text = path.read_text(encoding="utf-8")
+ if not env_text_needs_migration(text, HUGGINGFACE_TOKEN_MIGRATION):
+ return None
+ return (
+ f"{LEGACY_HUGGINGFACE_TOKEN_ENV} is set in explicit FCC_ENV_FILE {path}. "
+ f"Rename it to {HUGGINGFACE_API_KEY_ENV}; explicit env files are not "
+ "rewritten automatically."
+ )
+
+
+def migrate_env_key_in_file(path: Path, migration: EnvKeyMigration) -> bool:
+ """Rename a dotenv key in ``path`` when the new key is absent."""
+
+ if not path.is_file():
+ return False
+ original = path.read_text(encoding="utf-8")
+ migrated, changed = migrate_env_key_in_text(original, migration)
+ if not changed:
+ return False
+ path.write_text(migrated, encoding="utf-8")
+ return True
+
+
+def migrate_env_key_in_text(
+ text: str,
+ migration: EnvKeyMigration,
+) -> tuple[str, bool]:
+ """Return text with ``old_key`` renamed to ``new_key`` when safe."""
+
+ if _defines_key(text, migration.new_key):
+ return text, False
+
+ lines = text.splitlines(keepends=True)
+ changed = False
+ for index, line in enumerate(lines):
+ match = _DOTENV_ASSIGNMENT_RE.match(line)
+ if match is None or match.group("key") != migration.old_key:
+ continue
+ lines[index] = (
+ f"{match.group('prefix')}{migration.new_key}{match.group('suffix')}"
+ f"{line[match.end() :]}"
+ )
+ changed = True
+ if not changed:
+ return text, False
+ return "".join(lines), True
+
+
+def env_text_needs_migration(text: str, migration: EnvKeyMigration) -> bool:
+ """Return whether text defines old key without new key."""
+
+ return _defines_key(text, migration.old_key) and not _defines_key(
+ text, migration.new_key
+ )
+
+
+def _defines_key(text: str, key: str) -> bool:
+ for line in text.splitlines():
+ if line.lstrip().startswith("#"):
+ continue
+ match = _DOTENV_ASSIGNMENT_RE.match(line)
+ if match is not None and match.group("key") == key:
+ return True
+ return False
+
+
+def _unique_paths(paths: tuple[Path, ...]) -> tuple[Path, ...]:
+ seen: set[Path] = set()
+ unique: list[Path] = []
+ for path in paths:
+ try:
+ resolved = path.resolve()
+ except OSError:
+ resolved = path
+ if resolved in seen:
+ continue
+ seen.add(resolved)
+ unique.append(path)
+ return tuple(unique)
diff --git a/config/provider_catalog.py b/config/provider_catalog.py
index 5895c057..1a249d87 100644
--- a/config/provider_catalog.py
+++ b/config/provider_catalog.py
@@ -30,6 +30,7 @@ OLLAMA_DEFAULT_BASE = "http://localhost:11434"
OPENCODE_DEFAULT_BASE = "https://opencode.ai/zen/v1"
OPENCODE_GO_DEFAULT_BASE = "https://opencode.ai/zen/go/v1"
VERCEL_AI_GATEWAY_DEFAULT_BASE = "https://ai-gateway.vercel.sh/v1"
+HUGGINGFACE_DEFAULT_BASE = "https://router.huggingface.co/v1"
# Z.ai Anthropic-compatible Messages API (not OpenAI Coding Plan chat completions).
ZAI_DEFAULT_BASE = "https://api.z.ai/api/anthropic/v1"
# Google AI Studio Gemini API OpenAI-compat layer (not Vertex AI).
@@ -154,6 +155,17 @@ PROVIDER_CATALOG: dict[str, ProviderDescriptor] = {
proxy_attr="vercel_ai_gateway_proxy",
capabilities=("chat", "streaming", "tools", "thinking", "rate_limit"),
),
+ "huggingface": ProviderDescriptor(
+ provider_id="huggingface",
+ display_name="Hugging Face",
+ transport_type="openai_chat",
+ credential_env="HUGGINGFACE_API_KEY",
+ credential_url="https://huggingface.co/settings/tokens",
+ credential_attr="huggingface_api_key",
+ default_base_url=HUGGINGFACE_DEFAULT_BASE,
+ proxy_attr="huggingface_proxy",
+ capabilities=("chat", "streaming", "tools", "thinking", "rate_limit"),
+ ),
"wafer": ProviderDescriptor(
provider_id="wafer",
display_name="Wafer",
@@ -314,9 +326,9 @@ PROVIDER_CATALOG: dict[str, ProviderDescriptor] = {
# Key order:
# NVIDIA NIM first (README default), DeepSeek fourth, OpenCode gateways adjacent,
-# Vercel follows gateway-style remotes, then native Anthropic remotes and locals
-# per project plan (github.com/cheahjs/free-llm-api-resources Free Providers TOC
-# as rough guide beyond fixed slots).
+# Vercel / Hugging Face follow gateway-style remotes, then native Anthropic
+# remotes and locals per project plan (github.com/cheahjs/free-llm-api-resources
+# Free Providers TOC as rough guide beyond fixed slots).
# ``SUPPORTED_PROVIDER_IDS`` inherits this insertion order for UI and error-message listing.
SUPPORTED_PROVIDER_IDS: tuple[str, ...] = tuple(PROVIDER_CATALOG.keys())
diff --git a/config/settings.py b/config/settings.py
index d1ed657e..0f394b15 100644
--- a/config/settings.py
+++ b/config/settings.py
@@ -49,6 +49,9 @@ class Settings(BaseSettings):
default="", validation_alias="AI_GATEWAY_API_KEY"
)
+ # ==================== Hugging Face Inference Providers ====================
+ huggingface_api_key: str = Field(default="", validation_alias="HUGGINGFACE_API_KEY")
+
# ==================== Z.ai Config ====================
zai_api_key: str = Field(default="", validation_alias="ZAI_API_KEY")
@@ -131,6 +134,7 @@ class Settings(BaseSettings):
vercel_ai_gateway_proxy: str = Field(
default="", validation_alias="VERCEL_AI_GATEWAY_PROXY"
)
+ huggingface_proxy: str = Field(default="", validation_alias="HUGGINGFACE_PROXY")
zai_proxy: str = Field(default="", validation_alias="ZAI_PROXY")
fireworks_proxy: str = Field(default="", validation_alias="FIREWORKS_PROXY")
cloudflare_proxy: str = Field(default="", validation_alias="CLOUDFLARE_PROXY")
@@ -240,9 +244,6 @@ class Settings(BaseSettings):
# Local Whisper: "tiny", "base", "small", "medium", "large-v2", "large-v3", "large-v3-turbo"
# NVIDIA NIM: "nvidia/parakeet-ctc-1.1b-asr", "openai/whisper-large-v3", etc.
whisper_model: str = Field(default="base", validation_alias="WHISPER_MODEL")
- # Hugging Face token for faster model downloads (optional, for local Whisper)
- hf_token: str = Field(default="", validation_alias="HF_TOKEN")
-
# ==================== Bot Wrapper Config ====================
telegram_bot_token: str | None = None
allowed_telegram_user_id: str | None = None
diff --git a/messaging/platforms/discord.py b/messaging/platforms/discord.py
index f23dbd86..c7aab7d8 100644
--- a/messaging/platforms/discord.py
+++ b/messaging/platforms/discord.py
@@ -77,7 +77,7 @@ class DiscordRuntime:
voice_note_enabled: bool = True,
whisper_model: str = "base",
whisper_device: str = "cpu",
- hf_token: str = "",
+ huggingface_api_key: str = "",
nvidia_nim_api_key: str = "",
messaging_rate_limit: int = 1,
messaging_rate_window: float = 1.0,
@@ -113,7 +113,7 @@ class DiscordRuntime:
voice_note_enabled=voice_note_enabled,
whisper_model=whisper_model,
whisper_device=whisper_device,
- hf_token=hf_token,
+ huggingface_api_key=huggingface_api_key,
nvidia_nim_api_key=nvidia_nim_api_key,
log_raw_messaging_content=log_raw_messaging_content,
log_api_error_tracebacks=log_api_error_tracebacks,
diff --git a/messaging/platforms/factory.py b/messaging/platforms/factory.py
index 60b96cd7..adf9dfc1 100644
--- a/messaging/platforms/factory.py
+++ b/messaging/platforms/factory.py
@@ -18,7 +18,7 @@ class MessagingPlatformOptions:
voice_note_enabled: bool = True
whisper_model: str = "base"
whisper_device: str = "cpu"
- hf_token: str = ""
+ huggingface_api_key: str = ""
nvidia_nim_api_key: str = ""
messaging_rate_limit: int = 1
messaging_rate_window: float = 1.0
@@ -50,7 +50,7 @@ def create_messaging_components(
voice_note_enabled=opts.voice_note_enabled,
whisper_model=opts.whisper_model,
whisper_device=opts.whisper_device,
- hf_token=opts.hf_token,
+ huggingface_api_key=opts.huggingface_api_key,
nvidia_nim_api_key=opts.nvidia_nim_api_key,
messaging_rate_limit=opts.messaging_rate_limit,
messaging_rate_window=opts.messaging_rate_window,
@@ -78,7 +78,7 @@ def create_messaging_components(
voice_note_enabled=opts.voice_note_enabled,
whisper_model=opts.whisper_model,
whisper_device=opts.whisper_device,
- hf_token=opts.hf_token,
+ huggingface_api_key=opts.huggingface_api_key,
nvidia_nim_api_key=opts.nvidia_nim_api_key,
messaging_rate_limit=opts.messaging_rate_limit,
messaging_rate_window=opts.messaging_rate_window,
diff --git a/messaging/platforms/telegram.py b/messaging/platforms/telegram.py
index 8c6df412..9f4da856 100644
--- a/messaging/platforms/telegram.py
+++ b/messaging/platforms/telegram.py
@@ -52,7 +52,7 @@ class TelegramRuntime:
voice_note_enabled: bool = True,
whisper_model: str = "base",
whisper_device: str = "cpu",
- hf_token: str = "",
+ huggingface_api_key: str = "",
nvidia_nim_api_key: str = "",
messaging_rate_limit: int = 1,
messaging_rate_window: float = 1.0,
@@ -81,7 +81,7 @@ class TelegramRuntime:
voice_note_enabled=voice_note_enabled,
whisper_model=whisper_model,
whisper_device=whisper_device,
- hf_token=hf_token,
+ huggingface_api_key=huggingface_api_key,
nvidia_nim_api_key=nvidia_nim_api_key,
log_raw_messaging_content=log_raw_messaging_content,
log_api_error_tracebacks=log_api_error_tracebacks,
diff --git a/messaging/platforms/voice_flow.py b/messaging/platforms/voice_flow.py
index c1d63758..fa7ade3c 100644
--- a/messaging/platforms/voice_flow.py
+++ b/messaging/platforms/voice_flow.py
@@ -90,7 +90,7 @@ class VoiceNoteFlow:
voice_note_enabled: bool,
whisper_model: str,
whisper_device: str,
- hf_token: str,
+ huggingface_api_key: str,
nvidia_nim_api_key: str,
log_raw_messaging_content: bool,
log_api_error_tracebacks: bool,
@@ -102,7 +102,7 @@ class VoiceNoteFlow:
self._log_api_error_tracebacks = log_api_error_tracebacks
self._pending_voice = PendingVoiceRegistry()
self._voice_transcription = VoiceTranscriptionService(
- hf_token=hf_token,
+ huggingface_api_key=huggingface_api_key,
nvidia_nim_api_key=nvidia_nim_api_key,
)
diff --git a/messaging/transcription.py b/messaging/transcription.py
index 9a5f01ff..d6a021ee 100644
--- a/messaging/transcription.py
+++ b/messaging/transcription.py
@@ -28,7 +28,7 @@ _MODEL_MAP: dict[str, str] = {
"large-v3-turbo": "openai/whisper-large-v3-turbo",
}
-# Lazy-loaded pipelines: (model_id, device, hf_token_fingerprint) -> pipeline
+# Lazy-loaded pipelines: (model_id, device, Hugging Face API key fingerprint) -> pipeline
_pipeline_cache: dict[tuple[str, str, str], Any] = {}
@@ -37,12 +37,12 @@ def _resolve_model_id(whisper_model: str) -> str:
return _MODEL_MAP.get(whisper_model, whisper_model)
-def _get_pipeline(model_id: str, device: str, hf_token: str = "") -> Any:
+def _get_pipeline(model_id: str, device: str, huggingface_api_key: str = "") -> Any:
"""Lazy-load transformers Whisper pipeline. Raises ImportError if not installed."""
global _pipeline_cache
if device not in ("cpu", "cuda"):
raise ValueError(f"whisper_device must be 'cpu' or 'cuda', got {device!r}")
- resolved_token = hf_token or ""
+ resolved_token = huggingface_api_key or ""
cache_key = (model_id, device, resolved_token)
if cache_key not in _pipeline_cache:
try:
@@ -89,7 +89,7 @@ def transcribe_audio(
*,
whisper_model: str = "base",
whisper_device: str = "cpu",
- hf_token: str = "",
+ huggingface_api_key: str = "",
nvidia_nim_api_key: str = "",
) -> str:
"""
@@ -128,7 +128,10 @@ def transcribe_audio(
file_path, whisper_model, api_key=nvidia_nim_api_key
)
return _transcribe_local(
- file_path, whisper_model, whisper_device, hf_token=hf_token
+ file_path,
+ whisper_model,
+ whisper_device,
+ huggingface_api_key=huggingface_api_key,
)
@@ -149,11 +152,13 @@ def _transcribe_local(
whisper_model: str,
whisper_device: str,
*,
- hf_token: str = "",
+ huggingface_api_key: str = "",
) -> str:
"""Transcribe using transformers Whisper pipeline."""
model_id = _resolve_model_id(whisper_model)
- pipe = _get_pipeline(model_id, whisper_device, hf_token=hf_token)
+ pipe = _get_pipeline(
+ model_id, whisper_device, huggingface_api_key=huggingface_api_key
+ )
audio = _load_audio(file_path)
result = pipe(audio, generate_kwargs={"language": "en", "task": "transcribe"})
text = result.get("text", "") or ""
diff --git a/messaging/voice.py b/messaging/voice.py
index 6d067757..a1971f16 100644
--- a/messaging/voice.py
+++ b/messaging/voice.py
@@ -47,10 +47,10 @@ class VoiceTranscriptionService:
def __init__(
self,
*,
- hf_token: str = "",
+ huggingface_api_key: str = "",
nvidia_nim_api_key: str = "",
) -> None:
- self._hf_token = hf_token
+ self._huggingface_api_key = huggingface_api_key
self._nvidia_nim_api_key = nvidia_nim_api_key
async def transcribe(
@@ -69,6 +69,6 @@ class VoiceTranscriptionService:
mime_type,
whisper_model=whisper_model,
whisper_device=whisper_device,
- hf_token=self._hf_token,
+ huggingface_api_key=self._huggingface_api_key,
nvidia_nim_api_key=self._nvidia_nim_api_key,
)
diff --git a/providers/defaults.py b/providers/defaults.py
index df469c4a..633ba1e5 100644
--- a/providers/defaults.py
+++ b/providers/defaults.py
@@ -7,6 +7,7 @@ from config.provider_catalog import (
DEEPSEEK_DEFAULT_BASE,
GEMINI_DEFAULT_BASE,
GROQ_DEFAULT_BASE,
+ HUGGINGFACE_DEFAULT_BASE,
KIMI_DEFAULT_BASE,
LLAMACPP_DEFAULT_BASE,
LMSTUDIO_DEFAULT_BASE,
@@ -29,6 +30,7 @@ __all__ = (
"DEEPSEEK_DEFAULT_BASE",
"GEMINI_DEFAULT_BASE",
"GROQ_DEFAULT_BASE",
+ "HUGGINGFACE_DEFAULT_BASE",
"KIMI_DEFAULT_BASE",
"LLAMACPP_DEFAULT_BASE",
"LMSTUDIO_DEFAULT_BASE",
diff --git a/providers/huggingface/__init__.py b/providers/huggingface/__init__.py
new file mode 100644
index 00000000..32a50e64
--- /dev/null
+++ b/providers/huggingface/__init__.py
@@ -0,0 +1,7 @@
+"""Hugging Face Inference Providers OpenAI-compatible adapter."""
+
+from providers.defaults import HUGGINGFACE_DEFAULT_BASE
+
+from .client import HuggingFaceProvider
+
+__all__ = ["HUGGINGFACE_DEFAULT_BASE", "HuggingFaceProvider"]
diff --git a/providers/huggingface/client.py b/providers/huggingface/client.py
new file mode 100644
index 00000000..61ecb8af
--- /dev/null
+++ b/providers/huggingface/client.py
@@ -0,0 +1,37 @@
+"""Hugging Face Inference Providers implementation."""
+
+from typing import Any
+
+from providers.base import ProviderConfig
+from providers.defaults import HUGGINGFACE_DEFAULT_BASE
+from providers.transports.openai_chat import (
+ OpenAIChatRequestPolicy,
+ OpenAIChatTransport,
+ build_openai_chat_request_body,
+)
+
+_REQUEST_POLICY = OpenAIChatRequestPolicy(
+ provider_name="HUGGINGFACE",
+ include_extra_body=True,
+)
+
+
+class HuggingFaceProvider(OpenAIChatTransport):
+ """Hugging Face Inference Providers router at ``https://router.huggingface.co/v1``."""
+
+ def __init__(self, config: ProviderConfig):
+ super().__init__(
+ config,
+ provider_name="HUGGINGFACE",
+ base_url=config.base_url or HUGGINGFACE_DEFAULT_BASE,
+ api_key=config.api_key,
+ )
+
+ def _build_request_body(
+ self, request: Any, thinking_enabled: bool | None = None
+ ) -> dict:
+ return build_openai_chat_request_body(
+ request,
+ thinking_enabled=self._is_thinking_enabled(request, thinking_enabled),
+ policy=_REQUEST_POLICY,
+ )
diff --git a/providers/runtime/factory.py b/providers/runtime/factory.py
index 2b013672..cfe3b8b8 100644
--- a/providers/runtime/factory.py
+++ b/providers/runtime/factory.py
@@ -101,6 +101,12 @@ def _create_vercel(config: ProviderConfig, _settings: Settings) -> BaseProvider:
return VercelProvider(config)
+def _create_huggingface(config: ProviderConfig, _settings: Settings) -> BaseProvider:
+ from providers.huggingface import HuggingFaceProvider
+
+ return HuggingFaceProvider(config)
+
+
def _create_zai(config: ProviderConfig, _settings: Settings) -> BaseProvider:
from providers.zai import ZaiProvider
@@ -147,6 +153,7 @@ PROVIDER_FACTORIES: dict[str, ProviderFactory] = {
"opencode": _create_opencode,
"opencode_go": _create_opencode_go,
"vercel": _create_vercel,
+ "huggingface": _create_huggingface,
"wafer": _create_wafer,
"kimi": _create_kimi,
"minimax": _create_minimax,
diff --git a/pyproject.toml b/pyproject.toml
index 594e04fa..ddd28086 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "2.6.0"
+version = "3.0.0"
description = "Middleware between Claude Code CLI (Anthropic API) and NVIDIA NIM"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/smoke/lib/config.py b/smoke/lib/config.py
index 05a06df8..d7346e6f 100644
--- a/smoke/lib/config.py
+++ b/smoke/lib/config.py
@@ -54,6 +54,7 @@ PROVIDER_SMOKE_DEFAULT_MODELS: dict[str, str] = {
"opencode": "opencode/gpt-5.3-codex",
"opencode_go": "opencode_go/minimax-m2.7",
"vercel": "vercel/openai/gpt-5.5",
+ "huggingface": "huggingface/openai/gpt-oss-120b:fastest",
"zai": "zai/glm-5.1",
"gemini": "gemini/models/gemini-3.1-flash-lite",
"groq": "groq/llama-3.3-70b-versatile",
@@ -255,6 +256,8 @@ class SmokeConfig:
return bool(self.settings.opencode_api_key.strip())
if provider == "vercel":
return bool(self.settings.vercel_ai_gateway_api_key.strip())
+ if provider == "huggingface":
+ return bool(self.settings.huggingface_api_key.strip())
if provider == "zai":
return bool(self.settings.zai_api_key.strip())
if provider == "gemini":
diff --git a/tests/api/test_admin.py b/tests/api/test_admin.py
index 795719ab..822eaccc 100644
--- a/tests/api/test_admin.py
+++ b/tests/api/test_admin.py
@@ -315,6 +315,31 @@ def test_admin_apply_writes_cloudflare_fields_and_masks_preview(monkeypatch, tmp
assert "CLOUDFLARE_ACCOUNT_ID=cf-account" in text
+def test_admin_apply_writes_huggingface_key_and_masks_preview(monkeypatch, tmp_path):
+ _set_home(monkeypatch, tmp_path)
+ _clear_process_config(monkeypatch)
+ app = create_app(lifespan_enabled=False)
+
+ response = _local_client(app).post(
+ "/admin/api/config/apply",
+ json={
+ "values": {
+ "MODEL": "huggingface/openai/gpt-oss-120b:fastest",
+ "HUGGINGFACE_API_KEY": "hf-secret",
+ }
+ },
+ )
+
+ assert response.status_code == 200
+ body = response.json()
+ assert body["applied"] is True
+ assert "HUGGINGFACE_API_KEY=********" in body["env_preview"]
+ env_file = tmp_path / ".fcc" / ".env"
+ text = env_file.read_text(encoding="utf-8")
+ assert "MODEL=huggingface/openai/gpt-oss-120b:fastest" in text
+ assert "HUGGINGFACE_API_KEY=hf-secret" in text
+
+
def test_admin_apply_preserves_hidden_diagnostics_and_smoke_values(
monkeypatch, tmp_path
):
diff --git a/tests/api/test_app_lifespan_and_errors.py b/tests/api/test_app_lifespan_and_errors.py
index bf239c84..81ab028e 100644
--- a/tests/api/test_app_lifespan_and_errors.py
+++ b/tests/api/test_app_lifespan_and_errors.py
@@ -21,7 +21,7 @@ _RUNTIME_EXTRAS = {
"voice_note_enabled": True,
"whisper_model": "base",
"whisper_device": "cpu",
- "hf_token": "",
+ "huggingface_api_key": "",
"nvidia_nim_api_key": "",
"messaging_rate_limit": 1,
"messaging_rate_window": 1.0,
diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.py
index 8b6d8408..1467fc72 100644
--- a/tests/cli/test_entrypoints.py
+++ b/tests/cli/test_entrypoints.py
@@ -286,6 +286,52 @@ def test_serve_migrates_legacy_env_before_loading_settings(tmp_path: Path) -> No
get_settings.assert_called_once_with()
+def test_serve_migrates_hf_token_before_loading_settings(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ from cli import entrypoints
+
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ (repo / ".env").write_text("HF_TOKEN=legacy-hf\n", encoding="utf-8")
+ settings = _launcher_settings()
+ get_settings = MagicMock(return_value=settings)
+ get_settings.cache_clear = MagicMock()
+ monkeypatch.chdir(repo)
+
+ with (
+ patch("pathlib.Path.home", return_value=tmp_path),
+ patch.object(entrypoints, "get_settings", get_settings),
+ patch.object(entrypoints, "_run_supervised_server", return_value=False),
+ patch.object(entrypoints, "kill_all_best_effort"),
+ patch.object(entrypoints, "explicit_env_file_huggingface_warning"),
+ ):
+ entrypoints.serve()
+
+ assert (repo / ".env").read_text(encoding="utf-8") == (
+ "HUGGINGFACE_API_KEY=legacy-hf\n"
+ )
+ get_settings.assert_called_once_with()
+
+
+def test_config_env_key_migration_warns_for_explicit_env_file(
+ tmp_path: Path,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ from cli import entrypoints
+
+ explicit = tmp_path / "custom.env"
+ explicit.write_text("HF_TOKEN=legacy-hf\n", encoding="utf-8")
+
+ with patch.dict(entrypoints.os.environ, {"FCC_ENV_FILE": str(explicit)}):
+ migrated = entrypoints._migrate_config_env_keys()
+
+ assert migrated == ()
+ assert "HF_TOKEN" in capsys.readouterr().err
+ assert explicit.read_text(encoding="utf-8") == "HF_TOKEN=legacy-hf\n"
+
+
def test_serve_handles_keyboard_interrupt_without_traceback() -> None:
from cli import entrypoints
diff --git a/tests/config/test_config.py b/tests/config/test_config.py
index b3a03780..1130f734 100644
--- a/tests/config/test_config.py
+++ b/tests/config/test_config.py
@@ -316,6 +316,27 @@ class TestSettings:
assert settings.vercel_ai_gateway_api_key == "vercel-key"
assert settings.vercel_ai_gateway_proxy == "http://proxy.test:8080"
+ def test_huggingface_settings_from_env(self, monkeypatch):
+ """Hugging Face key and proxy env vars load into settings."""
+ from config.settings import Settings
+
+ monkeypatch.setenv("HUGGINGFACE_API_KEY", "hf-key")
+ monkeypatch.setenv("HUGGINGFACE_PROXY", "http://proxy.test:8080")
+ settings = Settings()
+ assert settings.huggingface_api_key == "hf-key"
+ assert settings.huggingface_proxy == "http://proxy.test:8080"
+ assert not hasattr(settings, "hf_token")
+
+ def test_legacy_hf_token_env_is_ignored(self, monkeypatch):
+ """HF_TOKEN is migrated by startup config migration, not read by Settings."""
+ from config.settings import Settings
+
+ monkeypatch.setenv("HF_TOKEN", "legacy-token")
+ monkeypatch.delenv("HUGGINGFACE_API_KEY", raising=False)
+ settings = Settings()
+ assert settings.huggingface_api_key == ""
+ assert not hasattr(settings, "hf_token")
+
def test_per_model_thinking_from_env(self, monkeypatch):
"""Per-model thinking env vars are loaded into settings."""
from config.settings import Settings
@@ -894,6 +915,10 @@ class TestPerModelMapping:
parse_provider_type("cloudflare/@cf/moonshotai/kimi-k2.6") == "cloudflare"
)
assert parse_provider_type("vercel/openai/gpt-5.5") == "vercel"
+ assert (
+ parse_provider_type("huggingface/openai/gpt-oss-120b:fastest")
+ == "huggingface"
+ )
assert parse_provider_type("gemini/models/gemini-3.1-flash-lite") == "gemini"
assert parse_provider_type("groq/llama-3.3-70b-versatile") == "groq"
assert parse_provider_type("cerebras/llama3.1-8b") == "cerebras"
@@ -919,6 +944,10 @@ class TestPerModelMapping:
== "@cf/moonshotai/kimi-k2.6"
)
assert parse_model_name("vercel/openai/gpt-5.5") == "openai/gpt-5.5"
+ assert (
+ parse_model_name("huggingface/openai/gpt-oss-120b:fastest")
+ == "openai/gpt-oss-120b:fastest"
+ )
assert (
parse_model_name("gemini/models/gemini-3.1-flash-lite")
== "models/gemini-3.1-flash-lite"
diff --git a/tests/config/test_env_migrations.py b/tests/config/test_env_migrations.py
new file mode 100644
index 00000000..b886d9f5
--- /dev/null
+++ b/tests/config/test_env_migrations.py
@@ -0,0 +1,92 @@
+from pathlib import Path
+
+from config.env_migrations import (
+ HUGGINGFACE_API_KEY_ENV,
+ HUGGINGFACE_TOKEN_MIGRATION,
+ LEGACY_HUGGINGFACE_TOKEN_ENV,
+ env_text_needs_migration,
+ explicit_env_file_huggingface_warning,
+ migrate_env_key_in_file,
+ migrate_env_key_in_text,
+ migrate_owned_env_files,
+)
+
+
+def test_migrate_env_key_in_text_renames_legacy_hf_token() -> None:
+ text = "# comment\nHF_TOKEN=old-token\nMODEL=nvidia_nim/model\n"
+
+ migrated, changed = migrate_env_key_in_text(text, HUGGINGFACE_TOKEN_MIGRATION)
+
+ assert changed is True
+ assert migrated == (
+ "# comment\nHUGGINGFACE_API_KEY=old-token\nMODEL=nvidia_nim/model\n"
+ )
+
+
+def test_migrate_env_key_in_text_preserves_existing_huggingface_api_key() -> None:
+ text = "HF_TOKEN=old-token\nHUGGINGFACE_API_KEY=new-token\n"
+
+ migrated, changed = migrate_env_key_in_text(text, HUGGINGFACE_TOKEN_MIGRATION)
+
+ assert changed is False
+ assert migrated == text
+
+
+def test_migrate_env_key_in_text_ignores_comments() -> None:
+ text = "# HF_TOKEN=old-token\n"
+
+ migrated, changed = migrate_env_key_in_text(text, HUGGINGFACE_TOKEN_MIGRATION)
+
+ assert changed is False
+ assert migrated == text
+ assert not env_text_needs_migration(text, HUGGINGFACE_TOKEN_MIGRATION)
+
+
+def test_migrate_env_key_in_file_rewrites_dotenv(tmp_path: Path) -> None:
+ env_file = tmp_path / ".env"
+ env_file.write_text("export HF_TOKEN = quoted-token\n", encoding="utf-8")
+
+ assert migrate_env_key_in_file(env_file, HUGGINGFACE_TOKEN_MIGRATION) is True
+
+ assert env_file.read_text(encoding="utf-8") == (
+ "export HUGGINGFACE_API_KEY = quoted-token\n"
+ )
+
+
+def test_migrate_owned_env_files_rewrites_repo_and_managed_env(
+ monkeypatch, tmp_path: Path
+) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ managed = tmp_path / ".fcc" / ".env"
+ managed.parent.mkdir()
+ (repo / ".env").write_text("HF_TOKEN=repo-token\n", encoding="utf-8")
+ managed.write_text("HF_TOKEN=managed-token\n", encoding="utf-8")
+ monkeypatch.chdir(repo)
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("USERPROFILE", str(tmp_path))
+
+ migrated = migrate_owned_env_files()
+
+ assert migrated == (repo / ".env", managed)
+ assert (repo / ".env").read_text(encoding="utf-8") == (
+ "HUGGINGFACE_API_KEY=repo-token\n"
+ )
+ assert managed.read_text(encoding="utf-8") == (
+ "HUGGINGFACE_API_KEY=managed-token\n"
+ )
+
+
+def test_explicit_env_file_huggingface_warning_does_not_rewrite(
+ tmp_path: Path,
+) -> None:
+ explicit = tmp_path / "custom.env"
+ explicit.write_text("HF_TOKEN=explicit-token\n", encoding="utf-8")
+
+ warning = explicit_env_file_huggingface_warning({"FCC_ENV_FILE": str(explicit)})
+
+ assert warning is not None
+ assert str(explicit) in warning
+ assert LEGACY_HUGGINGFACE_TOKEN_ENV in warning
+ assert HUGGINGFACE_API_KEY_ENV in warning
+ assert explicit.read_text(encoding="utf-8") == "HF_TOKEN=explicit-token\n"
diff --git a/tests/contracts/test_feature_manifest.py b/tests/contracts/test_feature_manifest.py
index f426c373..1377a620 100644
--- a/tests/contracts/test_feature_manifest.py
+++ b/tests/contracts/test_feature_manifest.py
@@ -10,6 +10,7 @@ from providers.deepseek import DeepSeekProvider
from providers.fireworks import FireworksProvider
from providers.gemini import GeminiProvider
from providers.groq import GroqProvider
+from providers.huggingface import HuggingFaceProvider
from providers.kimi import KimiProvider
from providers.llamacpp import LlamaCppProvider
from providers.lmstudio import LMStudioProvider
@@ -94,6 +95,7 @@ def test_provider_and_platform_registries_include_advertised_builtins() -> None:
"opencode": OpenCodeProvider,
"opencode_go": OpenCodeProvider,
"vercel": VercelProvider,
+ "huggingface": HuggingFaceProvider,
"zai": ZaiProvider,
"gemini": GeminiProvider,
"groq": GroqProvider,
diff --git a/tests/contracts/test_provider_catalog_order.py b/tests/contracts/test_provider_catalog_order.py
index 185ebe33..b5f81807 100644
--- a/tests/contracts/test_provider_catalog_order.py
+++ b/tests/contracts/test_provider_catalog_order.py
@@ -12,6 +12,7 @@ _EXPECTED_PROVIDER_ORDER: tuple[str, ...] = (
"opencode",
"opencode_go",
"vercel",
+ "huggingface",
"wafer",
"kimi",
"minimax",
@@ -27,7 +28,7 @@ _EXPECTED_PROVIDER_ORDER: tuple[str, ...] = (
def test_provider_catalog_key_order_matches_canonical_plan() -> None:
- """NIM first; OpenCode pair stays adjacent; Vercel follows gateway providers."""
+ """NIM first; OpenCode pair stays adjacent; gateways precede native remotes."""
assert tuple(PROVIDER_CATALOG.keys()) == _EXPECTED_PROVIDER_ORDER
assert SUPPORTED_PROVIDER_IDS == _EXPECTED_PROVIDER_ORDER
diff --git a/tests/contracts/test_smoke_config.py b/tests/contracts/test_smoke_config.py
index e569f983..be7a9a75 100644
--- a/tests/contracts/test_smoke_config.py
+++ b/tests/contracts/test_smoke_config.py
@@ -36,6 +36,7 @@ def _settings(**overrides):
"minimax_api_key": "",
"opencode_api_key": "",
"vercel_ai_gateway_api_key": "",
+ "huggingface_api_key": "",
"zai_api_key": "",
"gemini_api_key": "",
"groq_api_key": "",
@@ -209,6 +210,22 @@ def test_vercel_provider_configuration_uses_api_key(monkeypatch) -> None:
assert models[0].full_model == PROVIDER_SMOKE_DEFAULT_MODELS["vercel"]
+def test_huggingface_provider_configuration_uses_api_key(monkeypatch) -> None:
+ monkeypatch.delenv("FCC_SMOKE_MODEL_HUGGINGFACE", raising=False)
+ config = _smoke_config(
+ settings=_settings(
+ model="ollama/llama3.1",
+ ollama_base_url="",
+ huggingface_api_key="hf-key",
+ )
+ )
+
+ assert config.has_provider_configuration("huggingface")
+ models = config.provider_smoke_models()
+ assert models[0].provider == "huggingface"
+ assert models[0].full_model == PROVIDER_SMOKE_DEFAULT_MODELS["huggingface"]
+
+
def test_provider_smoke_model_override_accepts_model_name_without_prefix(
monkeypatch,
) -> None:
diff --git a/tests/messaging/test_messaging_factory.py b/tests/messaging/test_messaging_factory.py
index 816e0992..71f0f74d 100644
--- a/tests/messaging/test_messaging_factory.py
+++ b/tests/messaging/test_messaging_factory.py
@@ -44,7 +44,7 @@ class TestCreateMessagingComponents:
voice_note_enabled=False,
whisper_model="large-v3",
whisper_device="cuda",
- hf_token="",
+ huggingface_api_key="",
nvidia_nim_api_key="",
messaging_rate_limit=1,
messaging_rate_window=1.0,
@@ -97,7 +97,7 @@ class TestCreateMessagingComponents:
voice_note_enabled=False,
whisper_model="small",
whisper_device="nvidia_nim",
- hf_token="",
+ huggingface_api_key="",
nvidia_nim_api_key="",
messaging_rate_limit=1,
messaging_rate_window=1.0,
diff --git a/tests/messaging/test_platform_voice_flow.py b/tests/messaging/test_platform_voice_flow.py
index 334a210b..8abfab13 100644
--- a/tests/messaging/test_platform_voice_flow.py
+++ b/tests/messaging/test_platform_voice_flow.py
@@ -18,7 +18,7 @@ def _flow(*, enabled: bool = True) -> VoiceNoteFlow:
voice_note_enabled=enabled,
whisper_model="base",
whisper_device="cpu",
- hf_token="",
+ huggingface_api_key="",
nvidia_nim_api_key="",
log_raw_messaging_content=False,
log_api_error_tracebacks=False,
diff --git a/tests/messaging/test_voice_services.py b/tests/messaging/test_voice_services.py
index 55feb16e..54812f2c 100644
--- a/tests/messaging/test_voice_services.py
+++ b/tests/messaging/test_voice_services.py
@@ -29,9 +29,9 @@ async def test_pending_voice_registry_complete_removes_entries():
@pytest.mark.asyncio
async def test_voice_transcription_service_runs_backend():
- service = VoiceTranscriptionService()
+ service = VoiceTranscriptionService(huggingface_api_key="hf-provider-key")
- with patch("messaging.transcription.transcribe_audio", return_value="hello"):
+ with patch("messaging.transcription.transcribe_audio", return_value="hello") as run:
text = await service.transcribe(
Path("audio.ogg"),
"audio/ogg",
@@ -40,3 +40,4 @@ async def test_voice_transcription_service_runs_backend():
)
assert text == "hello"
+ assert run.call_args.kwargs["huggingface_api_key"] == "hf-provider-key"
diff --git a/tests/providers/test_huggingface.py b/tests/providers/test_huggingface.py
new file mode 100644
index 00000000..c19122d4
--- /dev/null
+++ b/tests/providers/test_huggingface.py
@@ -0,0 +1,188 @@
+"""Tests for Hugging Face Inference Providers."""
+
+from contextlib import asynccontextmanager
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from providers.base import ProviderConfig
+from providers.huggingface import HUGGINGFACE_DEFAULT_BASE, HuggingFaceProvider
+
+
+class MockMessage:
+ def __init__(self, role, content):
+ self.role = role
+ self.content = content
+
+
+class MockRequest:
+ def __init__(self, **kwargs):
+ self.model = "openai/gpt-oss-120b:fastest"
+ self.messages = [MockMessage("user", "Hello")]
+ self.max_tokens = 100
+ self.temperature = 0.5
+ self.top_p = 0.9
+ self.system = "System prompt"
+ self.stop_sequences = None
+ self.tools = []
+ self.thinking = MagicMock()
+ self.thinking.enabled = True
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+
+def huggingface_config():
+ return ProviderConfig(
+ api_key="test_hf_key",
+ base_url=HUGGINGFACE_DEFAULT_BASE,
+ rate_limit=10,
+ rate_window=60,
+ enable_thinking=True,
+ )
+
+
[email protected](autouse=True)
+def mock_rate_limiter():
+ @asynccontextmanager
+ async def _slot():
+ yield
+
+ with patch("providers.transports.openai_chat.transport.GlobalRateLimiter") as mock:
+ instance = mock.get_scoped_instance.return_value
+
+ async def _passthrough(fn, *args, **kwargs):
+ return await fn(*args, **kwargs)
+
+ instance.execute_with_retry = AsyncMock(side_effect=_passthrough)
+ instance.concurrency_slot.side_effect = _slot
+ yield instance
+
+
+def huggingface_provider(huggingface_config):
+ return HuggingFaceProvider(huggingface_config)
+
+
+def test_default_base_url_constant():
+ assert HUGGINGFACE_DEFAULT_BASE == "https://router.huggingface.co/v1"
+
+
+def test_init_uses_default_base_url_and_api_key(huggingface_config):
+ with patch("providers.transports.openai_chat.transport.AsyncOpenAI") as mock_openai:
+ provider = HuggingFaceProvider(huggingface_config)
+
+ assert provider._api_key == "test_hf_key"
+ assert provider._base_url == HUGGINGFACE_DEFAULT_BASE
+ mock_openai.assert_called_once()
+
+
+def test_init_strips_trailing_slash(huggingface_config):
+ config = huggingface_config.model_copy(
+ update={"base_url": f"{HUGGINGFACE_DEFAULT_BASE}/"}
+ )
+
+ with patch("providers.transports.openai_chat.transport.AsyncOpenAI"):
+ provider = HuggingFaceProvider(config)
+
+ assert provider._base_url == HUGGINGFACE_DEFAULT_BASE
+
+
+def test_build_request_body_keeps_max_tokens(huggingface_provider):
+ with patch(
+ "providers.transports.openai_chat.request_policy.build_base_request_body"
+ ) as mock_convert:
+ mock_convert.return_value = {
+ "model": "openai/gpt-oss-120b:fastest",
+ "messages": [{"role": "user", "name": "alice", "content": "hi"}],
+ "max_tokens": 42,
+ }
+
+ body = huggingface_provider._build_request_body(MockRequest())
+
+ assert body["messages"][0].get("name") == "alice"
+ assert body["max_tokens"] == 42
+ assert "max_completion_tokens" not in body
+
+
+def test_build_request_body_preserves_caller_extra_body(huggingface_provider):
+ req = MockRequest(extra_body={"provider": "auto", "bill_to": "my-org"})
+
+ body = huggingface_provider._build_request_body(req)
+
+ assert body["extra_body"] == {"provider": "auto", "bill_to": "my-org"}
+
+
+async def test_stream_response_text(huggingface_provider):
+ mock_chunk = MagicMock()
+ mock_chunk.choices = [
+ MagicMock(
+ delta=MagicMock(
+ content="Hello from Hugging Face",
+ reasoning_content=None,
+ tool_calls=None,
+ ),
+ finish_reason="stop",
+ )
+ ]
+ mock_chunk.usage = MagicMock(completion_tokens=5, prompt_tokens=10)
+
+ async def mock_stream():
+ yield mock_chunk
+
+ with patch.object(
+ huggingface_provider._client.chat.completions, "create", new_callable=AsyncMock
+ ) as mock_create:
+ mock_create.return_value = mock_stream()
+
+ events = [
+ event async for event in huggingface_provider.stream_response(MockRequest())
+ ]
+
+ assert any(
+ '"text_delta"' in event and "Hello from Hugging Face" in event
+ for event in events
+ )
+
+
+async def test_stream_response_reasoning_content(huggingface_provider):
+ mock_chunk = MagicMock()
+ mock_chunk.choices = [
+ MagicMock(
+ delta=MagicMock(
+ content=None,
+ reasoning_content="Thinking via router",
+ tool_calls=None,
+ ),
+ finish_reason="stop",
+ )
+ ]
+ mock_chunk.usage = MagicMock(completion_tokens=2, prompt_tokens=10)
+
+ async def mock_stream():
+ yield mock_chunk
+
+ with patch.object(
+ huggingface_provider._client.chat.completions, "create", new_callable=AsyncMock
+ ) as mock_create:
+ mock_create.return_value = mock_stream()
+
+ events = [
+ event async for event in huggingface_provider.stream_response(MockRequest())
+ ]
+
+ assert any(
+ '"thinking_delta"' in event and "Thinking via router" in event
+ for event in events
+ )
+
+
+async def test_cleanup(huggingface_provider):
+ huggingface_provider._client = AsyncMock()
+
+ await huggingface_provider.cleanup()
+
+ huggingface_provider._client.close.assert_called_once()
diff --git a/tests/providers/test_provider_runtime.py b/tests/providers/test_provider_runtime.py
index 66691b34..f8820e01 100644
--- a/tests/providers/test_provider_runtime.py
+++ b/tests/providers/test_provider_runtime.py
@@ -19,6 +19,7 @@ from providers.exceptions import UnknownProviderTypeError
from providers.fireworks import FireworksProvider
from providers.gemini import GeminiProvider
from providers.groq import GroqProvider
+from providers.huggingface import HUGGINGFACE_DEFAULT_BASE, HuggingFaceProvider
from providers.kimi import KimiProvider
from providers.llamacpp import LlamaCppProvider
from providers.lmstudio import LMStudioProvider
@@ -49,6 +50,7 @@ def _make_settings(**overrides):
mock.minimax_api_key = "test_minimax_key"
mock.opencode_api_key = "test_opencode_key"
mock.vercel_ai_gateway_api_key = "test_vercel_key"
+ mock.huggingface_api_key = "test_huggingface_key"
mock.zai_api_key = "test_zai_key"
mock.lm_studio_base_url = "http://localhost:1234/v1"
mock.llamacpp_base_url = "http://localhost:8080/v1"
@@ -66,6 +68,7 @@ def _make_settings(**overrides):
mock.opencode_proxy = ""
mock.opencode_go_proxy = ""
mock.vercel_ai_gateway_proxy = ""
+ mock.huggingface_proxy = ""
mock.zai_proxy = ""
mock.fireworks_proxy = ""
mock.fireworks_api_key = "test_fireworks_key"
@@ -213,6 +216,16 @@ def test_vercel_descriptor_uses_openai_chat_gateway() -> None:
assert "thinking" in descriptor.capabilities
+def test_huggingface_descriptor_uses_openai_chat_router() -> None:
+ descriptor = PROVIDER_CATALOG["huggingface"]
+
+ assert descriptor.transport_type == "openai_chat"
+ assert descriptor.default_base_url == HUGGINGFACE_DEFAULT_BASE
+ assert descriptor.credential_env == "HUGGINGFACE_API_KEY"
+ assert descriptor.proxy_attr == "huggingface_proxy"
+ assert "thinking" in descriptor.capabilities
+
+
def test_build_provider_config_vercel_uses_gateway_key_and_proxy() -> None:
descriptor = PROVIDER_CATALOG["vercel"]
settings = _make_settings(
@@ -226,6 +239,19 @@ def test_build_provider_config_vercel_uses_gateway_key_and_proxy() -> None:
assert config.proxy == "http://proxy.test:8080"
+def test_build_provider_config_huggingface_uses_api_key_and_proxy() -> None:
+ descriptor = PROVIDER_CATALOG["huggingface"]
+ settings = _make_settings(
+ huggingface_api_key="hf-token",
+ huggingface_proxy="http://proxy.test:8080",
+ )
+
+ config = build_provider_config(descriptor, settings)
+
+ assert config.api_key == "hf-token"
+ assert config.proxy == "http://proxy.test:8080"
+
+
def test_create_provider_uses_native_openrouter_by_default():
with patch("httpx.AsyncClient"):
provider = create_provider("open_router", _make_settings())
@@ -242,6 +268,7 @@ def test_create_provider_instantiates_each_builtin():
cloudflare_api_token="test_cloudflare_token",
cloudflare_account_id="test_cloudflare_account",
vercel_ai_gateway_api_key="test_vercel_key",
+ huggingface_api_key="test_huggingface_key",
kimi_api_key="test_kimi_key",
)
cases = {
@@ -260,6 +287,7 @@ def test_create_provider_instantiates_each_builtin():
"opencode": OpenCodeProvider,
"opencode_go": OpenCodeProvider,
"vercel": VercelProvider,
+ "huggingface": HuggingFaceProvider,
"zai": ZaiProvider,
"gemini": GeminiProvider,
"groq": GroqProvider,
diff --git a/uv.lock b/uv.lock
index b5614e93..07cde5eb 100644
--- a/uv.lock
+++ b/uv.lock
@@ -561,7 +561,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "2.6.0"
+version = "3.0.0"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },