Every agent builder has lived through it. You ask a model to call a tool. It returns something that looks kind of like JSON. Kind of. You patch the parser. You add regex. You pray. Then the next model version changes its output format and everything breaks again.

XGrammar-2 fixes this with Structural Tag. It is a JSON-based protocol that describes exactly what an LLM can output. Not suggests. Not hopes. Describes. The serving engine then enforces that description at every single token.

This is not post-hoc validation. The model literally cannot emit an invalid token.

What Structural Tag Actually Is

Structural Tag is a domain-specific language written in JSON. You compose a tree of format objects that describe the desired output structure. The serving engine compiles that tree into a grammar, generates token masks at each decoding step, and blocks anything that would violate your specification.

Think of it like this. Traditional structured generation gives the model a JSON schema and says "please follow this." Structural Tag says "here is the exact shape of your output, including the free-text parts, the reasoning parts, the tool-call wrappers, and the delimiters. Follow it or you cannot generate."

The key insight is composability. JSON Schema, regex, literal strings, and raw token IDs are all first-class atomic types. You nest and combine them to describe anything from a simple object response to a multi-part reasoning-plus-tool-call format.

The Five Building Blocks

The DSL defines five core tag types that cover every output pattern agents actually need.

Tag

Tag matches begin + content + end. The simplest wrapper. You define a start marker, a content format, and an end marker. The model must emit all three in order.

For reasoning tags, you might define begin: "<think>", content: any_text, end: "</think>". The model can ramble inside the tags but it cannot forget to close them.

Sequence

Sequence chains parts together. First this, then that. You use it to compose multi-section outputs like reasoning followed by tool calls followed by a final response.

AnyText

AnyText matches arbitrary text until it hits an enclosing boundary. This is where free-form reasoning lives. The model generates normally until the end marker appears. At that point, the engine forces the model out of the free-text section and into the next structured part.

TriggeredTags

TriggeredTags is the clever one. The model produces free text by default. Once it emits a trigger string, it must switch into a structured tag. After the tag ends, free text resumes.

This is exactly how tool calling works in practice. The model thinks out loud, then says "okay let me call a function," then emits the structured call. TriggeredTags captures this without hardcoding any particular tool format.

The excludes field prevents trigger strings from appearing in the final output. This matters. You do not want the model accidentally emitting <function= inside its reasoning text.

JSONSchema

JSONSchema constrains content to a JSON Schema. You can also specify a style parameter for models that expect XML-wrapped parameters instead of raw JSON. The engine supports json, qwenxml, minimaxxml, and deepseek_xml styles out of the box.

A Real Example

Here is what DeepSeek V4 output looks like with reasoning and a tool call:

Let me check the weather in Beijing.
<|DSML|tool_calls>
<|DSML|invoke name="get_weather">
<|DSML|parameter name="city" string="true">Beijing</|DSML|parameter>
</|DSML|invoke>
</|DSML|tool_calls>

Two distinct parts. Free-form reasoning until </thinking> or equivalent. Then either more free text or a structured tool call triggered by <|DSML|tool_calls>.

The Structural Tag for this:

{
  "type": "structural_tag",
  "format": {
    "type": "sequence",
    "elements": [
      {
        "type": "tag",
        "begin": "",
        "content": { "type": "any_text" },
        "end": "</thinking>"
      },
      {
        "type": "triggered_tags",
        "triggers": ["<|DSML|tool_calls>"],
        "tags": [
          {
            "type": "tag",
            "begin": "<|DSML|tool_calls>\n",
            "content": {
              "type": "tag",
              "begin": "<|DSML|invoke name=\"get_weather\">\n",
              "content": {
                "type": "json_schema",
                "json_schema": { ... },
                "style": "deepseek_xml"
              },
              "end": "</|DSML|invoke>\n"
            },
            "end": "</|DSML|tool_calls>\n"
          }
        ],
        "excludes": ["<|DSML|", "</thinking>"]
      }
    ]
  }
}

Nesting a tag inside a tag inside triggered_tags inside a sequence. This is why composability matters. No single format type handles everything. But together they handle anything.

Why This Is Different From JSON Schema Alone

JSON Schema says "the output should be valid JSON with these fields." That is useful. But it does not handle:

  • Free-form text mixed with structured fragments
  • Model-specific wrappers around tool calls
  • Reasoning tags that appear before or between tool calls
  • Token-level delimiters that do not map cleanly to text
  • Dynamic switching between formats mid-output

Structural Tag handles all of these because it describes the full output as a tree of composable chunks. JSON Schema becomes one leaf type in that tree. It is powerful but it is not the whole language.

The Integration Story

XGrammar-2 ships with built-in Structural Tags for DeepSeek V4, Qwen 3.6, GPT-OSS, and other popular models. The structural tag is already integrated into SGLang, vLLM, TensorRT-LLM, and MLC-LLM. You get strict tool calling and reasoning support without writing a single line of grammar code.

You can also pass custom structural tags through the OpenAI-compatible API:

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4",
    messages=[...],
    extra_body={
        "response_format": {
            "type": "structural_tag",
            "format": {
                "type": "tag",
                "begin": "<answer>",
                "content": {
                    "type": "json_schema",
                    "json_schema": {
                        "type": "object",
                        "properties": {
                            "status": { "type": "string" },
                            "message": { "type": "string" }
                        }
                    }
                },
                "end": "</answer>"
            }
        }
    }
)

This means any downstream agent framework can define its own output structure and enforce it at the serving layer. No prompt engineering. No fragile regex. No praying.

How It Handles Complexity at Scale

Agent workloads are not getting simpler. A single request might involve dozens of tools. The grammar for that gets huge fast. XGrammar-2 addresses this with three specific optimizations.

Cross-Grammar Cache

Different grammars share sub-structures. Every JSON schema with a string field uses the same {"type": "string"} sub-grammar. XGrammar-2 uses an automaton-based hierarchical hashing algorithm to find and reuse these shared parts across and within grammars. In tests with 50 tools, nearly 50% of structures get reused.

Repetition State Compression

An array of up to 1 million items would naively require preprocessing proportional to the count. XGrammar-2 introduces a native repetition primitive that stays constant-size regardless of repetition count. A complex JSON schema that took 534 ms to preprocess now takes 5.37 ms. That is a 100x reduction.

Batching and Speculative Decoding

XGrammar-2 provides batch APIs that process multiple grammar states in one C++ pass. No Python loops. For speculative decoding, the engine can traverse a draft tree once and generate masks for all nodes. It also overlaps mask generation on the CPU with model verification on the GPU. The result is near-zero overhead even in high-throughput serving.

Combined, these optimizations deliver up to 80x faster compilation than the original XGrammar, with near-zero end-to-end latency overhead.

Deployment Everywhere

Agents do not just run on A100 clusters. They run on laptops, phones, and edge devices. XGrammar-2 uses TVM-FFI, an open ABI and FFI library for ML systems, to provide consistent APIs across platforms.

Current support includes:

  • Languages: Python, C++, Rust, JavaScript
  • Frameworks: PyTorch, JAX, MLX
  • Operating systems: Windows, macOS, Linux
  • Heterogeneous hardware

On-device scenarios benefit most. Small models hallucinate output formats more often than large ones. Constrained decoding gives them guardrails they desperately need.

What the Numbers Say

The Berkeley Function Calling Leaderboard v3 measures both schema accuracy and output accuracy in multi-tool settings. Across four models of different scales, Structural Tag achieves 100% schema accuracy. Every tool call conforms to the target JSON schema. Output accuracy also improves substantially, especially for smaller models, because format-related failures simply disappear.

Efficiency tests measure compilation time as tool counts scale from 10 to 500. XGrammar-2 achieves up to 80x speedup over XGrammar. End-to-end request latency in SGLang shows minimal overhead in single-batch settings with warm-up and comparable output lengths.

Why This Matters for Production

If you are building agents, you have three options for structured output.

Option one: prompt engineering. Hope the model follows instructions. It usually does. Until it does not. At 3 AM. On a Friday.

Option two: post-hoc validation. Generate freely, then check. This wastes tokens on invalid output, breaks streaming, and introduces latency you cannot hide.

Option three: constrained decoding with Structural Tag. Define the exact output shape. Enforce it at every token. Get 100% reliability with near-zero overhead.

Option three is now available in every major serving engine. SGLang, vLLM, TensorRT-LLM, and MLC-LLM all support it. You pass a JSON DSL through the standard API. The engine handles the rest.

The Bigger Picture

XGrammar-2 was released on May 4, 2026. It has already been adopted by leading frontier AI labs and integrated into the serving engines that power most production LLM deployments. The paper is on arXiv at 2601.04426.

What makes this significant is not the speedup numbers or the cross-platform support. It is the unification. Before Structural Tag, every agent framework invented its own way to describe output structure. Every serving engine implemented partial support for some subset of formats. Every model had its own tool-calling convention.

Structural Tag collapses all of that into one protocol. One JSON DSL describes OpenAI Harmony format, open-source model tool calling, custom agent output shapes, and anything else you can express as a tree of composable chunks. One implementation enforces it across all major serving engines. One API surface lets developers define and deploy custom structures without touching C++.

This is what standardization looks like when it actually works.

Citations

Suggested Title

Structural Tag: The JSON DSL That Makes LLM Output Actually Predictable

Word Count

1,687 words

Fact-Check Notes

  • The 80x compilation speedup claim comes from the MLC blog post. Verify against your own benchmarks if you plan to cite it in a technical context.
  • The "leading frontier AI labs" adoption claim is stated in the MLC blog but not named specifically. Consider softening or requesting specifics if publishing in a context that requires named sources.
  • The 100% schema accuracy figure comes from BFCL-V3 evaluation on the simple and parallel subsets. Full BFCL results may differ.
  • Cross-grammar cache reuse rate of "nearly 50%" is from the blog post's JSON Schema compilation test with 50 tools.
  • Repetition compression example (534 ms to 5.37 ms) is from the blog post's complex JSON schema test.