|
|
8 luni în urmă | |
|---|---|---|
| .. | ||
| README.md | 8 luni în urmă | |
| arithmetic.gbnf | 2 ani în urmă | |
| c.gbnf | 2 ani în urmă | |
| chess.gbnf | 2 ani în urmă | |
| english.gbnf | 1 an în urmă | |
| japanese.gbnf | 2 ani în urmă | |
| json.gbnf | 1 an în urmă | |
| json_arr.gbnf | 1 an în urmă | |
| list.gbnf | 2 ani în urmă | |
GBNF (GGML BNF) is a format for defining formal grammars to constrain model outputs in llama.cpp. For example, you can use it to force the model to generate valid JSON, or speak only in emojis. GBNF grammars are supported in various ways in tools/main and tools/server.
Backus-Naur Form (BNF) is a notation for describing the syntax of formal languages like programming languages, file formats, and protocols. GBNF is an extension of BNF that primarily adds a few modern regex-like features.
In GBNF, we define production rules that specify how a non-terminal (rule name) can be replaced with sequences of terminals (characters, specifically Unicode code points) and other non-terminals. The basic format of a production rule is nonterminal ::= sequence....
Before going deeper, let's look at some of the features demonstrated in grammars/chess.gbnf, a small chess notation grammar:
# `root` specifies the pattern for the overall output
root ::= (
# it must start with the characters "1. " followed by a sequence
# of characters that match the `move` rule, followed by a space, followed
# by another move, and then a newline
"1. " move " " move "\n"
# it's followed by one or more subsequent moves, numbered with one or two digits
([1-9] [0-9]? ". " move " " move "\n")+
)
# `move` is an abstract representation, which can be a pawn, nonpawn, or castle.
# The `[+#]?` denotes the possibility of checking or mate signs after moves
move ::= (pawn | nonpawn | castle) [+#]?
pawn ::= ...
nonpawn ::= ...
castle ::= ...
Non-terminal symbols (rule names) stand for a pattern of terminals and other non-terminals. They are required to be a dashed lowercase word, like move, castle, or check-mate.
Terminals are actual characters (code points). They can be specified as a sequence like "1" or "O-O" or as ranges like [1-9] or [NBKQR].
Terminals support the full range of Unicode. Unicode characters can be specified directly in the grammar, for example hiragana ::= [ぁ-ゟ], or with escapes: 8-bit (\xXX), 16-bit (\uXXXX) or 32-bit (\UXXXXXXXX).
Character ranges can be negated with ^:
single-line ::= [^\n]+ "\n"
The order of symbols in a sequence matters. For example, in "1. " move " " move "\n", the "1. " must come before the first move, etc.
Alternatives, denoted by |, give different sequences that are acceptable. For example, in move ::= pawn | nonpawn | castle, move can be a pawn move, a nonpawn move, or a castle.
Parentheses () can be used to group sequences, which allows for embedding alternatives in a larger rule or applying repetition and optional symbols (below) to a sequence.
* after a symbol or sequence means that it can be repeated zero or more times (equivalent to {0,}).+ denotes that the symbol or sequence should appear one or more times (equivalent to {1,}).? makes the preceding symbol or sequence optional (equivalent to {0,1}).{m} repeats the precedent symbol or sequence exactly m times{m,} repeats the precedent symbol or sequence at least m times{m,n} repeats the precedent symbol or sequence at between m and n times (included){0,n} repeats the precedent symbol or sequence at most n times (included)Comments can be specified with #:
# defines optional whitespace
ws ::= [ \t\n]+
Newlines are allowed between rules and between symbols or sequences nested inside parentheses. Additionally, a newline after an alternate marker | will continue the current rule, even outside of parentheses.
In a full grammar, the root rule always defines the starting point of the grammar. In other words, it specifies what the entire output must match.
# a grammar for lists
root ::= ("- " item)+
item ::= [^\n]+ "\n"
This guide provides a brief overview. Check out the GBNF files in this directory (grammars/) for examples of full grammars. You can try them out with:
./llama-cli -m <model> --grammar-file grammars/some-grammar.gbnf -p 'Some prompt'
llama.cpp can also convert JSON schemas to grammars either ahead of time or at each request, see below.
Grammars currently have performance gotchas (see https://github.com/ggml-org/llama.cpp/issues/4218).
A common pattern is to allow repetitions of a pattern x up to N times.
While semantically correct, the syntax x? x? x?.... x? (with N repetitions) may result in extremely slow sampling. Instead, you can write x{0,N} (or (x (x (x ... (x)?...)?)?)? w/ N-deep nesting in earlier llama.cpp versions).
You can use GBNF grammars:
grammar body field--grammar & --grammar-file flagsllama.cpp supports converting a subset of https://json-schema.org/ to GBNF grammars:
json_schema body field/chat/completions endpoint, passed inside the response_format body field (e.g. {"type", "json_object", "schema": {"items": {}}} or { type: "json_schema", json_schema: {"schema": ...} })--json / -j flagTake a look at tests to see which features are likely supported (you'll also find usage examples in https://github.com/ggml-org/llama.cpp/pull/5978, https://github.com/ggml-org/llama.cpp/pull/6659 & https://github.com/ggml-org/llama.cpp/pull/6555).
llama-cli \
-hfr bartowski/Phi-3-medium-128k-instruct-GGUF \
-hff Phi-3-medium-128k-instruct-Q8_0.gguf \
-j '{
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 1,
"maxLength": 100
},
"age": {
"type": "integer",
"minimum": 0,
"maximum": 150
}
},
"required": ["name", "age"],
"additionalProperties": false
},
"minItems": 10,
"maxItems": 100
}' \
-p 'Generate a {name, age}[] JSON array with famous actors of all ages.'
Here is also a list of known limitations (contributions welcome):
additionalProperties defaults to false (produces faster grammars + reduces hallucinations)."additionalProperties": true may produce keys that contain unescaped newlines.properties w/ anyOf / oneOf in the same type (https://github.com/ggml-org/llama.cpp/issues/7703)minimum, exclusiveMinimum, maximum, exclusiveMaximum: only supported for "type": "integer" for now, not number$refs are broken (https://github.com/ggml-org/llama.cpp/issues/8073)^ and end with $$refs not supported in the C++ version (Python & JavaScript versions fetch https refs)string formats lack uri, emailpatternPropertiesAnd a non-exhaustive list of other unsupported features that are unlikely to be implemented (hard and/or too slow to support w/ stateless grammars):
uniqueItemscontains / minContains$anchor (cf. dereferencing)notif / then / else / dependentSchemas[!WARNING] The JSON schemas spec states
objects accept additional properties by default. Since this is slow and seems prone to hallucinations, we default to no additional properties. You can set"additionalProperties": truein the the schema of any object to explicitly allow additional properties.
If you're using Pydantic to generate schemas, you can enable additional properties with the extra config on each model class:
# pip install pydantic
import json
from typing import Annotated, List
from pydantic import BaseModel, Extra, Field
class QAPair(BaseModel):
class Config:
extra = 'allow' # triggers additionalProperties: true in the JSON schema
question: str
concise_answer: str
justification: str
class Summary(BaseModel):
class Config:
extra = 'allow'
key_facts: List[Annotated[str, Field(pattern='- .{5,}')]]
question_answers: List[Annotated[List[QAPair], Field(min_items=5)]]
print(json.dumps(Summary.model_json_schema(), indent=2))
If you're using Zod, you can make your objects to explicitly allow extra properties w/ nonstrict() / passthrough() (or explicitly no extra props w/ z.object(...).strict() or z.strictObject(...)) but note that zod-to-json-schema currently always sets "additionalProperties": false anyway.
import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';
const Foo = z.object({
age: z.number().positive(),
email: z.string().email(),
}).strict();
console.log(zodToJsonSchema(Foo));