A grammar is a set of rules specifying how the model should format its output. On Backyard AI, you can add a BNF grammar to your character to ensure that it responds with a very specific structure.
Grammars are written in the Backus-Naur Format (BNF).
::=
Assigns an expression. E.g., number ::= (0,1,2,3,4,5,6,7,8,9)
.*
0 or more occurrences of the previous item. E.g., ("x")*
outputs 0 or more X's.+
1 or more occurrences. E.g., ("x")+
outputs 1 or more X's.?
0 or 1 occurrence. Can be replaced by [...]
.[...]
Anything in brackets is optional. E.g., [-] "1"
outputs 1 or -1.x | y
A choice between items. ("+" | "-")
outputs + or -.(...)
Groups items. In (a | b) + c
, you get a or b, then c.^...
Anything but the following. [^\r\n]*
outputs any character except return or enter."..."
Outputs text directly."\n"
Special characters in quotes.root
Every grammar must start with a root expression. Also note that expression names cannot be capitalized.[...]*
or [...]+
can lead to stall-outs because the LLM needs to apply multiple layers of grammar calculations, rather than just one. Ideally, you want to give any +
or *
statement an "exit condition", such that each one has a distinct end. For instance ["X"]+ "\n"
will produce X’s until the model chooses to generate a new line, and then that statement is done.The quotation mark is a part of the BNF grammar syntax. As such, to output a quotation mark, you may need to write it as \"
to tell the grammar that it is a character. This is not required inside a bracket statement, as they are character-based and quotations cannot function within them.
Basic grammar to always write three paragraphs.
root ::= text text text ("<" | "#")
text ::= [^\r\n#]+ "\n"
Example Roleplay with three characters.
root ::= action character (character)? (action)?
action ::= "_" [^ ] dialogue "_ "
dialogue ::= [^<\n*#]+
character ::= "\n--" ("Cassandra" | "Tessa" | "Britney") ": " (action)? dialogue
Sample Stable Diffusion prompt format.
root ::= combo [combo] combo [combo]\*
object ::= [a-zA-Z" "]+
weight ::= [0-1] "." [0-9] [0-9]
combo ::= ["("]? object [":" weight ") "]?