Sub topic 9
Serving an OpenAI-compatible API with vllm serve
This chapter covers running vLLM as an HTTP server and calling it with the standard OpenAI client. It assumes you can run Python and shell commands, know what a chat prompt and completion are, and have read the earlier chapters on offline inference, sampling parameters, and chat templates. You should also be comfortable reading JSON.
Why serve instead of running offline
Offline inference with the LLM class suits batch jobs: one process loads the model, runs a list of prompts, and exits. Most applications need something different. Many clients send requests at unpredictable times, and each client wants its own reply without sharing a Python process with the model.
vllm serve starts one long-lived process that loads the model once and exposes it over HTTP. Requests from many clients enter the same scheduler, so the continuous batching described earlier works across all of them. The API follows the OpenAI REST format, so code written for OpenAI usually works after you change the base URL.
Starting the server
The command takes a model name or a local path, followed by options:
vllm serve Qwen/Qwen2.5-1.5B-Instruct \
--max-model-len 4096 \
--gpu-memory-utilization 0.85 \
--port 8000On startup the server does these steps in order:
- Downloads the weights from Hugging Face, or reads them from the local cache.
- Loads the weights onto the GPU.
- Runs a profiling pass to measure how much memory the model needs for activations.
- Allocates the KV cache from the memory that remains under your
--gpu-memory-utilizationlimit. - Starts listening on the port.
The server is not ready until step 5. Loading a large model can take minutes, so a client that connects early gets a connection error. Health checks should wait for the /health endpoint to return HTTP 200.
Three options matter in almost every deployment:
| Option | Meaning | Default behavior |
|---|---|---|
| `--max-model-len` | Largest total length of prompt plus output, in tokens, for one request | Taken from the model's config, which can be very large |
| `--gpu-memory-utilization` | Fraction of GPU memory vLLM may use in total | Around 0.9 |
| `--port` | TCP port for the API | 8000 |
Setting --max-model-len below the model's maximum is a common fix when startup fails because the KV cache cannot hold even one full-length sequence. The next chapter treats these settings in detail.
The request path
A request goes through several layers before any token is generated. The API layer parses the JSON and applies the chat template. The engine then tokenizes the prompt and puts the request in the scheduler's waiting queue. When the scheduler has KV cache blocks free, it admits the request into the running batch. Tokens stream back to the API layer as they are produced.
Because the server applies the chat template for you, the client sends structured messages and never builds the special tokens itself. This is the same template step you saw in llm.chat.
Endpoints
The server exposes these main routes:
| Route | Purpose |
|---|---|
| `/v1/chat/completions` | Chat requests with a `messages` list |
| `/v1/completions` | Raw text completion with no chat template |
| `/v1/models` | Lists the model names the server accepts |
| `/health` | Returns 200 when the server is up |
| `/metrics` | Prometheus metrics, covered in a later chapter |
Use /v1/chat/completions with instruction-tuned models. Use /v1/completions with base models, which have no chat template, or when you want to control the exact prompt text.
Calling the server with the OpenAI client
Install the client with pip install openai, then point it at your server:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
response = client.chat.completions.create(
model="Qwen/Qwen2.5-1.5B-Instruct",
messages=[{"role": "user", "content": "What is continuous batching?"}],
temperature=0.2,
max_tokens=150,
)
print(response.choices[0].message.content)Details that cause common errors:
base_urlmust include the/v1suffix.api_keyis required by the client library, but the server ignores it unless you start it with--api-key. Any string works otherwise.modelmust match the name the server serves. By default that is the string you passed tovllm serve. A mismatch returns a 404 error. Use--served-model-nameto expose a shorter alias.
You can also call the server without the client library. This is useful for debugging:
curl -s http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "Qwen/Qwen2.5-1.5B-Instruct",
"messages": [{"role": "user", "content": "Say hello."}],
"max_tokens": 20
}'Mapping sampling parameters
The SamplingParams you used offline map onto request fields. temperature, top_p, max_tokens, stop, and seed are standard OpenAI fields. vLLM adds extras such as top_k and repetition_penalty. The OpenAI client does not know these fields, so pass them through extra_body:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
response = client.chat.completions.create(
model="Qwen/Qwen2.5-1.5B-Instruct",
messages=[{"role": "user", "content": "Name three sorting algorithms."}],
max_tokens=100,
extra_body={"top_k": 40, "repetition_penalty": 1.1},
)
print(response.choices[0].message.content)If you omit max_tokens, the reply can run until it fills the remaining context. Set it on every request in production, because a long reply holds KV cache blocks for its whole duration.
Streaming
With stream=True, the server sends tokens as they are generated, using server-sent events. The client sees the first token after prefill finishes, which is the time to first token. For chat interfaces, this makes the application feel faster even though total generation time is unchanged.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
stream = client.chat.completions.create(
model="Qwen/Qwen2.5-1.5B-Instruct",
messages=[{"role": "user", "content": "Explain prefill in one paragraph."}],
max_tokens=120,
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
print()Securing and exposing the server
By default the server listens on all interfaces without authentication. Three options reduce the risk:
--api-keyrequires clients to sendAuthorization: Bearer <key>.--host 127.0.0.1restricts access to the local machine.- A reverse proxy such as nginx can add TLS and rate limits in front.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| Out-of-memory error at startup | Model plus KV cache exceed the memory limit | Lower `--max-model-len` or `--gpu-memory-utilization`, or use a smaller or quantized model |
| Error that the KV cache cannot hold one sequence | `--max-model-len` too large for the free memory | Lower `--max-model-len` |
| 404 "model does not exist" | `model` field differs from the served name | Check `/v1/models` |
| Connection refused | Server still loading, or wrong port | Wait for `/health`, then check `--port` |
| Chat request fails with a template error | Base model with no chat template | Use `/v1/completions`, or an instruct model |
| Requests slow under load | Many requests waiting for KV blocks | Check the waiting-request metric and tune concurrency |
Checking concurrency behavior
You can see continuous batching working by sending several requests at once. This script uses a thread pool and prints the time each request took:
import time
from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
def ask(i: int) -> float:
start = time.time()
client.chat.completions.create(
model="Qwen/Qwen2.5-1.5B-Instruct",
messages=[{"role": "user", "content": f"Write one fact about the number {i}."}],
max_tokens=60,
)
return time.time() - start
with ThreadPoolExecutor(max_workers=16) as pool:
times = list(pool.map(ask, range(16)))
print(f"slowest: {max(times):.2f}s, fastest: {min(times):.2f}s")Sixteen requests finish in far less than sixteen times the single-request time. The scheduler runs them in one batch and each decode step produces a token for every request. Per-request latency rises somewhat as the batch grows, but total throughput rises much more.
Exercise
A client calls your vLLM server with the OpenAI library and gets a 404 error saying the model does not exist, although the server is running and /health returns 200. Name two things you would check and the command or setting for each.
Show answer
First, run curl -s http://localhost:8000/v1/models and compare the listed model id with the model string in the client call. They must match exactly. Second, check whether the server was started with --served-model-name, which replaces the default name, and either use that alias in the client or remove the option. Also confirm base_url ends in /v1 and points to the right port.
Exercise
You want to use top_k=40 with the OpenAI Python client against vLLM. The client raises an error for the unknown argument. How do you send it, and why does the client reject it?
Show answer
Pass it through extra_body, for example extra_body={"top_k": 40}. The OpenAI client only accepts parameters in the official OpenAI API schema. top_k is a vLLM extension, so extra_body adds it to the JSON payload without the client checking it.