guidance-ai/llguidance
Super-fast Structured Outputs
What it solves
Large language models produce free-form text, but many applications need outputs in strict formats: JSON objects, regular-expression patterns, or custom grammars. Unconstrained generation often yields invalid or malformed results, forcing retries or error-prone post-processing. llguidance solves this by constraining the decoding process itself, so the model can only generate tokens that lead to a valid string under the given grammar.
How it works
Given a context-free grammar (such as a JSON schema or regex), a tokenizer, and the token prefix generated so far, llguidance computes a token mask — a set of allowed next tokens that can still yield a string in the language defined by the grammar. It uses Earley's parsing algorithm on top of a lexer built from derivatives of regular expressions, and then traverses a prefix tree of all possible tokens to compute the mask efficiently. For a typical 128k-token tokenizer, mask computation takes about 50 microseconds per token, with no significant startup cost. It also supports "fast-forward" tokens, which can bypass intermediate tokens to speed up decoding.
Who it’s for
Developers building LLM applications that require structured outputs, and maintainers of inference backends or frameworks who want to add constrained decoding support. The library is already integrated into major systems like OpenAI's structured outputs, llama.cpp, vLLM, SGLang, Chromium, and more, so it's also useful for anyone using those systems and needing reliable grammar enforcement.
Highlights
- Supports a large subset of JSON schemas, regular expressions, and a Lark-like grammar format with embedded JSON schemas and regexes.
- Very fast: ~50μs per token mask for a 128k tokenizer, with negligible startup cost.
- No precomputation phase; masks are computed on the fly, avoiding the long startup delays seen in some alternative approaches.
- Available from Rust, C/C++, and Python, with bindings for easy integration.
Related
- Project
- Project
- Project
- Project
- Project