Thuta Learning
API Tutorial
AdvancedWeb DevelopmentIntermediate

Hugging Face Inference API

API TutorialLesson 2335 min

What you'll walk away with

  • Send POST /v1/chat/completions to router.huggingface.co with a Bearer token and a messages body
  • Choose a provider with model suffixes such as :cheapest, :fastest or a provider name
  • Read choices[0].message.content, finish_reason and usage from the reply
  • Build an allowlist, tolerant error parsing and a fallback list around a router that fronts many providers

Explain it simply

Explain it simply

Hugging Face Inference Providers works like a taxi dispatcher. You send one request to Hugging Face, and Hugging Face forwards it to one of several companies that actually run the model, such as Groq, Together or Cerebras. You hold a single Hugging Face token instead of an account at every company.

The convenient part is that, for chat, the dispatcher speaks the same request and reply format as the OpenAI chat completions API. The tricky part is that behind the dispatcher the companies differ, so a model may be served by nobody at the moment, and errors can look different depending on who answered.

Problem → Why → Solution

The problem: any model, any token, one shape

An older tutorial says: pick any model on the Hub and call it. So a learner picks a popular repository, pastes in a broad personal token that can also write to their account, and reads the answer from data[0].generated_text, a shape from an older text-generation API.

Three things can go wrong. A model repository does not guarantee that any provider serves it right now. The chat router answers with choices, not a generated_text list, so the read throws. And a token with more rights than the job needs, shipped to a browser, lets anyone act as the account owner.

old-tutorial.js
const res = await fetch("https://router.huggingface.co/v1/chat/completions", {
  method: "POST",
  // a broad token, bundled into code that runs in the browser
  headers: { Authorization: "Bearer " + HF_BROAD_TOKEN },
  body: JSON.stringify({
    model: "any-model-from-the-hub", // is anyone serving it right now?
    messages: [{ role: "user", content: "Explain REST" }],
  }),
});
const data = await res.json();
console.log(data[0].generated_text); // older shape: the router returns choices

Why a convenient router still needs guard rails

A router hides the differences between providers most of the time, not all of the time. Hugging Face's own documentation notes that requests and response formats can vary between providers behind the proxy. Guard rails such as a model allowlist, a minimal token, tolerant error parsing and a fallback list make those differences a handled case instead of an outage.

Core concept: a router, a suffix and a token

The details below come from the Hugging Face Inference Providers documentation. Model ids and provider lists change, so the lesson uses placeholders and tells you where to look.

1. One router, many providers

Inference Providers acts as a proxy layer between your application and many providers. You use one Hugging Face token for all of them. With automatic provider selection, a request can be rerouted to another provider when the first one is flagged as unavailable. Because it is a proxy, the exact request and response format may vary between providers, which the official client libraries smooth over for you.

2. The OpenAI-compatible endpoint

For chat you can POST to https://router.huggingface.co/v1/chat/completions, which the docs describe as a drop-in replacement for the OpenAI chat completions API. It is for chat tasks only, and GET /v1/models lists the models available across providers, with pricing, context length and similar details when they are known. Other tasks such as text-to-image, embeddings or speech go through the inference client libraries.

3. The token

Authenticate with Authorization: Bearer $HF_TOKEN. The docs ask for a fine-grained token that has the permission to make calls to Inference Providers, which keeps the blast radius small if it leaks. Like every other key in this course, it belongs on your server.

4. Choosing a provider with a suffix

By default the router picks the fastest available provider, the same as appending :fastest. Append :cheapest for the lowest price per output token, or :preferred to follow the order you set in your Inference Provider settings. You can also pin one provider by appending its name, for example :groq. The suffix is part of the model string, so no extra field is needed.

5. Reply and billing

A non-streaming reply has choices, where choices[0].message.content holds the text and finish_reason says why generation stopped, plus usage with prompt_tokens, completion_tokens and total_tokens. Routed requests are billed to your Hugging Face account at the provider's rate with no markup. Free accounts must buy credits, while PRO, Team and Enterprise plans include monthly credits.

DoorUse it forRemember
OpenAI-compatible endpointChat onlySwap the base URL
InferenceClient (JS, Python)Every task typeprovider: auto by default
Direct HTTPCustom controlFormats can vary per provider
Mental model: a dispatcher with a short list
  1. One HF token, many providers
  2. Suffix picks the route
  3. choices[0] holds the answer
  4. Allowlist and fallback guard you

The router decides who answers, but you decide which models are acceptable, what happens when one is unavailable and how errors are read.

General pattern

bash
curl https://router.huggingface.co/v1/chat/completions \
  -H "Authorization: Bearer $HF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "<org/model-name>[:<policy-or-provider>]",
    "messages": [{"role": "user", "content": "<prompt>"}],
    "stream": false
  }'

The text inside angle brackets is a placeholder: take a real model id from the Hub's list of models served by a provider, and leave the suffix out to get the default. Illustrative only; use your own token from an environment variable.

An allowlist, a route suffix and defensive errors

The mock router answers in the chat completions shape and echoes the route it was asked for. It also fails in three different ways: an object error body, a plain-string error body and a plain-text 502. The client checks the allowlist before sending anything, builds the model string with an optional suffix, reads choices and usage, and falls back to a second model when the first one is unavailable.

router-client.mjs
import http from "node:http";

const TOKEN = "hf_demo_token";
const ALLOWED = ["org/model-a", "org/model-b"]; // your own allowlist, not the Hub's

// Mock router: OpenAI-style chat completions, with error bodies in different shapes.
const server = http.createServer((req, res) => {
  let raw = "";
  req.on("data", (chunk) => (raw += chunk));
  req.on("end", () => {
    const send = (status, body, type = "application/json") => {
      res.writeHead(status, { "content-type": type });
      res.end(typeof body === "string" ? body : JSON.stringify(body));
    };
    if (req.headers.authorization !== "Bearer " + TOKEN) {
      return send(401, { error: "Invalid credentials in Authorization header" });
    }
    const body = JSON.parse(raw);
    const [id, route] = body.model.split(":");
    const prompt = body.messages.at(-1).content;
    if (prompt === "gateway") return send(502, "Bad gateway", "text/plain");
    if (prompt === "unavailable" && id === "org/model-a") {
      return send(404, { error: { message: "No provider serves this model right now" } });
    }
    const via = route ? " via " + route : "";
    send(200, {
      id: "chatcmpl-demo",
      object: "chat.completion",
      model: id,
      choices: [
        {
          index: 0,
          message: { role: "assistant", content: "Answer from " + id + via },
          finish_reason: body.max_tokens < 10 ? "length" : "stop",
        },
      ],
      usage: { prompt_tokens: 12, completion_tokens: 14, total_tokens: 26 },
    });
  });
});

// The suffix after ":" picks a provider policy (fastest, cheapest, ...) or a provider.
function modelFor(id, route) {
  if (!ALLOWED.includes(id)) throw new Error("model is not on the allowlist: " + id);
  return route ? id + ":" + route : id;
}

// Error bodies may be an object, a plain string or not JSON at all: accept all three.
async function readError(res) {
  const raw = await res.text();
  try {
    const data = JSON.parse(raw);
    if (typeof data.error === "string") return data.error;
    return data.error?.message ?? JSON.stringify(data);
  } catch {
    return raw.slice(0, 80);
  }
}

async function chat(base, token, model, prompt, maxTokens = 64) {
  const res = await fetch(base + "/v1/chat/completions", {
    method: "POST",
    headers: {
      authorization: "Bearer " + token,
      "content-type": "application/json",
    },
    body: JSON.stringify({
      model,
      messages: [{ role: "user", content: prompt }],
      max_tokens: maxTokens,
      stream: false,
    }),
  });
  if (!res.ok) {
    const detail = await readError(res);
    throw Object.assign(new Error(detail), { status: res.status });
  }
  const data = await res.json();
  const choice = data.choices[0];
  const { content: text } = choice.message;
  return { text, finish: choice.finish_reason, usage: data.usage };
}

async function withFallback(base, ids, prompt) {
  for (const id of ids) {
    try {
      const reply = await chat(base, TOKEN, modelFor(id), prompt);
      return { id, ...reply };
    } catch (err) {
      console.log(id + " failed (" + err.status + "): " + err.message);
    }
  }
  throw new Error("no model in the list answered");
}

await new Promise((resolve) => server.listen(0, resolve));
const base = "http://127.0.0.1:" + server.address().port;

const ok = await chat(base, TOKEN, modelFor("org/model-a", "cheapest"), "Explain REST");
const { prompt_tokens, completion_tokens, total_tokens } = ok.usage;
console.log("text:", ok.text);
console.log("finish:", ok.finish, "| tokens:", prompt_tokens, "+", completion_tokens);
console.log("total tokens:", total_tokens);

const cut = await chat(base, TOKEN, modelFor("org/model-b"), "Explain REST", 5);
console.log("short limit -> finish_reason:", cut.finish);

try {
  modelFor("org/not-approved");
} catch (err) {
  console.log("blocked before sending:", err.message);
}
const failing = [
  ["bad token", "hf_wrong", "hi"],
  ["proxy", TOKEN, "gateway"],
];
for (const [label, token, prompt] of failing) {
  try {
    await chat(base, token, modelFor("org/model-a"), prompt);
  } catch (err) {
    console.log(label + " ->", err.status, err.message);
  }
}
const fallback = await withFallback(base, ["org/model-a", "org/model-b"], "unavailable");
console.log("fallback answered:", fallback.text);
server.close();

Code breakdown

  1. Allowlist before sendingif (!ALLOWED.includes(id)) throw new Error("model is not on the allowlist: " + id);

    A model that is not on your list never leaves your server, which protects both cost and data. The allowlist is yours; the Hub does not enforce it for you.

  2. Route suffixreturn route ? id + ":" + route : id;

    The policy or provider is appended to the model id after a colon. The first call asks for cheapest, and the reply text shows that the router saw org/model-a:cheapest.

  3. Three error shapesif (typeof data.error === "string") return data.error;

    readError() accepts a string error, an object with a message and text that is not JSON at all. The bad-token call and the proxy failure both end up as readable messages.

  4. Why generation stoppedfinish: choice.finish_reason

    With max_tokens set to 5 the reply reports length instead of stop, the signal that the text was cut off. Always check it before trusting a long answer.

  5. Token accountingconst { prompt_tokens, completion_tokens, total_tokens } = ok.usage;

    usage in the OpenAI-compatible shape is split into prompt and completion tokens, which is what you log to track cost per feature.

  6. Fallback listconst reply = await chat(base, TOKEN, modelFor(id), prompt);

    withFallback() tries each approved model in turn. The mock answers 404 for org/model-a when the prompt is unavailable, so org/model-b answers instead.

You should see
text: Answer from org/model-a via cheapest
finish: stop | tokens: 12 + 14
total tokens: 26
short limit -> finish_reason: length
blocked before sending: model is not on the allowlist: org/not-approved
bad token -> 401 Invalid credentials in Authorization header
proxy -> 502 Bad gateway
org/model-a failed (404): No provider serves this model right now
fallback answered: Answer from org/model-b

The same call in curl and with the JavaScript client

Both snippets are illustrative: check the current docs, put your own token in HF_TOKEN, and set HF_MODEL to an id from the Hub's list of models served by a provider. The curl call uses the :cheapest suffix. The client library snippet handles provider differences for you and is the better choice when you need tasks beyond chat.

bash
# Illustrative - check the current docs, and use your own token in HF_TOKEN.
# HF_MODEL is an id from the Hub's list of models served by an inference provider.
curl https://router.huggingface.co/v1/chat/completions \
  -H "Authorization: Bearer $HF_TOKEN" \
  -H "Content-Type: application/json" \
  -d "{
    \"model\": \"$HF_MODEL:cheapest\",
    \"messages\": [{\"role\": \"user\", \"content\": \"Explain REST in two sentences\"}],
    \"max_tokens\": 200
  }" | jq -r '.choices[0].message.content'
client.js
// Illustrative - check the current docs; needs your own token in HF_TOKEN.
import { InferenceClient } from "@huggingface/inference";

const client = new InferenceClient(process.env.HF_TOKEN);
const reply = await client.chatCompletion({
  model: process.env.HF_MODEL,
  provider: "auto", // or the name of one provider
  messages: [{ role: "user", content: "Explain REST in two sentences" }],
});
console.log(reply.choices[0].message.content);

Which models can you actually call

A repository on the Hub is not the same as a hosted endpoint. Before you build on a model, check that at least one provider serves it, for example with the Hub's inference-provider filter, the hf models ls --warm command or GET /v1/models on the router. Then read the model card for its licence, intended use and known limitations, because a hosted model can carry a licence that limits commercial use.

Billing options worth knowing

  • Routed requests are billed to your Hugging Face account at the provider's rate with no markup, and monthly credits apply to them where your plan includes credits.
  • A custom provider key makes the provider bill you directly, and then the included credits do not apply.
  • Team and Enterprise organizations can bill requests to the organization by sending an X-HF-Bill-To header.
  • Free accounts have no monthly credits and must purchase credits to use Inference Providers.

In real projects

How to apply it in a real project

Suppose you tag support tickets with an open model. Wrap the router in a server-side adapter whose configuration lists the approved model ids, so a typo or an unlicensed model is rejected before any request is sent. Use the default or :fastest route for interactive features and :cheapest for the overnight batch job, and pin one named provider in tests so results are reproducible.

Give the adapter a timeout and a fallback list, and log the model, the finish_reason and the usage numbers on every call. Test it with a mock that plays automatic routing, an unavailable model, a 429, error bodies in different shapes and a reply cut off by length, so the router's variety never surprises production.

Common mistakes

Common mistakes

Four mistakes show up again and again with the router.

Calling a Hub model that no provider serves

Being on the Hub does not mean being hosted. Check that a provider serves the model before you design around it, and keep a fallback in case it stops being served.

Using one broad personal token in the app

A token that can also write to your account is far more dangerous than one limited to calling Inference Providers. Create a fine-grained token for this one job, keep it on the server and rotate it if it ever appears in a log.

Reading data[0].generated_text from the chat endpoint

That shape belongs to older text-generation examples. The chat completions endpoint returns choices, so the text lives at choices[0].message.content.

Parsing every error body as one fixed shape

A proxy in front of many providers can surface errors as an object, a string or plain text. Code that does data.error.message on all of them throws a second error that hides the first.

Best practices

Habits worth keeping

  • Treat the model id and the route suffix as configuration, and change them through a reviewed pull request.
  • Prefer the official client libraries when you need image, embedding or speech tasks, since provider formats differ there.
  • Read the model card and licence before a model reaches users, and write down your fallback policy.

Mini challenge

Build an allowlist and route resolver

Write resolveModel(id, route) so that only approved model ids can be sent to the router. With no route it returns the id, and with a route it returns id:route. A route must be a policy name (fastest, cheapest, preferred) or a provider name made of lowercase letters, digits and dashes. Prove it with a mock router on port 0 that replies with the model string it received.

  • Throw "not allowed: <id>" for an id that is not on the allowlist
  • Accept a policy name or a provider-style name as the route, and reject anything else
  • Send only the resolved string to the mock router
  • Print sent: or rejected: for each of five test cases
resolver.mjs
import http from "node:http";

// TODO 1: keep an allowlist of two model ids you approve (a Set works well)
// TODO 2: keep the routing policies: fastest, cheapest and preferred

function resolveModel(id, route = "") {
  // TODO 3: throw "not allowed: <id>" when the id is not on the allowlist
  // TODO 4: with no route return the id; with a route return "<id>:<route>"
  // TODO 5: a route must be a policy name or a provider name made of lowercase
  //   letters, digits and dashes; otherwise throw "bad route: <route>"
  return id;
}

// TODO 6: start a mock router on port 0 that answers every request with
//   { choices: [{ message: { content: "router saw <the model string it received>" } }] }

// TODO 7: try five cases (two plain ids, one policy, one provider, one bad route,
//   one id that is not allowed). For each, print "sent: <router reply>" or
//   "rejected: <error message>". Close the server at the end.

Expected: Three sent: lines showing org/model-a, org/model-a:cheapest and org/model-b:groq, then "rejected: bad route: x y" and "rejected: not allowed: org/other".

Show hint

A Set makes the allowlist lookup short, and the regular expression /^[a-z0-9-]+$/ describes a provider-style name. Check the policy set first, then the pattern.

Show solution
resolver.mjs
import http from "node:http";

const ALLOWED = new Set(["org/model-a", "org/model-b"]);
const POLICIES = new Set(["fastest", "cheapest", "preferred"]);

// A route after ":" is a policy name or a provider name (lowercase, digits, dashes).
function resolveModel(id, route = "") {
  if (!ALLOWED.has(id)) throw new Error("not allowed: " + id);
  if (route === "") return id;
  const looksLikeProvider = /^[a-z0-9-]+$/.test(route);
  if (!POLICIES.has(route) && !looksLikeProvider) throw new Error("bad route: " + route);
  return id + ":" + route;
}

// Mock router: answers with the exact model string it received.
const server = http.createServer((req, res) => {
  let raw = "";
  req.on("data", (chunk) => (raw += chunk));
  req.on("end", () => {
    const { model } = JSON.parse(raw);
    res.writeHead(200, { "content-type": "application/json" });
    const message = { content: "router saw " + model };
    res.end(JSON.stringify({ choices: [{ message }] }));
  });
});
await new Promise((resolve) => server.listen(0, resolve));
const url = "http://127.0.0.1:" + server.address().port + "/v1/chat/completions";

const cases = [
  ["org/model-a", ""],
  ["org/model-a", "cheapest"],
  ["org/model-b", "groq"],
  ["org/model-b", "x y"],
  ["org/other", ""],
];
for (const [id, route] of cases) {
  try {
    const model = resolveModel(id, route);
    const res = await fetch(url, { method: "POST", body: JSON.stringify({ model }) });
    console.log("sent:", (await res.json()).choices[0].message.content);
  } catch (err) {
    console.log("rejected:", err.message);
  }
}
server.close();

Quick quiz 1 / 3

Which model string asks the router for the cheapest provider of org/model-a?

Quick quiz 2 / 3

Where is the generated text in a successful reply from the router's chat completions endpoint?

Quick quiz 3 / 3

Why should the client accept more than one shape of error body?

What to remember

  • Chat goes to POST https://router.huggingface.co/v1/chat/completions with a Bearer token; the text is in choices[0].message.content.
  • Append :fastest, :cheapest, :preferred or a provider name to the model id to choose the route.
  • Use a fine-grained token on your server, an allowlist of models and a fallback list, because a Hub model may have no provider.
  • Read errors tolerantly and check finish_reason, since the router fronts providers whose formats can differ.

Hugging Face — Inference Providers — Hugging Face

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Hugging Face Inference API | Thuta Learning