DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. AI/ML
  4. Migrating From the OpenAI API to vLLM: Configure It Right
Content sponsored by Runpod logo

Migrating From the OpenAI API to vLLM: Configure It Right

Pointing an OpenAI client at vLLM takes three code changes. Tool calling, structured output, context length and reasoning need server flags. Here they are.

By 
Matt Sarrel
·
Nov. 23, 26 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
84 Views

vLLM is an open-source inference engine that serves open-weight models, such as those on Hugging Face, on GPUs you control. It ships an HTTP server that implements the same routes as OpenAI's API, such as /v1/chat/completions and /v1/models, so code written for the OpenAI SDK can talk to it after a change of base URL. The routes match, but some of the work behind them is up to you. OpenAI's servers turn their own models' output into tool calls and separate reasoning from answers with logic tuned to those models. vLLM serves many model families that format that output differently, so for those features you tell it at startup which parser fits the model you loaded. Until you do, requests that depend on them fail or return output your code does not expect.

Point an OpenAI client at a self-hosted vLLM endpoint, change the API key and model name, and a basic chat completion may work immediately. Then you try tool calling and get a 400 error, tool_calls returns empty, or the model returns JSON that your application cannot parse.

Tool-call parsers, structured output, context limits, and reasoning output require explicit configuration. Here's what breaks when you switch to vLLM, why it breaks, and how to configure the server to fix it.

The examples below use Qwen3-8B because it supports tool calling and a reasoning mode in one model, letting a single endpoint exercise tool-calling, structured output, and reasoning failures. I ran the tool-calling, structured output, reasoning, and sampling examples against a live endpoint, and the errors and log lines quoted from it are marked as such.

Connect the OpenAI Client

I'll be using Runpod for this demo. Runpod is a cloud GPU platform. Its Serverless product runs containers, called workers, that start when requests arrive and scale back down when traffic stops, and its vLLM worker packages the vLLM server so you deploy a model by choosing it and a GPU. The examples run on Runpod Serverless using its vLLM worker, which runs the vLLM OpenAI-compatible server behind a per-endpoint URL and exposes vLLM's engine arguments as environment variables. 

I tested with worker v2.29.0, which ships vLLM 0.31.0, on a single 48 GB GPU (RTX A6000). Worker v2.30.0 and later ship vLLM 0.32.0; the flags below are unchanged, but re-check the reasoning field name against your worker version. The worker maps an allowlist of vLLM serve flags to environment variables with the uppercased flag name, so --max-model-len becomes MAX_MODEL_LEN. Flags newer than that allowlist, or outside it, go through VLLM_EXTRA_ARGS, which is appended last and can override anything above. Any vLLM deployment works for this tutorial. Where the worker's variable name differs from the upstream vLLM serve flag, I give both.

The same problems follow you to the alternatives. Hugging Face has put TGI in maintenance mode and now recommends vLLM or SGLang in its place. SGLang uses the same model: you pass --tool-call-parser and --reasoning-parser when you start the server, and it returns reasoning in reasoning_content rather than the reasoning field current vLLM uses, so client code written for one breaks on the other. Ollama needs no parser flags, but its OpenAI-compatible endpoint does not reliably honor tool_choice, so you cannot force a tool call the way the test later in this article does. Whichever server you choose, the checklist at the end applies; only the flag names change.

Python
 
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["RUNPOD_API_KEY"],
    base_url=f"https://api.runpod.ai/v2/{os.environ['ENDPOINT_ID']}/openai/v1",
)

resp = client.chat.completions.create(
    model="qwen/qwen3-8b",
    messages=[{"role": "user", "content": "Name the capital of Australia."}],
)
print(resp.choices[0].message.content)


The model field must match what the server registered, and vLLM compares names exactly. I deployed Qwen/Qwen3-8B, but the worker registered it as qwen/qwen3-8b, and every request that used the original casing failed. The worker log said, "The model Qwen/Qwen3-8B does not exist." Call /v1/models before you write any request code and copy the name it returns. Using gpt-4o returns an invalid-model error unless you change call sites or set an alias. On the Runpod worker, OPENAI_SERVED_MODEL_NAME_OVERRIDE sets the served model name (upstream vLLM uses --served-model-name). An alias keeps the diff small, but it also hides which model is answering, so I change call sites and keep the real name in configuration.

Read the Server Log, Not the Status Code

On the endpoint I tested, every error vLLM returned reached the OpenAI client as the same response: a 502 Bad Gateway generated by the proxy in front of the worker. The wrong model name (a 404 from vLLM), a missing tool parser (a 400), an over-length prompt (a 400), and a parser crash (a 500) all looked identical from the client side:

Plain Text
 
openai.InternalServerError: Error code: 502 - {'title': 'Error 502: Bad gateway',
'detail': 'The origin web server returned an invalid or incomplete response to
Cloudflare. ...', 'retryable': True, 'retry_after': 60, ...}


The response tells you to wait 60 seconds and retry, and none of these errors go away on retry. The real cause appeared only in the worker log. Keep the server log open while you migrate, set max_retries=0 on the client (an argument to the OpenAI() constructor in the Python SDK, or the equivalent retry setting in your agent harness) during testing so a retry loop does not hide the first failure, and treat any 5xx from the OpenAI route as unexplained until the log explains it. Clients that run behind a different proxy may see the original status code, so check how yours behaves before you write error handling around it.

Agent harnesses do not change this. I pointed opencode at the same endpoint with the tool-calling settings removed and asked it to count the Python files in a directory. With the settings in place, it called its file-search tool and answered within seconds once the worker was warm. Without them, opencode’s background request to name the session, which sends no tools, succeeded, and every request that carried tools failed with the same “auto” tool choice error in the worker log. The harness reported nothing and kept retrying for more than 20 minutes until I stopped it. A harness inherits the server’s configuration; it cannot add a tool parser the server does not have.

Tool Calling Needs a Parser That Matches the Model

An agent workflow ported without server changes fails on its first request. vLLM rejects it with a 400 whose message reads:

Plain Text
 
"auto" tool choice requires --enable-auto-tool-choice and --tool-call-parser to be set


On my endpoint, that 400 arrived as the 502 described above, and tool_choice="required" was rejected the same way until both settings were in place.

The model doesn't return an OpenAI tool_calls object directly. It generates text in a model-specific format, which might be JSON inside <tool_call> tags or a Python-style function call. When using tool_choice="auto", vLLM requires both automatic tool choice to be enabled and an explicit parser definition.

Two settings fix it:

Purpose vLLM flag Runpod worker variable
Allow the model to decide when to call tools --enable-auto-tool-choice ENABLE_AUTO_TOOL_CHOICE=true
Convert model output into tool_calls --tool-call-parser hermes TOOL_CALL_PARSER=hermes


The two settings belong on the server, not in the request. The client keeps sending tools and tool_choice exactly as it did against OpenAI; what changes is how the server starts. On a vLLM server you run yourself, add the flags to the launch command:

Plain Text
 
vllm serve Qwen/Qwen3-8B --enable-auto-tool-choice --tool-call-parser hermes


On the Runpod worker, add the two environment variables to the endpoint (Manage, then Edit Endpoint, then Public Environment Variables) and save. In my test, saving the endpoint replaced the running worker within a minute, and the new worker started with the new settings. Check the worker log for the flags before you test.

Select a tool-call parser that matches the model's output format and chat template. For the Qwen3-8B deployment in this tutorial, use hermes. Other configurations include llama3_json for supported Llama 3 models and mistral for supported Mistral models. Check the parser requirements for the specific model and vLLM version you're deploying. A mismatched parser is not always silent. When I set llama3_json on Qwen3, the server started normally and then failed every tool request with a 500. The worker log showed why:

Plain Text
 
RuntimeError: Llama3JsonToolParser could not locate the bot token '<|python_tag|>' in the tokenizer.


The llama3_json parser looks for a special token that only Llama tokenizers define, so it fails on the first tool request rather than at startup. A parser that can load against the tokenizer but does not recognize the model's output format can fail without any error, leaving tool_calls empty and the raw markup in content. Test for both outcomes.

Test automatic tool calling with a request that clearly requires the function. Check tool_calls rather than relying on the HTTP status. Because auto lets the model decide whether to call a tool, repeat the test if it answers directly. To test whether vLLM can produce a structured function call independently of that decision, run a separate request with tool_choice="required". With hermes configured, both auto and required returned a parsed get_weather call with {"city": "Oslo"} as the arguments.

Python
 
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

resp = client.chat.completions.create(
    model="qwen/qwen3-8b",
    messages=[{"role": "user", "content": "What's the weather in Oslo?"}],
    tools=tools,
    tool_choice="required",
)
msg = resp.choices[0].message
assert msg.tool_calls, f"No tool call parsed. Raw content: {msg.content!r}"
print(msg.tool_calls[0].function.name, msg.tool_calls[0].function.arguments)


Under tool_choice="auto", validate arguments against your schema before execution to guard against malformed parameters. Specifying a named function or using tool_choice="required" triggers constrained decoding to guarantee valid JSON structure, though logical validation of parameter values is still required.

Parallel tool-calling support depends on model capabilities (e.g., Llama 4 supports parallel calls, whereas Llama 3 does not). Setting parallel_tool_calls=true allows multiple calls, but it won't make a model generate them if it doesn't support parallel tool calling.

Put Structured Output in the Request

vLLM supports response_format with "type": "json_schema", using a constrained decoding backend to mask out invalid tokens at generation time.

Relying on prompt-based JSON formatting without API schema constraints breaks as soon as the model adds anything around the JSON. When I asked Qwen3-8B for JSON in the prompt alone, it wrote a <think> block ahead of the object, and json.loads failed on the first character. The same request with response_format parsed in both of my runs. Enforce strict output structures directly in the request payload:

Python
 
from pydantic import BaseModel

class Ticket(BaseModel):
    product: str
    severity: int
    summary: str

resp = client.chat.completions.create(
    model="qwen/qwen3-8b",
    messages=[{"role": "user", "content": f"Extract the ticket fields as JSON:\n{ticket_text}"}],
    response_format={
        "type": "json_schema",
        "json_schema": {"name": "ticket", "schema": Ticket.model_json_schema()},
    },
)
ticket = Ticket.model_validate_json(resp.choices[0].message.content)


Constrained decoding guarantees the shape of the output, not the values. Across two server configurations, the same ticket text came back as valid JSON with severity 5 the first time and severity 1 the second. Validate the values your application acts on, not only the schema.

vLLM also supports custom constraints via extra_body. The structured_outputs block accepts choice for string enumerations, regex for pattern matching, and grammar for context-free grammars. If a classifier only needs to return one of five labels, choice is simpler than defining a JSON schema with a single enum field. The same caution applies: given "The site has been down for an hour" and five labels that included outage, the constrained output was account on one run and feature_request on the next.

Older code that passes guided_choice, guided_json, or the other guided-decoding fields fails silently on current vLLM. The request succeeds, the output is unconstrained, and only the server log says so:

Plain Text
 
Request contains the removed guided-decoding field(s) ['guided_choice'], which are ignored;
output will NOT be constrained. Use `structured_outputs` (or `response_format`) instead


Upstream vLLM configures structured-output backends automatically, or explicitly via --structured-outputs-config.backend. The Runpod worker has removed its GUIDED_DECODING variables and ignores them if set, so pass the backend option through VLLM_EXTRA_ARGS instead. If complex regular expressions or recursive references fail, verify backend compatibility before modifying schema definitions.

Context Length Is a Memory Decision

On self-hosted GPUs, context length requires explicit memory allocation at model startup.

vLLM allocates GPU memory for a key-value (KV) cache, which stores attention keys and values as requests are processed. The memory required per token depends on the model architecture:

Plain Text
 
KV bytes per token = 2 (K and V) × layers × KV heads × head dimension × bytes per value


vLLM reports the result at startup, and the numbers are worth reading. On the 48 GB test GPU, the worker budgeted 0.95 of the card's memory, about 45 GiB. Weights and runtime took 15.61 GiB, peak activations 1.57 GiB, and CUDA graphs 0.17 GiB, which left 27.83 GiB for the KV cache. vLLM logged the consequence directly: "GPU KV cache size: 202,640 tokens, Maximum concurrency for 8,192 tokens per request: 24.74x." Dividing the cache by its token count gives 144 KiB per token for Qwen3-8B.

For Llama 3.1 8B (32 layers, 8 KV heads, head dimension 128 in 16-bit precision), the KV cache requires 128 KiB per token. A single sequence using the full 131,072-token context window would consume 16 GiB of KV-cache capacity, in addition to the memory needed for model weights, activations, and CUDA graphs. This is the calculated capacity requirement, not a measurement of vLLM's total GPU memory allocation.

If context length is left unconfigured, vLLM defaults to the model's maximum supported sequence length. If available GPU memory cannot fit at least one maximum-length sequence cache, startup fails:

Plain Text
 
ValueError: The model's max seq len (131072) is larger than the maximum number
of tokens that can be stored in KV cache (...). Try increasing
`gpu_memory_utilization` or decreasing `max_model_len` when initializing the engine.


You have three options, each with a tradeoff:

  • Lowering MAX_MODEL_LEN (vLLM flag --max-model-len) limits maximum sequence length, freeing KV memory for concurrency. At 8,192 tokens, the test GPU could hold 24 full-length requests at once. Requests exceeding this limit return HTTP 400 errors, which on my endpoint reached the client as a 502.
  • Increasing GPU_MEMORY_UTILIZATION allocates a larger fraction of GPU memory to vLLM, though setting it too high increases the risk of out-of-memory errors. The worker I tested already starts at 0.95, so there is little room to raise it.
  • Moving to a GPU with more memory, or quantizing the KV cache with KV_CACHE_DTYPE=fp8, raises capacity at the cost of money or a small amount of accuracy.

Reasoning Models Need a Reasoning Parser

Models like Qwen3 output thought processes inside <think> tags. Without a reasoning parser, the <think> tags and reasoning text end up in message.content alongside the answer. If your application expects JSON, parsing fails.

Setting a reasoning parser separates the two:

vLLM flag Runpod worker variable
--reasoning-parser qwen3 REASONING_PARSER=qwen3


With a reasoning parser enabled, vLLM returns the answer in content and reasoning in a separate field. Current versions use reasoning; older versions used reasoning_content. On vLLM 0.31.0 the field was reasoning, and reasoning_content was absent. If your application needs to support both, check for either field:

Python
 
msg = resp.choices[0].message
reasoning = getattr(msg, "reasoning", None) or getattr(msg, "reasoning_content", None)
answer = msg.content


Reasoning parsers are model-specific (e.g., qwen3 for Qwen3, deepseek_r1 for DeepSeek-R1). To disable reasoning outputs on Qwen3, pass "chat_template_kwargs": {"enable_thinking": False} in extra_body. With thinking off, a yes-or-no question returned in 1.2 seconds with no reasoning text.

vLLM parses tool calls exclusively from content. Tool calls placed inside reasoning blocks are ignored. When combining structured output with reasoning, schemas apply strictly to the answer. Combining structured output with reasoning requires explicit opt-in: start the server with --structured-outputs-config.enable_in_reasoning=True. vLLM's docs additionally warn that on Qwen3 Coder, from v0.11.2 onward, structured outputs can fail silently when reasoning is on, and the reasoning text is not split into a separate field.

Sampling Defaults Come From the Model Repository

vLLM loads default sampling parameters from the model's Hugging Face generation_config.json. If you don't set temperature explicitly, vLLM and the hosted API may use different values. Your evaluation results can change even with identical prompts. vLLM says so at startup. Every worker in the test logged this warning:

Plain Text
 
Default vLLM sampling parameters have been overridden by the model's `generation_config.json`:
`{'temperature': 0.6, 'top_k': 20, 'top_p': 0.95}`. If this is not intended, please relaunch
vLLM instance with `--generation-config vllm`.


Token counts also vary due to tokenizer differences. Truncation rules, rate limits, and cost logic must process explicit usage fields in API responses rather than relying on estimated counts.

Verify Before You Move Traffic

Execute these validation checks in CI before routing production traffic, and rerun them whenever updating models, parsers, or worker images:

  1. List models from /v1/models and confirm the name your code sends is registered, including its casing.
  2. Force one known error, such as an unknown model name, and confirm your client receives a status code and message you can act on. If it does not, route errors through the server log until it does.
  3. Send a tool-calling request with tool_choice="auto" and assert that tool_calls is populated and content holds no raw call markup.
  4. Validate tool arguments against the function schema, and decide what the agent does with a malformed call.
  5. Send every structured-output request through response_format or structured_outputs, search the codebase for leftover guided-decoding fields, and validate the result with the same model class you use in production.
  6. Test requests near the configured MAX_MODEL_LEN limit, accounting for chat-template overhead and the requested output-token budget. Verify that requests exceeding the supported context length return an error your client handles.
  7. For reasoning models, confirm the answer arrives without <think> tags and that your code reads the reasoning field under the name your server version uses.
  8. Pin temperature, top-p, and maximum tokens in every request, then rerun your evaluation set against both the old and new endpoints with identical parameters.
  9. When disabling a boolean engine arg, set the env var to false and confirm the worker log shows the --no-<flag> form, not --<flag> false.

Resources

  • vLLM documentation: Tool calling, Structured outputs, Reasoning outputs, and OpenAI-compatible server.
  • Runpod documentation: vLLM worker configuration reference, OpenAI compatibility, and migrating from OpenAI.

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook