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.
--grammar-backend when launching the server:
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 theGrammarManager which:
- Compiles grammars - Converts JSON schemas, regex, or EBNF into efficient grammar objects
- Caches compiled grammars - Reuses compiled grammars across requests for better performance
- Applies constraints during generation - Modifies logits to ensure only valid tokens are sampled
- Supports jump-forward optimization - Skips ahead when only one valid continuation exists
python/sglang/srt/constrained/grammar_manager.py:24
Performance Considerations
Grammar Compilation Overhead
Grammar Compilation Overhead
The first request with a new schema incurs compilation overhead. Subsequent requests with the same schema benefit from caching.
Logit Processing Cost
Logit Processing Cost
Applying grammar constraints adds per-token overhead. The impact varies by grammar complexity.
Jump-Forward Optimization
Jump-Forward Optimization
When the grammar has only one valid continuation, SGLang can skip token-by-token generation and jump forward, significantly improving throughput.
