char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
acecd5603
char/aliceai-t5-moe
Parsing Model Output
The common library contains a PEG parser implementation suitable for parsing
model output.
Types with the prefix common_peg_* are intended for general use and may have
applications beyond parsing model output, such as parsing user-provided regex
patterns.
Types with the prefix common_chat_peg_* are specialized helpers for model
output.
The parser features:
- Partial parsing of streaming input
- Built-in JSON parsers
- AST generation with semantics via "tagged" nodes
Example
Below is a contrived example demonstrating how to use the PEG parser to parse output from a model that emits arguments as JSON.
auto parser = build_chat_peg_parser ([& ](common_chat_peg_builder & p ) {// Build a choice of all available tools auto tool_choice = p .choice ();for (const auto & tool :tools ) {const auto & function = tool .at ("function" ); std::string name = function .at ("name" );const auto schema = common_chat_tool_parameters (function );auto tool_name = p .json_member ("name" ,"\"" + p .literal (name )+ "\"" );auto tool_args = p .json_member ("arguments" ,p .schema (p .json (),"tool-" + name + "-schema" ,schema ));tool_choice |=p .rule ("tool-" + name ,"{" <<tool_name <<"," <<tool_args <<"}" ); }// Define the tool call structure: <tool_call>[{tool}]</tool_call> auto tool_call = p .trigger_rule ("tool-call" ,p .sequence ({p .literal ("<tool_call>[" ),tool_choice ,p .literal ("]</tool_call>" ) }) );// Parser accepts content, optionally followed by a tool call return p .sequence ({p .content (p .until ("<tool_call>" )),p .optional (tool_call ),p .end () }); });
For a more complete example, see test_example_native() in
tests/test-chat-peg-parser.cpp.
Parsers/Combinators
Basic Matchers
eps()- Matches nothing and always succeeds (epsilon/empty match)start()- Matches the start of input (anchor^)end()- Matches the end of input (anchor$)literal(string)- Matches an exact literal stringany()- Matches any single character (.)
Combinators
sequence(...)- Matches parsers in order; all must succeedchoice(...)- Matches the first parser that succeeds from alternatives (ordered choice)one_or_more(p)- Matches one or more repetitions (+)zero_or_more(p)- Matches zero or more repetitions (*)optional(p)- Matches zero or one occurrence (?)repeat(p, min, max)- Matches between min and max repetitions (use-1for unbounded)repeat(p, n)- Matches exactly n repetitions
Lookahead
peek(p)- Positive lookahead: succeeds if parser succeeds without consuming input (&)negate(p)- Negative lookahead: succeeds if parser fails without consuming input (!)
Character Classes & Utilities
chars(classes, min, max)- Matches repetitions of characters from a character classspace()- Matches zero or more whitespace characters (space, tab, newline)until(delimiter)- Matches characters until delimiter is found (delimiter not consumed)until_one_of(delimiters)- Matches characters until any delimiter in the list is foundrest()- Matches everything remaining (.*)
JSON Parsers
json()- Complete JSON parser (objects, arrays, strings, numbers, booleans, null)json_object()- JSON object parserjson_array()- JSON array parserjson_string()- JSON string parserjson_number()- JSON number parserjson_bool()- JSON boolean parserjson_null()- JSON null parserjson_string_content()- JSON string content without surrounding quotesjson_member(key, p)- JSON object member with specific key and value parser
Grammar Building
ref(name)- Creates a lightweight reference to a named rule (for recursive grammars)rule(name, p, trigger)- Creates a named rule and returns a referencetrigger_rule(name, p)- Creates a trigger rule (entry point for lazy grammar generation)schema(p, name, schema, raw)- Wraps parser with JSON schema metadata for grammar generationschema(p, name, doc, node, raw)- Same, for a node of acommon_chat_schema_documentbuilt earlier, e.g. one tool parameter
AST Control
atomic(p)- Prevents AST node creation for partial parsestag(tag, p)- Creates AST nodes with semantic tags (multiple nodes can share tags)
GBNF Grammar Generation
The PEG parser also acts as a convenient DSL for generating GBNF grammars, with some exceptions.
data .grammar = build_grammar ([& ](const common_grammar_builder & builder ) {parser .build_grammar (builder ,data .grammar_lazy ); });
The notable exception is the negate(p) lookahead parser, which cannot be
defined as a CFG grammar and therefore does not produce a rule. Its usage
should be limited and preferably hidden behind a schema() parser. In many
cases, until(delimiter) or until_one_of(delimiters) is a better choice.
Another limitation is that the PEG parser requires an unambiguous grammar. In
contrast, the llama-grammar implementation can support ambiguous grammars,
though they are difficult to parse.
Lazy Grammars
During lazy grammar generation, only rules reachable from a trigger_rule(p)
are emitted in the grammar. All trigger rules are added as alternations in the
root rule. It is still necessary to define trigger patterns, as the parser has
no interaction with the grammar sampling.
JSON Schema
The schema(p, name, schema, raw) parser will use the json-schema-to-grammar
implementation to generate the grammar instead of the underlying parser.
The raw option emits a grammar suitable for a raw string instead of a JSON
string. In other words, it won't be wrapped in quotes or require escaping
quotes. It only takes effect when the schema may be a string, as reported by
common_chat_schema::may_be_string(), otherwise the JSON grammar is used.
The downside is that it can potentially lead to ambiguous grammars. For
example, if a user provides the pattern ^.*$, the following grammar may be
generated:
root ::= "<arg>" .* "</arg>"
This creates an ambiguous grammar that cannot be parsed by the PEG parser. To
help mitigate this, if .* is found in the pattern, the grammar from the
underlying parser will be emitted instead.
Common AST Shapes for Chat Parsing
Most model output can be placed in one of the following categories:
- Content only
- Tool calling with arguments emitted as a single JSON object
- Tool calling with arguments emitted as separate entities, either XML (Qwen3-Coder, MiniMax M2) or pseudo-function calls (LFM2)
To provide broad coverage,
common/chat-peg-parser.h contains builders and
mappers that help create parsers and visitors/extractors for these types. They
require parsers to tag nodes to conform to an AST "shape". This normalization
makes it easy to extract information and generalize parsing.
Simple
The common_chat_peg_builder builds a simple parser that supports
content-only models with optional reasoning.
reasoning(p)- Tag node for extractingreasoning_contentcontent(p)- Tag node for extractingcontent
build_chat_peg_parser ([& ](common_chat_peg_parser & p ) {return p .sequence ({p .optional ("<think>" + p .reasoning (p .until ("</think>" ))+ "</think>" ),p .content (p .until ("<tool_call>" )),p .end () }); });
Use common_chat_peg_mapper to extract the content. Note that this is already
done for you in common_chat_peg_parser when
chat_format == COMMON_CHAT_FORMAT_PEG_SIMPLE.
auto result = parser .parse (ctx );common_chat_msg msg ;auto mapper = common_chat_peg_mapper (msg );mapper .from_ast (ctx .ast ,result );
Native
The common_chat_peg_builder builds a native parser suitable for
models that emit tool arguments as a direct JSON object.
reasoning(p)- Tag node forreasoning_contentcontent(p)- Tag node forcontenttool(p)- Tag entirety of a single tool calltool_open(p)- Tag start of a tool calltool_close(p)- Tag end of a tool calltool_id(p)- Tag the tool call ID (optional)tool_name(p)- Tag the tool nametool_args(p)- Tag the tool arguments
build_chat_peg_parser ([& ](common_chat_peg_builder & p ) {auto get_weather_tool = p .tool (p .sequence ({p .tool_open (p .literal ("{" )),p .json_member ("name" ,"\"" + p .tool_name (p .literal ("get_weather" ))+ "\"" ),p .literal ("," ),p .json_member ("arguments" ,p .tool_args (p .json ())),p .tool_close (p .literal ("}" )) }));return p .sequence ({p .content (p .until ("<tool_call>" )),p .literal ("<tool_call>" ),get_weather_tool ,p .literal ("</tool_call>" ),p .end () }); });
Constructed
The common_chat_peg_builder builds a constructed parser
suitable for models that emit tool arguments as separate entities, such as XML
tags.
reasoning(p)- Tag node forreasoning_contentcontent(p)- Tag node forcontenttool(p)- Tag entirety of a single tool calltool_open(p)- Tag start of a tool calltool_close(p)- Tag end of a tool calltool_name(p)- Tag the tool nametool_arg(p)- Tag a complete tool argument (name + value)tool_arg_open(p)- Tag start of a tool argumenttool_arg_close(p)- Tag end of a tool argumenttool_arg_name(p)- Tag the argument nametool_arg_string_value(p)- Tag string value for the argumenttool_arg_json_value(p)- Tag JSON value for the argument
build_chat_peg_parser ([& ](common_chat_peg_builder & p ) {auto location_arg = p .tool_arg (p .tool_arg_open ("<parameter name=\"" + p .tool_arg_name (p .literal ("location" ))+ "\">" ),p .tool_arg_string_value (p .until ("</parameter>" )),p .tool_arg_close (p .literal ("</parameter>" )) );auto get_weather_tool = p .tool (p .sequence ({p .tool_open ("<function name=\"" + p .tool_name (p .literal ("get_weather" ))+ "\">" ),location_arg ,p .tool_close (p .literal ("</function>" )) }));return p .sequence ({p .content (p .until ("<tool_call>" )),p .literal ("<tool_call>" ),get_weather_tool ,p .literal ("</tool_call>" ),p .end () }); });
1# Parsing Model Output 2 3The `common` library contains a PEG parser implementation suitable for parsing 4model output. 5 6Types with the prefix `common_peg_*` are intended for general use and may have 7applications beyond parsing model output, such as parsing user-provided regex 8patterns. 9 10Types with the prefix `common_chat_peg_*` are specialized helpers for model 11output. 12 13The parser features: 14 15- Partial parsing of streaming input 16- Built-in JSON parsers 17- AST generation with semantics via "tagged" nodes 18 19## Example 20 21Below is a contrived example demonstrating how to use the PEG parser to parse 22output from a model that emits arguments as JSON. 23 24``` cpp 25auto parser = build_chat_peg_parser ([ & ]( common_chat_peg_builder & p ) { 26// Build a choice of all available tools 27auto tool_choice = p . choice (); 28for ( const auto & tool : tools ) { 29const auto & function = tool . at ( "function" ); 30std:: string name = function . at ( "name" ); 31const auto schema = common_chat_tool_parameters ( function ); 32 33auto tool_name = p . json_member ( "name" , "\"" + p . literal ( name ) + "\"" ); 34auto tool_args = p . json_member ( "arguments" , p . schema ( p . json (), "tool-" + name + "-schema" , schema )); 35 36tool_choice |= p . rule ( "tool-" + name , "{" << tool_name << "," << tool_args << "}" ); 37} 38 39// Define the tool call structure: <tool_call>[{tool}]</tool_call> 40auto tool_call = p . trigger_rule ( "tool-call" , 41p . sequence ({ 42p . literal ( "<tool_call>[" ), 43tool_choice , 44p . literal ( "]</tool_call>" ) 45}) 46); 47 48// Parser accepts content, optionally followed by a tool call 49return p . sequence ({ 50p . content ( p . until ( "<tool_call>" )), 51p . optional ( tool_call ), 52p . end () 53}); 54}); 55``` 56 57For a more complete example, see `test_example_native()` in 58[tests/test-chat-peg-parser.cpp](/tests/test-chat-peg-parser.cpp). 59 60## Parsers/Combinators 61 62### Basic Matchers 63 64- **`eps()`** - Matches nothing and always succeeds (epsilon/empty match) 65- **`start()`** - Matches the start of input (anchor `^`) 66- **`end()`** - Matches the end of input (anchor `$`) 67- **`literal(string)`** - Matches an exact literal string 68- **`any()`** - Matches any single character (`.`) 69 70### Combinators 71 72- **`sequence(...)`** - Matches parsers in order; all must succeed 73- **`choice(...)`** - Matches the first parser that succeeds from alternatives (ordered choice) 74- **`one_or_more(p)`** - Matches one or more repetitions (`+`) 75- **`zero_or_more(p)`** - Matches zero or more repetitions (`*`) 76- **`optional(p)`** - Matches zero or one occurrence (`?`) 77- **`repeat(p, min, max)`** - Matches between min and max repetitions (use `-1` for unbounded) 78- **`repeat(p, n)`** - Matches exactly n repetitions 79 80### Lookahead 81 82- **`peek(p)`** - Positive lookahead: succeeds if parser succeeds without consuming input (`&`) 83- **`negate(p)`** - Negative lookahead: succeeds if parser fails without consuming input (`!`) 84 85### Character Classes & Utilities 86 87- **`chars(classes, min, max)`** - Matches repetitions of characters from a character class 88- **`space()`** - Matches zero or more whitespace characters (space, tab, newline) 89- **`until(delimiter)`** - Matches characters until delimiter is found (delimiter not consumed) 90- **`until_one_of(delimiters)`** - Matches characters until any delimiter in the list is found 91- **`rest()`** - Matches everything remaining (`.*`) 92 93### JSON Parsers 94 95- **`json()`** - Complete JSON parser (objects, arrays, strings, numbers, booleans, null) 96- **`json_object()`** - JSON object parser 97- **`json_array()`** - JSON array parser 98- **`json_string()`** - JSON string parser 99- **`json_number()`** - JSON number parser 100- **`json_bool()`** - JSON boolean parser 101- **`json_null()`** - JSON null parser 102- **`json_string_content()`** - JSON string content without surrounding quotes 103- **`json_member(key, p)`** - JSON object member with specific key and value parser 104 105### Grammar Building 106 107- **`ref(name)`** - Creates a lightweight reference to a named rule (for recursive grammars) 108- **`rule(name, p, trigger)`** - Creates a named rule and returns a reference 109- **`trigger_rule(name, p)`** - Creates a trigger rule (entry point for lazy grammar generation) 110- **`schema(p, name, schema, raw)`** - Wraps parser with JSON schema metadata for grammar generation 111- **`schema(p, name, doc, node, raw)`** - Same, for a node of a `common_chat_schema_document` built earlier, e.g. one tool parameter 112 113### AST Control 114 115- **`atomic(p)`** - Prevents AST node creation for partial parses 116- **`tag(tag, p)`** - Creates AST nodes with semantic tags (multiple nodes can share tags) 117 118## GBNF Grammar Generation 119 120The PEG parser also acts as a convenient DSL for generating GBNF grammars, with 121some exceptions. 122 123``` cpp 124data. grammar = build_grammar ([ & ]( const common_grammar_builder & builder ) { 125parser . build_grammar ( builder , data . grammar_lazy ); 126}); 127``` 128 129The notable exception is the `negate(p)` lookahead parser, which cannot be 130defined as a CFG grammar and therefore does not produce a rule. Its usage 131should be limited and preferably hidden behind a `schema()` parser. In many 132cases, `until(delimiter)` or `until_one_of(delimiters)` is a better choice. 133 134Another limitation is that the PEG parser requires an unambiguous grammar. In 135contrast, the `llama-grammar` implementation can support ambiguous grammars, 136though they are difficult to parse. 137 138### Lazy Grammars 139 140During lazy grammar generation, only rules reachable from a `trigger_rule(p)` 141are emitted in the grammar. All trigger rules are added as alternations in the 142root rule. It is still necessary to define trigger patterns, as the parser has 143no interaction with the grammar sampling. 144 145### JSON Schema 146 147The `schema(p, name, schema, raw)` parser will use the `json-schema-to-grammar` 148implementation to generate the grammar instead of the underlying parser. 149 150The `raw` option emits a grammar suitable for a raw string instead of a JSON 151string. In other words, it won't be wrapped in quotes or require escaping 152quotes. It only takes effect when the schema may be a string, as reported by 153`common_chat_schema::may_be_string()`, otherwise the JSON grammar is used. 154 155The downside is that it can potentially lead to ambiguous grammars. For 156example, if a user provides the pattern `^.*$`, the following grammar may be 157generated: 158 159``` 160root ::= "<arg>" .* "</arg>" 161``` 162 163This creates an ambiguous grammar that cannot be parsed by the PEG parser. To 164help mitigate this, if `.*` is found in the pattern, the grammar from the 165underlying parser will be emitted instead. 166 167## Common AST Shapes for Chat Parsing 168 169Most model output can be placed in one of the following categories: 170 171- Content only 172- Tool calling with arguments emitted as a single JSON object 173- Tool calling with arguments emitted as separate entities, either XML 174(Qwen3-Coder, MiniMax M2) or pseudo-function calls (LFM2) 175 176To provide broad coverage, 177[`common/chat-peg-parser.h`](/common/chat-peg-parser.h) contains builders and 178mappers that help create parsers and visitors/extractors for these types. They 179require parsers to tag nodes to conform to an AST "shape". This normalization 180makes it easy to extract information and generalize parsing. 181 182### Simple 183 184The `common_chat_peg_builder` builds a `simple` parser that supports 185content-only models with optional reasoning. 186 187- **`reasoning(p)`** - Tag node for extracting `reasoning_content` 188- **`content(p)`** - Tag node for extracting `content` 189 190``` cpp 191build_chat_peg_parser([ & ]( common_chat_peg_parser & p ) { 192return p . sequence ({ 193p . optional ( "<think>" + p . reasoning ( p . until ( "</think>" )) + "</think>" ), 194p . content ( p . until ( "<tool_call>" )), 195p . end () 196}); 197}); 198``` 199 200Use `common_chat_peg_mapper` to extract the content. Note that this is already 201done for you in `common_chat_peg_parser` when 202`chat_format == COMMON_CHAT_FORMAT_PEG_SIMPLE`. 203 204``` cpp 205auto result = parser . parse ( ctx ); 206 207common_chat_msg msg ; 208auto mapper = common_chat_peg_mapper ( msg ); 209mapper. from_ast ( ctx . ast , result ); 210``` 211 212### Native 213 214The `common_chat_peg_builder` builds a `native` parser suitable for 215models that emit tool arguments as a direct JSON object. 216 217- **`reasoning(p)`** - Tag node for `reasoning_content` 218- **`content(p)`** - Tag node for `content` 219- **`tool(p)`** - Tag entirety of a single tool call 220- **`tool_open(p)`** - Tag start of a tool call 221- **`tool_close(p)`** - Tag end of a tool call 222- **`tool_id(p)`** - Tag the tool call ID (optional) 223- **`tool_name(p)`** - Tag the tool name 224- **`tool_args(p)`** - Tag the tool arguments 225 226``` cpp 227build_chat_peg_parser([ & ]( common_chat_peg_builder & p ) { 228auto get_weather_tool = p . tool ( p . sequence ({ 229p . tool_open ( p . literal ( "{" )), 230p . json_member ( "name" , "\"" + p . tool_name ( p . literal ( "get_weather" )) + "\"" ), 231p . literal ( "," ), 232p . json_member ( "arguments" , p . tool_args ( p . json ())), 233p . tool_close ( p . literal ( "}" )) 234})); 235 236return p . sequence ({ 237p . content ( p . until ( "<tool_call>" )), 238p . literal ( "<tool_call>" ), 239get_weather_tool , 240p . literal ( "</tool_call>" ), 241p . end () 242}); 243}); 244``` 245 246### Constructed 247 248The `common_chat_peg_builder` builds a `constructed` parser 249suitable for models that emit tool arguments as separate entities, such as XML 250tags. 251 252- **`reasoning(p)`** - Tag node for `reasoning_content` 253- **`content(p)`** - Tag node for `content` 254- **`tool(p)`** - Tag entirety of a single tool call 255- **`tool_open(p)`** - Tag start of a tool call 256- **`tool_close(p)`** - Tag end of a tool call 257- **`tool_name(p)`** - Tag the tool name 258- **`tool_arg(p)`** - Tag a complete tool argument (name + value) 259- **`tool_arg_open(p)`** - Tag start of a tool argument 260- **`tool_arg_close(p)`** - Tag end of a tool argument 261- **`tool_arg_name(p)`** - Tag the argument name 262- **`tool_arg_string_value(p)`** - Tag string value for the argument 263- **`tool_arg_json_value(p)`** - Tag JSON value for the argument 264 265``` cpp 266build_chat_peg_parser([ & ]( common_chat_peg_builder & p ) { 267auto location_arg = p . tool_arg ( 268p . tool_arg_open ( "<parameter name=\"" + p . tool_arg_name ( p . literal ( "location" )) + "\">" ), 269p . tool_arg_string_value ( p . until ( "</parameter>" )), 270p . tool_arg_close ( p . literal ( "</parameter>" )) 271); 272 273auto get_weather_tool = p . tool ( p . sequence ({ 274p . tool_open ( "<function name=\"" + p . tool_name ( p . literal ( "get_weather" )) + "\">" ), 275location_arg , 276p . tool_close ( p . literal ( "</function>" )) 277})); 278 279return p . sequence ({ 280p . content ( p . until ( "<tool_call>" )), 281p . literal ( "<tool_call>" ), 282get_weather_tool , 283p . literal ( "</tool_call>" ), 284p . end () 285}); 286}); 287```