Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Efficient, Flexible and Portable Structured Generation for Rust
Rust bindings for XGrammar
Overview
XGrammar is an open-source library for efficient, flexible, and portable structured generation.
It leverages constrained decoding to ensure 100% structural correctness of the output. It supports general context-free grammar to enable a broad range of structures, including JSON, regex, custom context-free grammar, etc.
XGrammar uses careful optimizations to achieve extremely low overhead in structured generation. It has achieved near-zero overhead in JSON generation, making it one of the fastest structured generation engines available.
XGrammar features universal deployment. It supports:
- Platforms: Linux, macOS, Windows
- Hardware: CPU, NVIDIA GPU, AMD GPU, Apple Silicon, TPU, etc.
- Models: Qwen, Llama, DeepSeek, Phi, Gemma, etc.
Features
Installation
Add this to your Cargo.toml:
[]
= "0.1"
For HuggingFace tokenizer support:
[]
= { = "0.1", = ["hf"] }
Quick Start
JSON Schema Generation
use ;
EBNF Grammar
use Grammar;
let ebnf = r#"
root ::= expression
expression ::= term ("+" term | "-" term)*
term ::= factor ("*" factor | "/" factor)*
factor ::= number | "(" expression ")"
number ::= [0-9]+
"#;
let grammar = from_ebnf?;
Regular Expression
use Grammar;
let regex = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}";
let grammar = from_regex?;
With HuggingFace Tokenizers (requires hf feature)
use ;
// Load tokenizer from HuggingFace
let tokenizer = from_file?;
let tokenizer_info = from_huggingface?;
// Create and compile grammar
let grammar = builtin_json_grammar;
let mut compiler = new?;
let compiled_grammar = compiler.compile_grammar?;
// Create matcher and use for token-level generation
let mut matcher = new?;
// Allocate token bitmask for batch generation
let mut bitmask_data = allocate_token_bitmask;
// For string-based generation (simpler approach)
assert!;
assert!;
API Documentation
For detailed API documentation, visit docs.rs/xgrammar-rs.
License
This project is licensed under the Apache License - see the LICENSE file for details.