Structured Output and Tool Calling in vLLM and SGLang

Vladimir Lomtev•
Structured Output and Tool Calling in vLLM and SGLang

vLLM and SGLang can constrain generation so the model’s response exactly matches a JSON schema, regular expression, list of options, or grammar. For tool calling, the server must be launched with a parser for the specific model, and the guarantees depend on tool_choice: with required and a named function, the call will be parsed correctly; with auto the arguments may sometimes not match the schema. Format constraints do not make the answer correct in terms of meaning, so value validation in the application remains mandatory.

Prepared by AI Studio by Vladimir Lomtev on November 16, 2026, for developers connecting a local LLM to systems that expect a strict format: CRMs, accounting systems, and agents with tools. Parameters were checked against the documentation for vLLM structured outputs, vLLM tool calling and SGLang structured outputs. The code was syntax-checked, but we did not run it on a specific model.

Contents

Why “answer in JSON” is not enough

If you ask a model in the prompt to return JSON, it will usually do so. But “usually” is a bad fit for integration: an extra sentence before the opening brace, a missing field, a quote inside a string — and the parser fails. At a thousand documents a day, even rare failures turn into manual review.

Constrained decoding solves this at the engine level. At each generation step, the server knows which tokens are allowed by the schema or grammar and blocks the rest. The model physically cannot produce an invalid structure. The tradeoff is a small overhead for preparing constraints and the risk that an overly strict schema will force the model to fill in a field for which it has no data.

What constraints are available

Type What it defines Example use case
choice Response strictly from a list of options Routing support tickets by category
regex Response matching a regular expression Contract number, date, tax ID
json / response_format Response according to a JSON schema Extracting document fields
grammar Response according to a context-free EBNF grammar SQL query or a custom command language
structural_tag (vLLM) JSON schema inside specified tags in the text Reasoning plus a structured block

vLLM: backends and parameters

According to the vLLM documentation, it uses the XGrammar and Guidance backends. The backend is selected with --structured-outputs-config.backend, and the default is auto, which chooses a backend based on the request. The lm-format-enforcer backend is deprecated and, according to the documentation, will be removed in version 0.35.0.

If you are migrating code from older versions: fields such as guided_json were removed in v0.12.0; instead, use structured_outputs. The documentation also warns that changing the backend can alter the output: for example, lm-format-enforcer uses Python-style regular expressions, while XGrammar and Guidance use Rust-style regular expressions. Check your schemas and expressions when migrating.

JSON by schema through the standard response_format (the details in the example are fictional):

import os
from openai import OpenAI
from pydantic import BaseModel

class Invoice(BaseModel):
    supplier: str
    inn: str
    total_rub: float
    due_date: str

client = OpenAI(base_url="http://127.0.0.1:8000/v1", api_key=os.environ["VLLM_API_KEY"])
text = "Invoice from Romashka LLC, INN 7701234567, amount due 125,400 rubles by November 30, 2026."
reply = client.chat.completions.create(
    model="Qwen/Qwen3-8B",
    messages=[{"role": "user", "content": "Extract invoice details: " + text}],
    response_format={"type": "json_schema",
                     "json_schema": {"name": "invoice", "schema": Invoice.model_json_schema()}},
)
invoice = Invoice.model_validate_json(reply.choices[0].message.content)
print(invoice)

Selection from a list and a regular expression are passed through extra_body:

category = client.chat.completions.create(
    model="Qwen/Qwen3-8B",
    messages=[{"role": "user", "content": "What category does this request belong to: ‘I haven’t received my refund for the order’?"}],
    extra_body={"structured_outputs": {"choice": ["delivery", "payment and refunds", "quality", "other"]}},
)
contract = client.chat.completions.create(
    model="Qwen/Qwen3-8B",
    messages=[{"role": "user", "content": "Contract number from the text: ‘under contract No. DP-2026/0457 dated March 3’"}],
    extra_body={"structured_outputs": {"regex": r"DP-\d{4}/\d{4}"}},
)
print(category.choices[0].message.content, contract.choices[0].message.content)

SGLang: XGrammar by default

In SGLang, constraints are defined with a JSON schema, regular expression, or EBNF. Supported backends include XGrammar (default), Outlines, and llguidance; the choice is made with the --grammar-backend flag. The SGLang documentation recommends XGrammar for performance and capabilities and notes that Outlines supports only JSON schemas and regular expressions, without EBNF. A request with response_format in the json_schema format looks the same as in vLLM, so client code can be moved between servers without changes.

Reasoning models

For models that first write their reasoning and then the answer, the constraint should apply to the answer, not the reasoning. In vLLM, the server is started with a reasoning parser for this, for example --reasoning-parser deepseek_r1. For some models, according to the documentation, structured output in reasoning mode must be enabled explicitly with --structured-outputs-config.enable_in_reasoning=True. In SGLang, there is a separate page dedicated to structured output for reasoning models.

The vLLM documentation warns: in custom grammars with boundaries like </think> a match in the decoded text does not yet guarantee that the tokens will match and the parser will trigger. For such boundaries in XGrammar, use token-level structural tag elements.

Tool calling in vLLM

To let the model call functions through an OpenAI-compatible API, start the server with two flags:

vllm serve Qwen/Qwen3-8B \
  --host 127.0.0.1 --port 8000 \
  --api-key "$VLLM_API_KEY" \
  --enable-auto-tool-choice \
  --tool-call-parser hermes

--tool-call-parser is chosen based on the model: the documentation lists, for example, hermes, llama3_json, mistral, pythonic, deepseek_v3 and qwen3_xml. If the model's chat template does not support tool messages, pass it through --chat-template. Check the vLLM documentation and the model card to see which parser a specific model needs.

Behavior depends on tool_choice:

tool_choice What vLLM guarantees
Named function A correctly parsed call to this function; argument quality is not guaranteed
required One or more tool calls (starting with version 0.8.3)
auto The model decides for itself whether to call the tool; arguments can sometimes be invalid if the tool does not have strict: true set or if --tool-strict-level
none No calls; tool definitions still get included in the prompt unless --exclude-tools-when-tool-choice-none

is set. Parallel calls depend on the parser and the model. The documentation gives examples: Llama 3 does not support them, Llama 4 does, and Mistral 7B handles them poorly.

tools = [{
    "type": "function",
    "function": {
        "name": "get_order_status",
        "description": "Order status by order number",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "string"}},
            "required": ["order_id"],
        },
        "strict": True,
    },
}]
reply = client.chat.completions.create(
    model="Qwen/Qwen3-8B",
    messages=[{"role": "user", "content": "Where is my order 58213?"}],
    tools=tools,
    tool_choice="auto",
)
calls = reply.choices[0].message.tool_calls or []
for call in calls:
    print(call.function.name, call.function.arguments)

In SGLang, a similar role is played by the flag --tool-call-parser; the value auto takes the parser from the model's chat template. The list of parsers is in the SGLang arguments reference.

How to design the schema

  • Make fields optional if data may be missing. An required field forces the model to make something up. It's better to allow null and handle the absence in code.
  • Use enums instead of free text where the set of values is known: categories, statuses, currencies.
  • Keep the schema short. Dozens of nested levels make the task harder for the model and complicate constraint setup.
  • Describe fields. The description field in the schema tells the model what to put there.
  • Validate values after the response. The schema guarantees that a tax ID is a string, but not that it is a valid tax ID. Check control sums, dates, and amounts in code.

How to test on your own data

  1. Collect 100–200 real inputs with reference field values.
  2. Run them without constraints and with constraints, at temperature 0.
  3. Compare the share of valid responses, the share of correct values for each field, and response time.
  4. Separately test hard cases: missing data, contradictions in the document, long texts.
  5. For tools, check whether the model calls the right function when it should and does not call it when it should not.

If you work with Ollama, a similar approach is described in the article “Ollama and JSON Schema: Data Extraction”. How to measure model quality on your own tasks is covered in the article about your own benchmark for choosing an LLM.

Frequently Asked Questions

Does constrained decoding slow down generation? There is overhead for preparing and applying constraints; how noticeable it is depends on the backend, schema, and model. Measure it on your own workload.

Does a JSON schema guarantee correct data? No. It guarantees structure. The model can still put the wrong value in a field, so validation in code is required.

Why isn’t the model calling a tool? Common reasons: the server was started without --enable-auto-tool-choice, the wrong --tool-call-parser was selected for the model, the chat template doesn’t support tools, or tool_choice is set to none.

Can reasoning and JSON work at the same time? Yes, with a reasoning parser; for some models, structured output must be explicitly enabled in reasoning mode.

How Vladimir Lomtev’s AI Studio helps with structured output

Vladimir Lomtev’s AI Studio deploys LLMs on the company’s servers and integrates them with enterprise systems. For strict formats, that means:

  • designing the response schema and validation rules together with process owners;
  • configuring a vLLM or SGLang server with the required backends, tool parser, and reasoning parser;
  • comparing accuracy and latency on real documents with and without constraints;
  • embedding model responses into an accounting system, CRM, or agent with error handling.

The first step is to choose one document or request that is currently handled manually, define the required fields, and record what share of correctly filled fields will be acceptable. Discuss the project.

Bottom line: the server guarantees the format, validation guarantees the meaning

Structured output in vLLM and SGLang removes an entire class of integration errors: invalid JSON, extra text, unknown categories. For tools, choose the correct parser and tool_choiceand remember that auto mode without strict schemas does not provide guarantees. Validate field values in code, and measure quality on your own dataset.

Request an audit

Share your contact details and we will follow up.

← All articles

Comments (0)

Loading comments…

Leave a comment
No registration required

Book a strategy call
for agentic operations

Tell us which workflow you want to improve. We will map feasibility, risks, and the fastest MVP path.

By submitting, you agree to our privacy policy

Contacts

Global Operations

Serving U.S. clients remotely
with private cloud and on-prem options

Strategy calls by request

We respond after reviewing your workflow context.

info@agentsunrise.pro

For partnership inquiries

Have a proposal?

Write to us in messengers

© 2026 AgentSunrise