GBNF Grammar is a notation for defining Context-Free Grammars (CFGs) that constrain the token generation process of a language model. It acts as a strict set of production rules, forcing the model's output to conform to a predefined syntactical structure, such as valid JSON or a custom data format, by dynamically masking invalid tokens during decoding.
Glossary
GBNF Grammar

What is GBNF Grammar?
GBNF (GGML BNF) is a formal grammar notation used to define syntactical rules for constrained decoding, ensuring language model output strictly matches a specified format.
Primarily used in high-performance inference engines like llama.cpp, GBNF defines rules using a syntax of terminal strings and non-terminal symbols. During grammar-constrained generation, the engine compiles these rules into a Finite State Machine (FSM) that tracks the valid next tokens, guaranteeing the final output is syntactically correct and parseable without post-processing.
Key Features of GBNF Grammar
GBNF (GGML BNF) is a formal grammar notation used by llama.cpp and related frameworks to define syntactical rules for constrained decoding. It ensures language model output strictly matches a specified format, such as JSON or a custom DSL.
Formal Syntax Definition
GBNF uses a Context-Free Grammar (CFG) notation to define all valid output strings. Rules are expressed as recursive production rules, providing a strict syntactic contract for the model.
- Root Rule: Every grammar starts with a
rootrule defining the top-level structure. - Terminals: Literal strings and character ranges (e.g.,
[a-z]) define valid tokens. - Non-Terminals: Named rules (e.g.,
json-object) allow recursive composition. - Alternation: The pipe
|operator defines logical OR branches for valid sequences.
Token-Level Enforcement
During decoding, the GBNF grammar is compiled into a Finite State Machine (FSM). At each step, the FSM calculates the set of permissible next tokens and applies a token mask.
- Logit Bias: The probabilities of all invalid tokens are set to negative infinity.
- Guaranteed Validity: The model is physically prevented from sampling an out-of-schema token.
- Zero Overhead: Masking happens natively in the C++ inference engine for minimal latency impact.
JSON Schema Compliance
GBNF is the primary mechanism for forcing JSON output in local inference engines. A grammar can precisely define the structure, required keys, and data types of a JSON object.
- Type Safety: Enforce
string,number,boolean, andnulltypes. - Required Fields: Define mandatory keys within an object.
- Array Constraints: Specify the element type and cardinality of arrays.
- Example: A grammar can enforce the exact
{ "name": string, "age": integer }schema.
Domain-Specific Languages
Beyond JSON, GBNF enables the creation of custom Domain-Specific Languages (DSLs) for specialized agent outputs. This allows for more token-efficient and parseable formats.
- ReAct Format: Enforce the
Thought: ... Action: ...structure for agentic loops. - Code Generation: Constrain output to a specific programming language syntax.
- Tool Calling: Define a precise grammar for function names and arguments.
- Efficiency: Custom DSLs often require fewer tokens than equivalent JSON.
Integration with llama.cpp
GBNF is a core feature of the llama.cpp inference engine, making structured output accessible on consumer hardware. The grammar is passed as a string parameter to the API.
- Server API: Use the
grammarfield in the/completionendpoint. - Offline Usage: Pass the grammar string directly to the
llama_eval()function. - Grammar Caching: Compiled FSMs are cached to avoid re-parsing on subsequent calls.
- Compatibility: Works with all GGUF-quantized models supported by the runtime.
Comparison to JSON Schema
While JSON Schema defines the what (the data contract), GBNF defines the how (the token-level path to get there). GBNF is a lower-level, more deterministic mechanism.
- JSON Schema: Validates output after generation. Relies on model instruction-following.
- GBNF: Physically constrains generation during decoding. Guarantees syntactic validity.
- Combined Approach: Use a library to compile a JSON Schema into a GBNF grammar for the strongest guarantee.
- Trade-off: GBNF is rigid; it cannot gracefully recover from a semantic error mid-stream.
GBNF Grammar vs. Other Structuring Methods
A feature-level comparison of GBNF Grammar against JSON Schema, Function Calling, and Token Masking for constraining language model output to valid, parseable formats.
| Feature | GBNF Grammar | JSON Schema | Function Calling | Token Masking |
|---|---|---|---|---|
Constraint Mechanism | Context-Free Grammar rules | JSON structure definition | API tool definition | Per-token logit modification |
Guarantees Syntactic Validity | ||||
Supports Non-JSON Formats | ||||
Requires Post-Processing | ||||
Schema Complexity Support | Arbitrary CFG rules | Nested objects, arrays, enums | Flat parameter lists | Simple token sequences |
Runtime Overhead | Low (FSM-based) | Medium (validation step) | Medium (API round-trip) | Low (logit bias) |
Framework Dependency | llama.cpp, llama-cpp-python | OpenAI, LangChain, Instructor | OpenAI, Anthropic, Cohere | Custom inference code |
Whitespace and Formatting Control | Exact character-level | Schema-agnostic | Model-dependent | Token-level only |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Frequently Asked Questions
Clear, technical answers to the most common questions about GBNF grammar, its role in constrained decoding, and how it compares to other structured output techniques.
GBNF (GGML BNF) is a formal grammar notation used by the llama.cpp inference framework to define syntactical rules for constrained decoding. It works by compiling a set of production rules into a finite state machine (FSM) that tracks the valid state of an output sequence. At each generation step, the FSM determines the set of permissible next tokens, and a token mask is applied to the model's logits, setting the probability of all invalid tokens to zero. This physically prevents the language model from generating text that violates the defined grammar, guaranteeing that the final output is syntactically valid according to the specified rules. GBNF is an extension of the standard Backus-Naur Form (BNF), adapted to handle the token-level constraints of large language models.
Related Terms
Mastering GBNF grammar requires understanding the broader landscape of formal languages, validation techniques, and decoding strategies that ensure deterministic, schema-compliant output from large language models.
Finite State Machine (FSM)
The computational engine that executes a GBNF grammar. During generation, a Finite State Machine is compiled from the grammar rules. Each state represents a valid point in the output sequence. The FSM tracks the current state and provides the set of permissible next tokens. As each token is generated, the FSM transitions to a new state, ensuring every step remains syntactically valid according to the defined grammar.
Schema Validation
The post-generation verification step. Even with a perfect GBNF grammar, schema validation is a critical defense-in-depth measure. It acts as a final gatekeeper, programmatically verifying that the generated data structure strictly conforms to the expected schema. This catches any edge cases where the grammar might be syntactically correct but semantically invalid, ensuring absolute data integrity before the output is consumed by downstream systems.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us