Skip to main content
SGLang enables you to constrain model outputs to follow specific formats using JSON schemas, regular expressions, or EBNF grammars. The model output is guaranteed to follow the specified constraints.

Grammar Backends

SGLang supports three grammar backends for constrained generation:

XGrammar

Default backend - Best performance and utility. Supports JSON schema, regex, and EBNF.

Outlines

Supports JSON schema and regex constraints.

Llguidance

Supports JSON schema, regex, and EBNF constraints.
To select a backend, use --grammar-backend when launching the server:
For better output quality, explicitly include instructions in your prompt to guide the model. For example: “Please generate the output in the following JSON format: …”

JSON Schema Constraints

Constrain outputs to valid JSON following a specific schema. This is useful for extracting structured data from model responses.

Using Pydantic Models

Using Direct JSON Schema

EBNF Grammars

Define custom grammars using Extended Backus-Naur Form (EBNF) notation. XGrammar uses the GGML BNF format.

Regular Expression Constraints

Constrain outputs to match a specific regex pattern.

Structural Tags

Combine multiple schemas with trigger patterns for complex structured outputs, such as function calling.

Native API Usage

You can also use structured outputs with the native SGLang API:

Implementation Details

SGLang’s constrained generation is implemented through the GrammarManager which:
  1. Compiles grammars - Converts JSON schemas, regex, or EBNF into efficient grammar objects
  2. Caches compiled grammars - Reuses compiled grammars across requests for better performance
  3. Applies constraints during generation - Modifies logits to ensure only valid tokens are sampled
  4. Supports jump-forward optimization - Skips ahead when only one valid continuation exists
The grammar compilation happens asynchronously to avoid blocking request processing. Requests wait in a grammar queue until their grammar objects are ready. Source: python/sglang/srt/constrained/grammar_manager.py:24

Performance Considerations

The first request with a new schema incurs compilation overhead. Subsequent requests with the same schema benefit from caching.
Applying grammar constraints adds per-token overhead. The impact varies by grammar complexity.
When the grammar has only one valid continuation, SGLang can skip token-by-token generation and jump forward, significantly improving throughput.

Configuration Options

For XGrammar technical details and performance characteristics, see the XGrammar technical overview.