Skip to content

Grammar

Namespace: LLama.Grammars

A grammar is a set of GrammarRules for deciding which characters are valid next. Can be used to constrain output to certain formats - e.g. force the model to output JSON

1
public sealed class Grammar

Inheritance ObjectGrammar

Properties

StartRuleIndex

Index of the initial rule to start from

1
public ulong StartRuleIndex { get; }

Property Value

UInt64

Rules

The rules which make up this grammar

1
public IReadOnlyList<GrammarRule> Rules { get; }

Property Value

IReadOnlyList<GrammarRule>

Constructors

Grammar(IReadOnlyList<GrammarRule>, UInt64)

Create a new grammar from a set of rules

1
public Grammar(IReadOnlyList<GrammarRule> rules, ulong startRuleIndex)

Parameters

rules IReadOnlyList<GrammarRule>
The rules which make up this grammar

startRuleIndex UInt64
Index of the initial rule to start from

Exceptions

ArgumentOutOfRangeException

Methods

CreateInstance()

Create a SafeLLamaGrammarHandle instance to use for parsing

1
public SafeLLamaGrammarHandle CreateInstance()

Returns

SafeLLamaGrammarHandle

Parse(String, String)

Parse a string of GGML BNF into a Grammar

1
public static Grammar Parse(string gbnf, string startRule)

Parameters

gbnf String
The string to parse

startRule String
Name of the start rule of this grammar

Returns

Grammar
A Grammar which can be converted into a SafeLLamaGrammarHandle for sampling

Exceptions

GrammarFormatException
Thrown if input is malformed

ToString()

1
public string ToString()

Returns

String