skip to content

How do you point existing OpenAI SDK chat code at Hugging Face Inference Providers, and how do you control which provider serves it?

level: middleimportance: must knowfreq 11%

answer

  1. swap two client settings
  2. router.huggingface.co/v1
  3. a Hugging Face token as the API key
  4. Hub model id, never the provider's
  5. suffix after a colon picks the policy

basics

~20 s

Set the OpenAI client's base URL to https://router.huggingface.co/v1 and its API key to a Hugging Face token, and pass the Hub model id. A suffix picks the provider: none means :fastest, or use :cheapest, :preferred or a provider name.

solid answer

~40 s

Keep the OpenAI SDK and change two settings: `base_url="https://router.huggingface.co/v1"` and `api_key` set to a Hugging Face token with the "Make calls to Inference Providers" permission. The `model` field takes the Hub model id, such as `openai/gpt-oss-120b`, never the provider's own id. Provider choice rides on a suffix: with none, the router picks the fastest available provider (`:fastest`, highest throughput in tokens per second); `:cheapest` picks the lowest price per output token; `:preferred` follows the order saved in your Inference Providers settings; a provider name such as `:groq` pins one. `GET /v1/models` lists served chat models with per-provider pricing, context length, latency and throughput. The compatible endpoint is chat-only; images, embeddings and speech go through `InferenceClient`.

code

python · 14 lines
python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://router.huggingface.co/v1",
    api_key=os.environ["HF_TOKEN"],  # fine-grained: Make calls to Inference Providers
)

completion = client.chat.completions.create(
    model="openai/gpt-oss-120b:cheapest",  # Hub id + policy; no suffix means :fastest
    messages=[{"role": "user", "content": "Classify: refund not received"}],
    extra_headers={"X-HF-Bill-To": "my-org"},  # optional: a Team or Enterprise org pays
)
print(completion.choices[0].message.content)

go deeper

for a junior

Recall the two settings that change, the base URL and the key, and that the model field takes the Hub model id.

for a middle

Explain the suffix grammar exactly: no suffix equals :fastest by throughput, :cheapest by price per output token, :preferred by your saved order, and a provider name to pin.

for a senior

Discuss what the default costs you in production: the serving provider can change between calls, so pin a provider where reproducibility matters and know that failover applies only to automatic selection.

for a principal

Weigh the router as a dependency: one token and one bill across partners against the variance of shared providers, and decide which workloads stay on policy suffixes and which move to dedicated capacity.

## The two-line migration Inference Providers exposes an **OpenAI-compatible chat endpoint** on Hugging Face's router, so code already written against an OpenAI client keeps its request and response handling. Only the client construction changes: - `base_url` (Python) or `baseURL` (JavaScript) becomes `https://router.huggingface.co/v1`. - `api_key` becomes a **Hugging Face user access token**, usually read from `HF_TOKEN`. The Inference Providers docs ask for a fine-grained token with the "Make calls to Inference Providers" permission. - `model` becomes a **Hub model id**, for example `openai/gpt-oss-120b`. The router maps it to each provider's internal id for you; passing a provider's own model name is a classic first mistake. The message list, streaming and tool calls are whatever the Chat Completions contract defines; the router does not change that shape. ## The suffix grammar: who serves the request The router reads an optional suffix after a colon on the model id. It is the only routing control you put in the request itself, so it matters: | Model string | Selection | |---|---| | `openai/gpt-oss-120b` | default, same as `:fastest` | | `openai/gpt-oss-120b:fastest` | the provider with the highest throughput in tokens per second | | `openai/gpt-oss-120b:cheapest` | the provider with the lowest price per output token | | `openai/gpt-oss-120b:preferred` | the first available provider in your saved order at hf.co/settings/inference-providers | | `openai/gpt-oss-120b:groq` | that one provider, by name | Two consequences follow from the defaults: 1. **The provider can change between calls.** A policy suffix ranks live providers, so latency, price and even small output differences can shift when the ranking does. Pin a provider name when reproducibility matters more than speed or price. 2. **Failover belongs to automatic selection.** The docs describe requests under automatic selection being sent to an alternative provider when the primary is flagged unavailable; a pinned provider name is the provider you get. ## Discovering what you can call - `GET https://router.huggingface.co/v1/models` lists the chat models served through Providers, with per-provider pricing, context length, latency and throughput where available. - On the Hub, `hf models ls --warm` lists every model served by at least one provider, and `hf models ls --inference-provider <name>` narrows the list to one provider. ## The same call without the OpenAI SDK The router is plain HTTP, so nothing ties it to one SDK: - **Raw HTTP.** `POST https://router.huggingface.co/v1/chat/completions` with the header `Authorization: Bearer $HF_TOKEN` and a JSON body whose `model` carries the same Hub id and optional suffix. - **`huggingface_hub`.** `InferenceClient` exposes an OpenAI-style alias, `client.chat.completions.create(...)`, next to its native `chat_completion(...)`. With no `provider` argument, chat requests go to the same server-side router, so the default policy is again `:fastest`. - **`@huggingface/inference`.** `client.chatCompletion({ model, messages })` in JavaScript, with an optional `provider` field such as `"novita"` to choose one explicitly instead of writing a suffix. The Hugging Face clients add one thing the OpenAI SDK cannot: an explicit `provider=` argument that the client turns into the right request format for that partner, which matters once you leave chat for other tasks. ## Where the compatible endpoint stops The OpenAI-compatible route is **chat completion only**. Text-to-image, embeddings (`feature_extraction`), speech recognition and the other tasks go through the Hugging Face clients instead: `InferenceClient` in `huggingface_hub` (for example `client.text_to_image(...)`) or `InferenceClient` from `@huggingface/inference` in JavaScript (`client.textToImage(...)`). Those clients take the same Hub model id and either a `provider=` argument or the default automatic selection. ## Checks before you ship it 1. **Token scope.** A fine-grained token limited to Inference Providers calls limits the blast radius if it leaks, compared with a broad write token. 2. **The model is served.** A model with no provider simply fails on the router; check `/v1/models` or the `warm` status first. 3. **Policy versus pin.** Decide whether the job wants the fastest, the cheapest, your saved preference order, or one named provider every time. 4. **Who pays.** Requests bill the token owner by default. A Team or Enterprise organization pays when the request carries `X-HF-Bill-To: <org>`, which the OpenAI Python client sends through `extra_headers` and the JavaScript client through per-request `headers`. The same router also sits behind the Hugging Face clients, which is why a team can start with the OpenAI SDK for chat and add `InferenceClient` later for other tasks without changing tokens or billing.

  • Your job sends `openai/gpt-oss-120b` with no suffix and latency varies day to day. Why, and what do you change?
    With no suffix the router applies `:fastest`, ranking live providers by throughput, so the serving provider can change as that ranking moves. Append a provider name such as `:groq` to pin one, accepting that you lose automatic selection's switch to another provider when that one is flagged unavailable.
  • Can the same `router.huggingface.co/v1` client generate embeddings or images?
    No. The OpenAI-compatible route covers chat completion only. Use `InferenceClient` from `huggingface_hub` (`feature_extraction`, `text_to_image`) or from `@huggingface/inference` (`featureExtraction`, `textToImage`) with the same Hub model id and token.

  • You must create an account with each partner provider before calling the router.
  • The model field takes the provider's own model id, not the Hub id.
  • Without a suffix the router picks the cheapest provider.
  • The :preferred suffix means Hugging Face's own hf-inference provider.
  • The OpenAI-compatible router also serves image generation and embeddings.