Skip to main content

Grammars (GBNF)

GBNF (GGML BNF) allows you to define formal grammars to constrain model outputs in llama.cpp.

What is GBNF?

GBNF is an extension of Backus-Naur Form (BNF) with regex-like features for defining syntax rules. Use cases:
  • Force valid JSON output
  • Generate code in specific languages
  • Ensure structured responses (chess notation, math equations)
  • Constrain outputs to specific formats (dates, emails, URLs)
  • Create domain-specific languages

Quick Start

Use Built-in Grammars

llama.cpp includes example grammars in the grammars/ directory:

JSON Schema

Generate grammar from JSON schema:
Or use the online tool: grammar.intrinsiclabs.ai

GBNF Syntax

Basic Structure

GBNF defines production rules that specify how non-terminals (rule names) can be replaced with sequences of terminals (characters) and other non-terminals:

Simple Example

This grammar matches: “Hello, Alice!”, “Hello, Bob!”, etc.

Chess Notation Example

From grammars/chess.gbnf:

Core Concepts

Non-Terminals

Rule names (must be lowercase with dashes):

Terminals

Actual characters or character ranges:

Character Escapes

Negation

Operators

Repetition

Alternatives

Grouping

Advanced Features

Token Matching

Match specific tokenizer tokens (useful for special tokens):
Example:

Comments

Practical Examples

Email Addresses

Phone Numbers

JSON Object

Simplified JSON grammar:

Markdown Headers

Python Function Definition

Usage Examples

CLI

Server API

Python Example

Best Practices

  • Begin with basic grammars and test thoroughly
  • Add complexity incrementally
  • Use comments to document rules
  • Test with various prompts
  • Minimize backtracking with specific rules
  • Use character classes instead of many alternatives
  • Avoid deeply nested optional groups
  • Consider grammar complexity vs. model capability
  • Test with empty inputs
  • Verify Unicode character handling
  • Check escape sequences
  • Validate against malformed inputs
  • Use grammars/json.gbnf as a base
  • Or generate from JSON Schema for complex types
  • Validate output with JSON parser
  • Handle optional fields correctly

Available Built-in Grammars

llama.cpp includes these grammars in grammars/:
  • json.gbnf — Valid JSON objects
  • json_arr.gbnf — JSON arrays
  • chess.gbnf — Chess move notation
  • arithmetic.gbnf — Mathematical expressions
  • c.gbnf — C-like code
  • japanese.gbnf — Japanese text patterns
  • list.gbnf — Bulleted lists

Tools

Grammar Generator:
  • Online: grammar.intrinsiclabs.ai
  • Python: examples/json_schema_to_grammar.py
  • Pydantic: examples/pydantic_models_to_grammar.py
Testing:
  • Test grammar locally before deployment
  • Use simple prompts for validation
  • Verify edge cases

Troubleshooting

  • Check for syntax errors in grammar
  • Ensure file path is correct
  • Verify grammar allows what you expect
  • Test with simpler grammar first
  • Grammar may be too restrictive
  • Model struggling to match constraints
  • Try more lenient grammar
  • Increase temperature for flexibility
  • Grammar may have bugs (test separately)
  • Check for missing rules or alternatives
  • Verify all paths lead to valid output

Next Steps

JSON Schema

Generate grammars from JSON schemas

CLI Usage

Use grammars with llama-cli

Server API

Apply grammars in API requests

Function Calling

Combine with function calling