vLLM Free code examples in Python and JavaScript
High-throughput self-hosted serving for when one GPU must serve many users.
WHAT THIS PAGE COVERS
Continuous batching — the reason throughput jumps without more hardware.
Qwen/Qwen2.5-1.5B-Instruct
vllm
Model ids change. If a sample returns a 404 on the model, that is the first thing to check against the official docs.
Linux and an NVIDIA GPU is the supported path. --torch-backend=auto picks the CUDA build that matches the driver, which is the step that otherwise goes wrong.
uv pip install vllm --torch-backend=auto
# A served deployment should require a key. The server reads it from
# the environment and clients send it as a normal bearer token.
export VLLM_API_KEY="a-long-random-string"
vllm serve Qwen/Qwen2.5-1.5B-Instruct --api-key "$VLLM_API_KEY"
An OpenAI-compatible server, so the client is the OpenAI client. The model name is the full Hugging Face repo id — not a short alias.
import os
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:8000/v1",
api_key=os.environ["VLLM_API_KEY"],
)
response = client.chat.completions.create(
model="Qwen/Qwen2.5-1.5B-Instruct", # the full repo id
messages=[{"role": "user", "content": "Explain a database index."}],
)
print(response.choices[0].message.content)
THESE THREE ARE THE DEPLOYMENT. max-num-seqs is how many sequences may be in flight at once — the batching width. gpu-memory-utilization is how much of the card vLLM may claim for the KV cache, and a bigger cache is what allows a wider batch.
vllm serve Qwen/Qwen2.5-1.5B-Instruct \
--api-key "$VLLM_API_KEY" \
--max-num-seqs 256 \
--gpu-memory-utilization 0.90 \
--max-model-len 8192
# max-num-seqs concurrent sequences. Higher = more throughput
# and higher per-request latency.
# gpu-memory-utilization fraction of VRAM for weights + KV cache.
# 0.90 is aggressive; leave headroom if anything
# else shares the card.
# max-model-len context per sequence. THIS IS THE ONE PEOPLE
# OVERSPEND ON: the KV cache is proportional to
# it, so asking for 128k when you use 4k cuts
# the batch width by a factor of thirty.
Run this against one GPU. Sequential requests measure latency; concurrent ones measure throughput, and the gap between them IS continuous batching. If total time barely moves as concurrency rises, the GPU was idle before.
import asyncio
import time
from openai import AsyncOpenAI
client = AsyncOpenAI(
base_url="http://localhost:8000/v1",
api_key=os.environ["VLLM_API_KEY"],
)
async def one(prompt: str) -> int:
response = await client.chat.completions.create(
model="Qwen/Qwen2.5-1.5B-Instruct",
messages=[{"role": "user", "content": prompt}],
max_tokens=128,
)
return response.usage.completion_tokens
async def measure(concurrency: int) -> None:
started = time.perf_counter()
counts = await asyncio.gather(
*(one(f"Explain concept number {i}.") for i in range(concurrency)))
elapsed = time.perf_counter() - started
print(f"{concurrency:>3} concurrent "
f"{sum(counts) / elapsed:7.0f} tokens/sec {elapsed:5.1f}s")
for concurrency in (1, 8, 32, 128):
asyncio.run(measure(concurrency))
The metrics endpoint is Prometheus format and carries the numbers that matter: how many sequences are running, how many are queued, and how full the KV cache is.
curl -s http://localhost:8000/metrics | grep -E 'num_requests|gpu_cache_usage'
# vllm:num_requests_running in flight right now
# vllm:num_requests_waiting QUEUED. Persistently above zero means
# max-num-seqs or the KV cache is the
# bottleneck, not the GPU's compute.
# vllm:gpu_cache_usage_perc KV cache fullness. Pinned near 1.0
# with requests waiting means
# max-model-len is too generous.
vLLM itself is Python and runs as a server; nothing is installed in Node beyond an OpenAI client.
# On the GPU box:
# uv pip install vllm --torch-backend=auto
# vllm serve Qwen/Qwen2.5-1.5B-Instruct --api-key "$VLLM_API_KEY"
npm install openai
export VLLM_API_KEY="a-long-random-string"
Standard OpenAI client, different base URL. The model is the full repo id the server was started with.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "http://localhost:8000/v1",
apiKey: process.env.VLLM_API_KEY,
});
const response = await client.chat.completions.create({
model: "Qwen/Qwen2.5-1.5B-Instruct",
messages: [{ role: "user", content: "Explain a database index." }],
});
console.log(response.choices[0].message.content);
Fire n requests at once and divide tokens by wall clock. Throughput that climbs steeply with concurrency is the batcher filling a GPU that was previously idle between requests.
async function one(prompt) {
const response = await client.chat.completions.create({
model: "Qwen/Qwen2.5-1.5B-Instruct",
messages: [{ role: "user", content: prompt }],
max_tokens: 128,
});
return response.usage.completion_tokens;
}
for (const concurrency of [1, 8, 32, 128]) {
const started = Date.now();
const counts = await Promise.all(
Array.from({ length: concurrency }, (_, i) =>
one(`Explain concept number ${i}.`),
),
);
const seconds = (Date.now() - started) / 1000;
const total = counts.reduce((sum, n) => sum + n, 0);
console.log(
`${String(concurrency).padStart(3)} concurrent ` +
`${Math.round(total / seconds)} tokens/sec ${seconds.toFixed(1)}s`,
);
}
vLLM batches; it does not police. A single caller opening five hundred streams fills max-num-seqs and everyone else queues, so the fairness has to live in front of the server.
// A bounded pool in front of the server. The limit should be a
// fraction of --max-num-seqs, not equal to it, so other callers can
// still get admitted.
let inFlight = 0;
const MAX_PER_CLIENT = 16;
const waiting = [];
async function submit(prompt) {
if (inFlight >= MAX_PER_CLIENT) {
await new Promise((resolve) => waiting.push(resolve));
}
inFlight++;
try {
return await one(prompt);
} finally {
inFlight--;
waiting.shift()?.();
}
}
QUESTIONS
Which languages are the vLLM 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 vLLM?
The samples use vllm. The install step on each language tab gives the exact command.
Which vLLM model do these examples use?
Qwen/Qwen2.5-1.5B-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 vLLM documentation?
https://docs.vllm.ai/ — 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 vLLM 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.
https://docs.vllm.ai/