← Code Recipes
Hosting, Gateways & Local

Hugging Face Free code examples in Python and JavaScript

The model registry, plus Inference Endpoints and Transformers.

C# Python Java JavaScript

WHAT THIS PAGE COVERS

Downloading weights once and serving them from your own machine.

Model meta-llama/Llama-3.1-8B-Instruct
Package huggingface_hub
Checked

Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.

Install

huggingface_hub covers the registry and inference. transformers is only needed once you are running weights locally.

pip install huggingface_hub

export HF_TOKEN="hf_your-token"   # macOS / Linux
setx HF_TOKEN "hf_your-token"     # Windows, then open a new shell

# Or log in once and the client finds the token on its own:
hf auth login
One client, many providers

THE MODEL ID IS THE HUB ID, always — not the provider's name for the same weights. provider='auto' picks the first available in your configured order.

import os
from huggingface_hub import InferenceClient

client = InferenceClient(
    provider="auto",                      # or "together", "groq", ...
    api_key=os.environ["HF_TOKEN"],
)

response = client.chat.completions.create(
    model="meta-llama/Llama-3.1-8B-Instruct",
    messages=[{"role": "user", "content": "Explain a database index."}],
    max_tokens=200,
)

print(response.choices[0].message.content)
Downloading the weights once

hf download fetches into the shared cache, so the second consumer on the box pays nothing. PIN THE REVISION in anything reproducible — `main` moves, and a model that changed underneath you is a very confusing bug.

# Just the files you need, not the whole repository.
hf download meta-llama/Llama-3.1-8B-Instruct \
  --include "*.safetensors" "*.json" "tokenizer*" \
  --revision refs/pr/1

# Where it went, and how much of the disk it is using:
hf cache scan

# HF_HOME relocates the cache — worth setting on a box where /home
# is small and the models are not.
export HF_HOME=/data/hf
Serving them yourself

Once the weights are local, the per-token bill and the network dependency both go away. vLLM reads straight from the cache, so there is no second copy and no conversion step.

# vLLM finds the model in the HF cache by its hub id.
vllm serve meta-llama/Llama-3.1-8B-Instruct \
  --api-key "$VLLM_API_KEY" \
  --max-model-len 8192

# From here it is an OpenAI-compatible endpoint on :8000, and the
# InferenceClient can point at it too — see the next step.
The same client, against your own server

InferenceClient speaks to any OpenAI-compatible endpoint, so moving from a hosted provider to your own GPU is a base URL. Note that a URL and a provider are MUTUALLY EXCLUSIVE — passing both is an error.

# No provider= here: a URL and a provider cannot both be given.
local = InferenceClient(
    base_url="http://localhost:8000/v1",
    api_key=os.environ["VLLM_API_KEY"],
)

response = local.chat.completions.create(
    model="meta-llama/Llama-3.1-8B-Instruct",
    messages=[{"role": "user", "content": "Explain a database index."}],
    max_tokens=200,
)

# Identical call, identical response object. The only thing that
# changed is who pays for the tokens.
print(response.choices[0].message.content)
Install

@huggingface/inference is the JS equivalent of InferenceClient. @huggingface/hub covers the registry operations.

npm install @huggingface/inference @huggingface/hub

export HF_TOKEN="hf_your-token"
One client, many providers

Hub ids everywhere. Switching provider is one field, and the model id does not change with it — which is the point of routing through Hugging Face at all.

import { InferenceClient } from "@huggingface/inference";

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

const response = await client.chatCompletion({
  provider: "auto",                    // or "together", "groq", ...
  model: "meta-llama/Llama-3.1-8B-Instruct",
  messages: [{ role: "user", content: "Explain a database index." }],
  max_tokens: 200,
});

console.log(response.choices[0].message.content);
Streaming

chatCompletionStream yields OpenAI-shaped chunks whichever provider served it, which is what keeps the consuming code provider-agnostic.

const stream = client.chatCompletionStream({
  provider: "auto",
  model: "meta-llama/Llama-3.1-8B-Instruct",
  messages: [{ role: "user", content: "Explain B-trees in 200 words." }],
  max_tokens: 400,
});

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) process.stdout.write(delta);
}
Downloading weights once, from Node

listFiles and downloadFile cover the registry side. PIN THE REVISION for anything reproducible — a hub id alone points at a branch that moves.

import { listFiles, downloadFile } from "@huggingface/hub";

const repo = { type: "model", name: "meta-llama/Llama-3.1-8B-Instruct" };

for await (const file of listFiles({ repo, accessToken: process.env.HF_TOKEN })) {
  if (!file.path.endsWith(".safetensors")) continue;

  const blob = await downloadFile({
    repo,
    path: file.path,
    revision: "refs/pr/1",        // pin it, or `main` moves under you
    accessToken: process.env.HF_TOKEN,
  });

  console.log(file.path, blob.size);
}
The same client, against your own server

Once the weights are served locally, the endpoint is OpenAI-compatible and the call is unchanged. The bill is the only difference.

import OpenAI from "openai";

// vllm serve meta-llama/Llama-3.1-8B-Instruct --api-key "$VLLM_API_KEY"
const local = new OpenAI({
  baseURL: "http://localhost:8000/v1",
  apiKey: process.env.VLLM_API_KEY,
});

const response = await local.chat.completions.create({
  model: "meta-llama/Llama-3.1-8B-Instruct",
  messages: [{ role: "user", content: "Explain a database index." }],
});

console.log(response.choices[0].message.content);

QUESTIONS

Which languages are the Hugging Face examples in?

Python and JavaScript. Every sample runs as pasted and reads its credentials from an environment variable — no key is ever written into the code.

Which package do I install for Hugging Face?

The samples use huggingface_hub. The install step on each language tab gives the exact command.

Which Hugging Face model do these examples use?

meta-llama/Llama-3.1-8B-Instruct, checked against the official documentation on 26 September 2026. Model ids change often; if a call returns a model-not-found error, check the current list in the official docs.

Where is the official Hugging Face documentation?

https://huggingface.co/docs — it is linked at the bottom of this page, and it is the authority whenever it disagrees with a sample here.

ALSO IN HOSTING, GATEWAYS & LOCAL

The authority

Official Hugging Face documentation

Model names, pricing and rate limits change faster than any page here can. When this page and the official docs disagree, the official docs are right.

Read the docs ↗

https://huggingface.co/docs

New drops, every week

Free tools & Claude templates, landing regularly.

We keep shipping new free tools, code recipes and Claude Code templates. Follow @freeyantra on Instagram or join the newsletter so you never miss one.

Follow @freeyantra

or get them by email

Double opt-in. Unsubscribe any time. Privacy