mirror of
https://github.com/ikawrakow/ik_llama.cpp.git
synced 2026-05-22 21:48:30 +00:00
* Autoparser - complete refactoring of parser architecture Autoparser: add optional argument reshuffle capability Autoparser: True streaming (#20177) * Relax atomicity constraint for nicer, more pleasent, True Streaming parsing * Whitespace * Remove redundant atomics Revert to OAI-compatible args (#20213) * Revert to OAI-compatible args * Apply workaround::func_args_not_string Fix structured outputs (#20223) * Fix structured outputs * Update common/chat-auto-parser-generator.cpp Co-authored-by: Aldehir Rojas <hello@alde.dev> --------- Co-authored-by: Aldehir Rojas <hello@alde.dev> Fix compile bug (#20203) * Fix compile bug * Update common/chat-auto-parser-helpers.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> # Conflicts: # common/chat-auto-parser-helpers.cpp common : gracefully handle incomplete output (#20191) * common : handle incomplete UTF-8 at end of input in PEG parser * cont : if reached end prematurely, emit needs_more_input to propagate partial output * cont: refactor peg parse context to add lenient flag * cont : remove partial flag, keep lenient flag PEG parser for LFM2 (#20251) * PEG parser for LFM2 * Simplify using python_value() common: map developer role to system (#20215) * Map developer role to system * Simplify common: consolidate PEG string parsers (#20263) * common : consolidate PEG string parsers * cont : fix json_string_content() examples : fix empty items in json_schema_to_grammar.py [no ci] (#19968) * Fix logic for retrieving schema items in `json_schema_to_grammar.py` If `schema['items']` is `{}` and `prefixItems not in schema', as `{}` is Falsy, the original code here will raise an error. I think if `schema['items']` is `{}`, them items should just be `{}` * Apply suggestion from @CISC Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Add tests for arrays with empty items Add two unit tests to `tests/test-json-schema-to-grammar.cpp` that validate handling of arrays when 'items' is an empty schema and when 'prefixItems' is present alongside an empty 'items'. Both tests expect the same generated grammar, ensuring the JSON Schema->grammar conversion treats an empty 'items' schema (and the presence of 'prefixItems') correctly and covering this edge case. --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Reduce level of content parser warning message to avoid log spam on non-debug verbosity (#20347) do not return if template parse failed add arg to enable parallel tool call common : fix incorrect uses of stoul (#20313) # Conflicts: # common/arg.cpp # src/llama-grammar.cpp examples : fix empty items in json_schema_to_grammar.py [no ci] (#19968) * Fix logic for retrieving schema items in `json_schema_to_grammar.py` If `schema['items']` is `{}` and `prefixItems not in schema', as `{}` is Falsy, the original code here will raise an error. I think if `schema['items']` is `{}`, them items should just be `{}` * Apply suggestion from @CISC Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Add tests for arrays with empty items Add two unit tests to `tests/test-json-schema-to-grammar.cpp` that validate handling of arrays when 'items' is an empty schema and when 'prefixItems' is present alongside an empty 'items'. Both tests expect the same generated grammar, ensuring the JSON Schema->grammar conversion treats an empty 'items' schema (and the presence of 'prefixItems') correctly and covering this edge case. --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Add support for MiroThinker with new jinja template common/parser: handle reasoning budget (#20297) * v1 * Finished! * Handlie cli * Reasoning sampler * Apply suggestions from code review Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * Less explosive terminology :) * Add utf-8 case and tests * common : migrate reasoning budget sampler to common * cont : clean up * cont : expose state and allow passing as initial state * cont : remove unused imports * cont : update state machine doc string --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> Co-authored-by: Alde Rojas <hello@alde.dev> common/parser: use nlohmann::ordered_json to preserve parameter order (#20385) common/parser: add GigaChatV3/3.1 models support (#19931) Co-authored-by: Mishusha <pmv26021975@gmail.com> common/parser: gracefully handle undetected tool parser, print error message. (#20286) fix: prevent nullptr dereference (#20552) common : fix iterator::end() dereference (#20445) # Conflicts: # common/regex-partial.cpp jinja : add capability check for object args (#20612) common/parser: add `--skip-chat-parsing` to force a pure content parser. (#20289) * Add `--force-pure-content` to force a pure content parser. * Update common/arg.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : rework gpt-oss parser (#20393) * common : rework gpt-oss parser * cont : fix gpt-oss tests * cont : add structured output test * cont : rename final to final_msg common : fix gpt-oss content removal (#20745) common/parser: add proper reasoning tag prefill reading (#20424) * Implement proper prefill extraction * Refactor cli parameters, update docs, move reasoning budget sampler part to common/reasoning-budget.cpp * Update tools/server/server-task.cpp * refactor: move grammars to variant, remove grammar_external, handle exception internally * Make code less C++y Co-authored-by: Georgi Gerganov <ggerganov@gmail.com> chat : handle tool calls with no required args in TAG_WITH_TAGGED format (#20764) * chat : handle tool calls with no required args in TAG_WITH_TAGGED format * Update tests/test-chat.cpp [no ci] Co-authored-by: Aldehir Rojas <hello@alde.dev> --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> Co-authored-by: Aldehir Rojas <hello@alde.dev> common/parser : fix out_of_range crash in throw path (#20424 regression) (#20777) * chat : fix out_of_range crash in throw path (#20424 regression) #20424 introduced effective_input = generation_prompt + input, but the throw path uses input.substr(result.end) where result.end is a position within effective_input. Every thinking model with a non-empty generation_prompt crashes with std::out_of_range instead of the intended error message. Test crashes on unpatched master, passes with fix: cmake -B build -DLLAMA_BUILD_TESTS=ON -DLLAMA_BUILD_TOOLS=OFF cmake --build build --target test-chat ./build/bin/test-chat * Update test-chat.cpp * Update test-chat.cpp * Update test-chat.cpp --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> jinja : fix heap OOB read in value equality comparison (#20782) Address GHSA-q9j6-4hhc-rq9p and GHSA-2q4c-9gq5-5vfp. The three-iterator overload of std::equal in value_array_t::equivalent() and value_object_t::equivalent() reads past the end of the shorter container when comparing arrays or objects of different lengths. Use the four-iterator overload (C++14) which checks both range lengths. Found-by: Pwno common : fix typo in debug log ('extracft' -> 'extract') (#20807) common/parser: fix nasty bug causing subtle corruption of generation prompt (#20825) jinja : refactor token advancement (#20864) * refactor token advancement * exercise sub-expressions common/autoparser : detect reasoning markers when enable_thinking changes system prompt (#20859) common : replace wrap_for_generation with a prefix convenience function and fix gpt-oss (#20912) jinja: fix macro with kwargs (#20960) * jinja: fix macro with kwargs * Apply suggestions from code review Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * fix newline problem --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : inhibit lazy grammar sampler while reasoning is active (#20970) * common : inhibit grammar while reasoning budget is active * cont : update force_pos in accept * cont : fix tests * cont : tweak should apply logic * cont : return early not using grammar sampler * Add tests * cont : prevent backend sampling when reasoning budget enabled * cont : fix typo --------- Co-authored-by: Piotr Wilkin <piotr.wilkin@syndatis.com> # Conflicts: # common/reasoning-budget.h # common/sampling.cpp # tools/cli/cli.cpp # tools/server/server-common.cpp # tools/server/server-task.cpp common/parser: fix reasoning whitespace bugs + extra parser tests (#21085) * fix whitespace reasoning issues + add reconstruction tests * Proper fix * fix Nemotron autoparser test expectations to include newline in marker common : add reasoning_format = none support to gpt-oss (#21094) common/json-schema: fix: handle non-capturing groups (?:...) in JSON schema pattern converter (#21124) The regex-to-grammar converter in _visit_pattern() crashes with SIGSEGV when a JSON schema "pattern" field contains a non-capturing group (?:...). Root cause: when the parser sees '(' followed by '?', it pushes a warning but does not advance past '?:'. The recursive transform() call then interprets '?' as a quantifier and calls seq.back() on an empty vector, causing undefined behavior. This commonly occurs when serving OpenAI-compatible tool calls from clients that include complex regex patterns in their JSON schemas (e.g., date validation patterns like ^(?:(?:\d\d[2468][048]|...)-02-29|...)$). The fix: - Skip '?:' after '(' to treat non-capturing groups as regular groups - For unsupported syntax (?=, ?!, etc.), skip to matching ')' safely, handling escaped characters to avoid miscounting parenthesis depth - Adjust the ')' unbalanced-parentheses check using direct char comparisons instead of substr - Add test cases for non-capturing groups (C++ only, as the JS/Python implementations do not yet support this syntax) common/parser: fix handling of tool definition with missing properties key (#21128) jinja : handle empty expressions correctly (#20913) * Reject empty computed member expressions before returning slices[0] from parse_member_expression_arguments(). * Treat empty computed member expressions with Jinja2 undefined semantics Treat empty computed member expressions like `a[]` as undefined instead of raising a parser error, to match Jinja2 behavior. - return a noop expression for empty computed member arguments - return undefined when a computed member key evaluates to undefined - add Jinja tests covering `a[]|default('fallback')` and `a[] is undefined` * Handle undefined computed member properties Move undefined-property handling to the common member access path, and add a test covering `a[undefined] is undefined`. * Use default undefined value in member access Initialize val and then return it when property is undefined. Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> * empty statement parses to blank_expression instead of noop_statement --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : gpt-oss handle builtin and unsolicited tool calls (#21213) fix: tool call parsing for LFM2 and LFM2.5 models (#21242) * fix: tool call parsing for LFM2 and LFM2.5 models' * refactor: add test / break out lfm2 and lfm2.5 parsing logic # Conflicts: # common/chat.cpp Relax prefill parser to allow space. (#21240) * Relax prefill parser to allow space. * Move changes from prefix() to parser generation * Only allow spaces if we're not having a pure content parser next common : add commentary rules for gpt-oss-20b (#21286) add reasoning budget model, mtmd: fix gguf conversion for audio/vision mmproj (#21309) * fix gguf conversion for audio/vision mmproj * fix test # Conflicts: # convert_hf_to_gguf.py # examples/eval-callback/eval-callback.cpp # examples/mtmd/CMakeLists.txt # examples/mtmd/clip-impl.h # examples/mtmd/mtmd.cpp # gguf-py/gguf/constants.py # gguf-py/gguf/gguf_writer.py # gguf-py/gguf/tensor_mapping.py # src/CMakeLists.txt # src/llama-arch.cpp # src/llama-arch.h # src/llama-model.cpp # src/llama-model.h # src/llama-vocab.cpp # src/models/models.h # tests/test-llama-archs.cpp # tools/mtmd/clip-graph.h # tools/mtmd/clip-model.h # tools/mtmd/clip.cpp # tools/mtmd/models/models.h fix: gemma 4 template (#21326) chat : avoid including json in chat.h (#21306) jinja: coerce input for string-specific filters (#21370) common : fix tool call type detection for nullable and enum schemas (#21327) * common : fix tool call type detection for nullable and enum schemas * common, tests : fix grammar delegation for nullable/enum schemas and add tests Fix enum type inference to scan all enum values (not just index 0) so schemas like {"enum": [0, "celsius"]} correctly detect string type. Fix schema_delegates in peg-parser to handle nullable type arrays (["string", "null"]) and typeless enum schemas in raw mode, allowing the tagged parser to use raw text instead of JSON-formatted strings. Add test cases for Qwen3-Coder (TAG_WITH_TAGGED format): - nullable string ["string", "null"] - nullable string with null first ["null", "string"] - nullable integer ["integer", "null"] - enum without explicit type key common/parser: fix call ID detection (Mistral parser mostly) + atomicity for tag-json parsers (#21230) * Fix call ID detection (Mistral parser mostly) + atomicity for tag-json parsers * Rename * Update common/chat-auto-parser-generator.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : add gemma 4 specialized parser (#21418) * common : add gemma4 dedicated parser * cont : add '<|tool_response>' as eog * cont : emit JSON from Gemma4 tool call AST * cont : more fixes * cont : refactor convert function * cont : refine rules and mapping * cont : add more tests * cont : clean up * cont : remove autoparser gemma4 implementation * cont : more cleanup * cont : rename gemma4.jinja to match the others * cont : add custom template to support interleaved thinking * cont : preserve reasoning in model turns * cont : fix initializer error * cont : fix unused vars * cont : fix accidental static * cont : fix specialized_template signature * fix extra semicolon * remove debug line and extra space [no ci] fix reasoning budget parser: fix MiniMax handling (#21573) jinja : support ensure_ascii=true, string repetition and int/float self-filtering (#21623) * feat: jinja engine improvements for reka-edge Port three Jinja engine improvements needed for the reka-edge model: 1. Python-style string repetition ("ab" * 3 → "ababab") 2. ensure_ascii=true support for tojson filter (escapes non-ASCII to \uXXXX) 3. int() builtin on value_int_t (identity, needed for Reka Edge template) * fix: escape invalid utf8 bytes when ensure_ascii=true The json_ensure_ascii_preserving_format function does not correctly handle an edge case where if UTF-8 parsing fails, it adds the non-ascii character back to the output as a raw byte. This commit fixes that by adding the unicode standard replacement character \\ufffd to the output instead. This is the standard behavior for various programming languages like Python, Rust, Go, etc. * chore: address PR comments 1. Add todo comment for supporting string repetition for array/tuples 2. Add support for float identity operation 3. Move invalid ascii test case to test_fuzzing * chore: accept suggestion for common/jinja/value.cpp Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> --------- Co-authored-by: Sigbjørn Skjæret <sigbjorn.skjaeret@scala.com> common : simplify autoparser tagged parser rules (#21216) * common : simplify autoparser tagged parser rules * cont : remove upper limit on optional args * cont : revert changes to parsing at the end * cont : undo arbitrary ordering of optional args * cont : fix uninitialized required parameters * revert to simplify merge * re-apply patches * restore flexible optional arg ordering tests common : fix ambiguous grammar rule in gemma4 (#21661) * common : fix ambiguous grammar rule in gemma4 * cont : fix missing comma... common : enable reasoning budget sampler for gemma4 (#21697) * fix: enable reasoning budget sampler for gemma4 Add thinking_start_tag and thinking_end_tag to common_chat_params_init_gemma4(). Without these, the reasoning budget sampler never activates for gemma4. Make the newline after "thought" optional in the PEG parser to handle budget=0 (sampler forces end tag before the newline). Add test case for empty thinking block. Fixes #21487 * use p.space() instead of p.optional(p.literal("\n")) in gemma4 thought parser common : better align to the updated official gemma4 template (#21704) fix: Fix broken structured output when using $refs in json_schema (#21699) chat: dedicated DeepSeek v3.2 parser + "official" template (#21785) Hide render_message_to_json warning common/gemma4 : handle parsing edge cases (#21760) common: skip reasoning budget sampler when no budget is requested (#21870) * common: skip reasoning budget sampler when no budget is requested After I added thinking_start_tag / thinking_end_tag for gemma4 in #21697, the reasoning budget sampler gets unconditionally created even when no budget is configured (the default -1). The same applies to kimi_k2, lfm2, lfm2_5, and ministral_3 which also set these tags. The budget gets converted to INT_MAX, so the sampler never actually forces any tokens but still runs per-token checks (start tag matching in IDLE state, token-to-piece conversion + UTF-8 checks in COUNTING state). More importantly, the mere existence of the sampler (non-null rbudget) disables backend sampling. Backend sampling lets the GPU select tokens directly, avoiding a full logits transfer from GPU to CPU every token. This could explain the 30% speed regression reported in #21784 (98 t/s to 70 t/s on Vulkan). So I added a reasoning_budget_tokens >= 0 check to the sampler creation condition. When the budget is unlimited, the sampler is not created, backend sampling stays enabled, and no per-token overhead is added. When a budget is explicitly set (0, 128, 1024, etc.), the sampler is created and works as before. * common: preserve rbudget when grammar is lazy Following up on the review feedback on #21870: keep the reasoning budget sampler when grammar_lazy is true, so the thinking-block grammar suppression from #20970 still works when tools are in use. This way, we only skip the sampler when both no budget is set AND grammar is not lazy. autoparser: support case of JSON_NATIVE with per-call markers (test case: Reka-Edge) (#21892) * fix grammar * fix add sampled token --------- Co-authored-by: Piotr Wilkin (ilintar) <piotr.wilkin@syndatis.com> Co-authored-by: firecoperana <firecoperana>
1008 lines
39 KiB
C++
1008 lines
39 KiB
C++
#include "chat-peg-parser.h"
|
|
|
|
#include "chat-auto-parser.h"
|
|
#include "ggml.h"
|
|
#include "peg-parser.h"
|
|
|
|
#include <nlohmann/json.hpp>
|
|
|
|
using ordered_json = nlohmann::ordered_json;
|
|
|
|
static std::string_view trim_trailing_space(std::string_view sv, int max = -1) {
|
|
int count = 0;
|
|
while (!sv.empty() && std::isspace(static_cast<unsigned char>(sv.back()))) {
|
|
if (max != -1 && count >= max) {
|
|
break;
|
|
}
|
|
sv.remove_suffix(1);
|
|
count++;
|
|
}
|
|
return sv;
|
|
}
|
|
|
|
static std::string_view trim_leading_space(std::string_view sv, int max = -1) {
|
|
int count = 0;
|
|
while (!sv.empty() && std::isspace(static_cast<unsigned char>(sv.front()))) {
|
|
if (max != -1 && count >= max) {
|
|
break;
|
|
}
|
|
sv.remove_prefix(1);
|
|
count++;
|
|
}
|
|
return sv;
|
|
}
|
|
|
|
static std::string_view trim(std::string_view sv) {
|
|
return trim_trailing_space(trim_leading_space(sv, 1));
|
|
}
|
|
|
|
// Count the number of unclosed '{' braces in a JSON-like string,
|
|
// properly skipping braces inside quoted strings.
|
|
static int json_brace_depth(const std::string & s) {
|
|
int depth = 0;
|
|
bool in_string = false;
|
|
bool escaped = false;
|
|
for (char c : s) {
|
|
if (escaped) {
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (c == '\\' && in_string) {
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (c == '"') {
|
|
in_string = !in_string;
|
|
continue;
|
|
}
|
|
if (!in_string) {
|
|
if (c == '{') {
|
|
depth++;
|
|
} else if (c == '}') {
|
|
depth--;
|
|
}
|
|
}
|
|
}
|
|
return depth;
|
|
}
|
|
|
|
// JSON-escape a string and return the inner content (without surrounding quotes).
|
|
static std::string escape_json_string_inner(const std::string & s) {
|
|
std::string escaped = ordered_json(s).dump();
|
|
if (escaped.size() >= 2 && escaped.front() == '"' && escaped.back() == '"') {
|
|
return escaped.substr(1, escaped.size() - 2);
|
|
}
|
|
return escaped;
|
|
}
|
|
|
|
// Convert Python-style single-quoted strings to JSON double-quoted strings
|
|
// Only converts outer string delimiters, properly handling escape sequences:
|
|
// - {'key': 'value'} -> {"key": "value"}
|
|
// - {'code': 'print(\'hello\')'} -> {"code": "print('hello')"}
|
|
// - {'msg': 'He said "hi"'} -> {"msg": "He said \"hi\""}
|
|
static std::string normalize_quotes_to_json(const std::string & input) {
|
|
std::string result;
|
|
result.reserve(input.size() + 16); // May need extra space for escaping
|
|
|
|
bool in_single_quoted = false;
|
|
bool in_double_quoted = false;
|
|
|
|
for (size_t i = 0; i < input.size(); ++i) {
|
|
char c = input[i];
|
|
|
|
// Handle escape sequences
|
|
if (c == '\\' && i + 1 < input.size()) {
|
|
char next = input[i + 1];
|
|
|
|
if (in_single_quoted) {
|
|
// Inside a single-quoted string being converted to double quotes
|
|
if (next == '\'') {
|
|
// \' -> ' (escaped single quote becomes unescaped in double-quoted string)
|
|
result += '\'';
|
|
++i;
|
|
continue;
|
|
}
|
|
if (next == '"') {
|
|
// \" stays as \" (already escaped, works in double-quoted string)
|
|
result += "\\\"";
|
|
++i;
|
|
continue;
|
|
}
|
|
// Other escapes (\n, \\, etc.): pass through both characters
|
|
result += c;
|
|
result += next;
|
|
++i;
|
|
continue;
|
|
}
|
|
|
|
if (in_double_quoted) {
|
|
// Inside a double-quoted string - pass through escape sequences as-is
|
|
result += c;
|
|
result += next;
|
|
++i;
|
|
continue;
|
|
}
|
|
|
|
// Outside any string - just pass through the backslash
|
|
result += c;
|
|
continue;
|
|
}
|
|
|
|
// Handle quote characters
|
|
if (c == '"') {
|
|
if (in_single_quoted) {
|
|
// Unescaped double quote inside single-quoted string -> must escape for JSON
|
|
result += "\\\"";
|
|
} else {
|
|
// Double quote as string delimiter or outside strings
|
|
in_double_quoted = !in_double_quoted;
|
|
result += c;
|
|
}
|
|
} else if (c == '\'') {
|
|
if (in_double_quoted) {
|
|
// Single quote inside double-quoted string -> pass through
|
|
result += c;
|
|
} else if (in_single_quoted) {
|
|
// Closing single quote -> convert to double quote
|
|
in_single_quoted = false;
|
|
result += '"';
|
|
} else {
|
|
// Opening single quote -> convert to double quote
|
|
in_single_quoted = true;
|
|
result += '"';
|
|
}
|
|
} else {
|
|
result += c;
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void tag_based_peg_mapper::from_ast(const common_peg_ast_arena & arena, const common_peg_parse_result & result) {
|
|
arena.visit(result, [this](const common_peg_ast_node & node) {
|
|
if (!node.tag.empty()) {
|
|
tags[node.tag] = std::string(node.text);
|
|
}
|
|
});
|
|
}
|
|
|
|
tagged_parse_result tagged_peg_parser::parse_and_extract(const std::string & input, common_peg_parse_flags extra_flags) const {
|
|
common_peg_parse_context ctx(input, flags | extra_flags);
|
|
auto parse_result = arena.parse(ctx);
|
|
|
|
tag_based_peg_mapper mapper;
|
|
mapper.from_ast(ctx.ast, parse_result);
|
|
|
|
return { std::move(parse_result), std::move(mapper.tags) };
|
|
}
|
|
|
|
tagged_parse_result tagged_peg_parser::parse_anywhere_and_extract(const std::string & input) const {
|
|
if (input.empty()) {
|
|
return parse_and_extract(input);
|
|
}
|
|
for (size_t i = 0; i < input.size(); i++) {
|
|
common_peg_parse_context ctx(input, flags);
|
|
auto parse_result = arena.parse(ctx, i);
|
|
if (parse_result.success() || i == input.size() - 1) {
|
|
tag_based_peg_mapper mapper;
|
|
mapper.from_ast(ctx.ast, parse_result);
|
|
return { std::move(parse_result), std::move(mapper.tags) };
|
|
}
|
|
}
|
|
GGML_ABORT("Should not happen");
|
|
}
|
|
|
|
tagged_peg_parser build_tagged_peg_parser(
|
|
const std::function<common_peg_parser(common_peg_parser_builder & builder)> & fn) {
|
|
common_peg_parser_builder builder;
|
|
builder.set_root(fn(builder));
|
|
return { builder.build() };
|
|
}
|
|
|
|
common_peg_parser common_chat_peg_builder::tag_with_safe_content(const std::string & tag_name,
|
|
const std::string & marker,
|
|
const common_peg_parser & p) {
|
|
if (marker.empty()) {
|
|
return zero_or_more(choice({ p, rule(tag_name, content(any())) }));
|
|
}
|
|
auto content_chunk = rule(tag_name, content(negate(literal(marker)) + any() + until(marker)));
|
|
return zero_or_more(choice({ p, content_chunk }));
|
|
}
|
|
|
|
std::string & common_chat_peg_mapper::args_target() {
|
|
return (current_tool && !current_tool->name.empty()) ? current_tool->arguments : args_buffer;
|
|
}
|
|
|
|
std::string common_chat_peg_mapper::normalize_container_value(const std::string & input) {
|
|
return normalize_quotes_to_json(input);
|
|
}
|
|
|
|
void common_chat_peg_mapper::from_ast(const common_peg_ast_arena & arena,
|
|
const common_peg_parse_result & parse_result_arg) {
|
|
arena.visit(parse_result_arg, [this](const common_peg_ast_node & node) { map(node); });
|
|
// Flush any pending tool call that was started but never got a name
|
|
// This happens during partial parsing when the tool call is incomplete
|
|
if (pending_tool_call.has_value() && !pending_tool_call->name.empty()) {
|
|
if (!args_buffer.empty()) {
|
|
pending_tool_call->arguments = args_buffer;
|
|
}
|
|
if (closing_quote_pending && !pending_tool_call->arguments.empty()) {
|
|
pending_tool_call->arguments += "\"";
|
|
}
|
|
result.tool_calls.push_back(pending_tool_call.value());
|
|
pending_tool_call.reset();
|
|
}
|
|
|
|
// Discard whitespace-only reasoning content (e.g. from <think></think> prefill)
|
|
if (!result.reasoning_content.empty()) {
|
|
bool all_whitespace = true;
|
|
for (char c : result.reasoning_content) {
|
|
if (c != ' ' && c != '\n' && c != '\r' && c != '\t') {
|
|
all_whitespace = false;
|
|
break;
|
|
}
|
|
}
|
|
if (all_whitespace) {
|
|
result.reasoning_content.clear();
|
|
}
|
|
}
|
|
}
|
|
|
|
void common_chat_peg_mapper::map(const common_peg_ast_node & node) {
|
|
// Handle reasoning/content tags
|
|
bool is_reasoning = node.tag == common_chat_peg_builder::REASONING;
|
|
bool is_content = node.tag == common_chat_peg_builder::CONTENT;
|
|
|
|
if (is_reasoning) { // GPT OSS can have more than 1 reasoning block, so concatenate here
|
|
result.reasoning_content += std::string(node.text);
|
|
}
|
|
|
|
if (is_content) {
|
|
// Concatenate content from multiple content nodes (e.g., when reasoning markers
|
|
// are preserved before content markers in reasoning_format=NONE mode)
|
|
result.content += std::string(node.text);
|
|
}
|
|
|
|
// Handle tool-related tags (supporting both JSON and tagged formats)
|
|
bool is_tool_open = node.tag == common_chat_peg_builder::TOOL_OPEN;
|
|
bool is_tool_close = node.tag == common_chat_peg_builder::TOOL_CLOSE;
|
|
bool is_tool_name = node.tag == common_chat_peg_builder::TOOL_NAME;
|
|
bool is_tool_id = node.tag == common_chat_peg_builder::TOOL_ID;
|
|
bool is_tool_args = node.tag == common_chat_peg_builder::TOOL_ARGS;
|
|
bool is_arg_open = node.tag == common_chat_peg_builder::TOOL_ARG_OPEN;
|
|
bool is_arg_close = node.tag == common_chat_peg_builder::TOOL_ARG_CLOSE;
|
|
bool is_arg_name = node.tag == common_chat_peg_builder::TOOL_ARG_NAME;
|
|
bool is_arg_value = node.tag == common_chat_peg_builder::TOOL_ARG_VALUE;
|
|
bool is_arg_string_value = node.tag == common_chat_peg_builder::TOOL_ARG_STRING_VALUE;
|
|
|
|
if (is_tool_open) {
|
|
pending_tool_call = common_chat_tool_call();
|
|
current_tool = &pending_tool_call.value();
|
|
arg_count = 0;
|
|
args_buffer.clear();
|
|
closing_quote_pending = false;
|
|
}
|
|
|
|
if (is_tool_id && current_tool) {
|
|
auto text = trim_trailing_space(node.text);
|
|
if (text.size() >= 2 && text.front() == '"' && text.back() == '"') {
|
|
text = text.substr(1, text.size() - 2);
|
|
}
|
|
current_tool->id = std::string(text);
|
|
}
|
|
|
|
if (is_tool_name && current_tool) {
|
|
current_tool->name = std::string(trim_trailing_space(node.text));
|
|
// Now that we have the name, populate the arguments from the buffer
|
|
if (!args_buffer.empty()) {
|
|
current_tool->arguments = args_buffer;
|
|
args_buffer.clear();
|
|
} else if (current_tool->arguments.empty()) {
|
|
current_tool->arguments = "{";
|
|
}
|
|
// Add the tool call to results so streaming can see it
|
|
if (pending_tool_call.has_value()) {
|
|
result.tool_calls.push_back(pending_tool_call.value());
|
|
pending_tool_call.reset();
|
|
current_tool = &result.tool_calls.back();
|
|
}
|
|
}
|
|
|
|
if (is_tool_args && current_tool) {
|
|
// For JSON format: arguments come as a complete JSON object
|
|
// For tagged format: built up from individual arg_name/arg_value nodes
|
|
auto text = trim_trailing_space(node.text);
|
|
if (!text.empty() && text.front() == '{') {
|
|
args_target() = std::string(text);
|
|
}
|
|
}
|
|
|
|
if (is_arg_open) {
|
|
closing_quote_pending = false;
|
|
}
|
|
|
|
if (is_arg_name && current_tool) {
|
|
std::string arg_entry;
|
|
if (arg_count > 0) {
|
|
arg_entry = ",";
|
|
}
|
|
arg_entry += ordered_json(trim(node.text)).dump() + ":";
|
|
++arg_count;
|
|
|
|
auto & target = args_target();
|
|
if (target.empty()) {
|
|
target = "{";
|
|
}
|
|
target += arg_entry;
|
|
}
|
|
|
|
if ((is_arg_value || is_arg_string_value) && current_tool) {
|
|
std::string value_content = std::string(trim_trailing_space(trim_leading_space(node.text, 1), 1));
|
|
|
|
std::string value_to_add;
|
|
if (value_content.empty() && is_arg_string_value) {
|
|
// Empty string value - arg_close will add the closing quote
|
|
value_to_add = "\"";
|
|
closing_quote_pending = true;
|
|
} else if (!value_content.empty() && is_arg_string_value) {
|
|
// Schema declares this as string type - always treat as literal string value
|
|
if (!closing_quote_pending) {
|
|
value_to_add = "\"";
|
|
closing_quote_pending = true;
|
|
}
|
|
value_to_add += escape_json_string_inner(value_content);
|
|
} else if (!value_content.empty()) {
|
|
// For potential containers, normalize Python-style single quotes to JSON double quotes
|
|
bool is_potential_container = value_content[0] == '[' || value_content[0] == '{';
|
|
if (is_potential_container) {
|
|
value_content = normalize_container_value(value_content);
|
|
}
|
|
|
|
// Try to parse as JSON value (number, bool, null, object, array)
|
|
try {
|
|
ordered_json parsed = ordered_json::parse(value_content);
|
|
if (parsed.is_string()) {
|
|
// Don't add closing quote yet (added by arg_close) for monotonic streaming
|
|
std::string escaped = parsed.dump();
|
|
if (!escaped.empty() && escaped.back() == '"') {
|
|
escaped.pop_back();
|
|
}
|
|
value_to_add = escaped;
|
|
closing_quote_pending = true;
|
|
} else {
|
|
// Non-string values: use raw content to preserve whitespace for monotonicity
|
|
value_to_add = value_content;
|
|
}
|
|
} catch (...) {
|
|
if (node.is_partial && is_potential_container) {
|
|
// Partial container: pass through the already-normalized content
|
|
value_to_add = value_content;
|
|
} else {
|
|
// Not valid JSON - treat as string value
|
|
if (!closing_quote_pending) {
|
|
value_to_add = "\"";
|
|
closing_quote_pending = true;
|
|
}
|
|
value_to_add += escape_json_string_inner(value_content);
|
|
}
|
|
}
|
|
}
|
|
|
|
args_target() += value_to_add;
|
|
}
|
|
|
|
if (is_arg_close && current_tool) {
|
|
if (closing_quote_pending) {
|
|
args_target() += "\"";
|
|
closing_quote_pending = false;
|
|
}
|
|
}
|
|
|
|
if (is_tool_close && current_tool) {
|
|
// Flush buffer to arguments if tool name was never seen
|
|
if (current_tool->name.empty() && !args_buffer.empty()) {
|
|
current_tool->arguments = args_buffer;
|
|
args_buffer.clear();
|
|
}
|
|
// Close any pending string quote
|
|
if (closing_quote_pending) {
|
|
current_tool->arguments += "\"";
|
|
closing_quote_pending = false;
|
|
}
|
|
// Close any unclosed braces (accounts for nested objects)
|
|
for (int d = json_brace_depth(current_tool->arguments); d > 0; d--) {
|
|
current_tool->arguments += "}";
|
|
}
|
|
// Add tool call to results if named; otherwise discard
|
|
if (pending_tool_call.has_value()) {
|
|
if (!current_tool->name.empty()) {
|
|
result.tool_calls.push_back(pending_tool_call.value());
|
|
}
|
|
pending_tool_call.reset();
|
|
}
|
|
}
|
|
}
|
|
|
|
common_peg_parser common_chat_peg_builder::standard_constructed_tools(
|
|
const std::map<std::string, std::string> & markers,
|
|
const ordered_json & tools,
|
|
bool parallel_tool_calls,
|
|
bool force_tool_calls) {
|
|
if (!tools.is_array() || tools.empty()) {
|
|
return eps();
|
|
}
|
|
|
|
// Extract markers with defaults
|
|
auto get_marker = [&markers](const std::string & key, const std::string & default_val = "") -> std::string {
|
|
auto it = markers.find(key);
|
|
return it != markers.end() ? it->second : default_val;
|
|
};
|
|
|
|
std::string section_start = get_marker("tool_call_start_marker", "<tool_call>");
|
|
std::string section_end = get_marker("tool_call_end_marker", "</tool_call>");
|
|
std::string func_opener = get_marker("function_opener", "<function=");
|
|
std::string func_name_suffix = get_marker("function_name_suffix", ">");
|
|
std::string func_closer = get_marker("function_closer", "</function>");
|
|
std::string param_key_prefix = get_marker("parameter_key_prefix", "<param=");
|
|
std::string param_key_suffix = get_marker("parameter_key_suffix", ">");
|
|
std::string param_closer = get_marker("parameter_closer", "</param>");
|
|
|
|
// Build tool choices for tagged format
|
|
auto tool_choices = choice();
|
|
|
|
for (const auto & tool_def : tools) {
|
|
if (!tool_def.contains("function")) {
|
|
continue;
|
|
}
|
|
const auto & function = tool_def.at("function");
|
|
std::string name = function.at("name");
|
|
ordered_json params = function.contains("parameters") ? function.at("parameters") : ordered_json::object();
|
|
|
|
// Build argument parsers
|
|
auto args = eps();
|
|
if (params.contains("properties") && !params["properties"].empty()) {
|
|
auto arg_choice = choice();
|
|
for (const auto & el : params["properties"].items()) {
|
|
const std::string & prop_name = el.key();
|
|
|
|
auto arg_name_parser =
|
|
choice({ literal(prop_name), literal("\"" + prop_name + "\""), literal("'" + prop_name + "'") });
|
|
|
|
auto arg_rule = tool_arg(tool_arg_open(literal(param_key_prefix)) + tool_arg_name(arg_name_parser) +
|
|
literal(param_key_suffix) + tool_arg_value(until(param_closer)) +
|
|
tool_arg_close(literal(param_closer)));
|
|
arg_choice |= arg_rule;
|
|
}
|
|
args = zero_or_more(arg_choice + space());
|
|
}
|
|
|
|
// Build function parser: <function=name>args</function>
|
|
auto tool_parser = tool(tool_open(literal(func_opener) + tool_name(literal(name)) + literal(func_name_suffix)) +
|
|
space() + tool_args(args) + space() + tool_close(literal(func_closer)));
|
|
|
|
tool_choices |= rule("tool-" + name, tool_parser);
|
|
}
|
|
|
|
// Build the section with markers
|
|
auto section =
|
|
parallel_tool_calls ?
|
|
trigger_rule("tool-call", literal(section_start) + space() + one_or_more(tool_choices + space()) +
|
|
literal(section_end)) :
|
|
trigger_rule("tool-call", literal(section_start) + space() + tool_choices + space() + literal(section_end));
|
|
|
|
return force_tool_calls ? section : optional(section);
|
|
}
|
|
|
|
// Python-style tool calls: name(arg1="value1", arg2=123)
|
|
// Used only by LFM2 for now, so we don't merge it into autoparser
|
|
common_peg_parser common_chat_peg_builder::python_style_tool_calls(
|
|
const ordered_json & tools,
|
|
bool parallel_tool_calls) {
|
|
if (!tools.is_array() || tools.empty()) {
|
|
return eps();
|
|
}
|
|
|
|
auto tool_choices = choice();
|
|
|
|
for (const auto & tool_def : tools) {
|
|
if (!tool_def.contains("function")) {
|
|
continue;
|
|
}
|
|
const auto & function = tool_def.at("function");
|
|
std::string name = function.at("name");
|
|
ordered_json params = function.contains("parameters") ? function.at("parameters") : ordered_json::object();
|
|
|
|
auto args = eps();
|
|
if (params.contains("properties") && !params["properties"].empty()) {
|
|
auto arg_choice = choice();
|
|
for (const auto & el : params["properties"].items()) {
|
|
const std::string & prop_name = el.key();
|
|
const auto & prop_def = el.value();
|
|
bool is_string_type = (prop_def.contains("type") && prop_def["type"] == "string");
|
|
|
|
auto arg_name_parser = literal(prop_name);
|
|
|
|
common_peg_parser arg_value_parser = eps();
|
|
auto string_value_parser = choice({
|
|
literal("\"") + tool_arg_string_value(string_content('"')) + literal("\""),
|
|
literal("'") + tool_arg_string_value(string_content('\'')) + literal("'")
|
|
});
|
|
|
|
if (is_string_type) {
|
|
arg_value_parser = string_value_parser;
|
|
} else {
|
|
arg_value_parser = tool_arg_value(python_value());
|
|
}
|
|
|
|
// Full argument: name="value" or name=value
|
|
auto arg_rule = tool_arg(
|
|
tool_arg_open(eps()) +
|
|
tool_arg_name(arg_name_parser) +
|
|
literal("=") +
|
|
arg_value_parser +
|
|
tool_arg_close(eps())
|
|
);
|
|
arg_choice |= arg_rule;
|
|
}
|
|
|
|
args = arg_choice + zero_or_more("," + space() + arg_choice);
|
|
}
|
|
|
|
auto tool_parser = tool(tool_open(tool_name(literal(name)) + literal("(")) +
|
|
space() + tool_args(args) + space() + tool_close(literal(")"))
|
|
);
|
|
|
|
tool_choices |= rule("tool-" + name, tool_parser);
|
|
}
|
|
|
|
if (parallel_tool_calls) {
|
|
return "[" + space() + tool_choices + zero_or_more("," + space() + tool_choices) + space() + "]";
|
|
}
|
|
return "[" + space() + tool_choices + space() + "]";
|
|
}
|
|
|
|
// Helper: Parse dot notation key into prefix and field name
|
|
static std::pair<std::string, std::string> parse_key_spec(const std::string & key) {
|
|
auto dot_pos = key.find('.');
|
|
if (dot_pos == std::string::npos) {
|
|
return {"", key}; // Top-level field
|
|
}
|
|
return {key.substr(0, dot_pos), key.substr(dot_pos + 1)};
|
|
}
|
|
|
|
// Mode 1: function_is_key — parse {"function_name": {...}}
|
|
common_peg_parser common_chat_peg_builder::build_json_tools_function_is_key(
|
|
const ordered_json & tools,
|
|
const std::string & args_key,
|
|
const std::string & effective_args_key,
|
|
const std::string & call_id_key,
|
|
const std::string & gen_call_id_key) {
|
|
|
|
auto tool_choices = choice();
|
|
|
|
for (const auto & tool_def : tools) {
|
|
if (!tool_def.contains("function")) {
|
|
continue;
|
|
}
|
|
const auto & function = tool_def.at("function");
|
|
std::string name = function.at("name");
|
|
ordered_json params = function.contains("parameters") ? function.at("parameters") : ordered_json::object();
|
|
|
|
// Build inner object fields
|
|
std::vector<common_peg_parser> inner_fields;
|
|
|
|
if (!call_id_key.empty()) {
|
|
auto id_parser = atomic(
|
|
literal("\"" + call_id_key + "\"") + space() + literal(":") + space() +
|
|
literal("\"") + tool_id(string_content('"')) + literal("\"")
|
|
);
|
|
inner_fields.push_back(optional(id_parser + space() + optional(literal(",") + space())));
|
|
}
|
|
|
|
if (!gen_call_id_key.empty()) {
|
|
auto gen_id_parser = atomic(
|
|
literal("\"" + gen_call_id_key + "\"") + space() + literal(":") + space() +
|
|
choice({
|
|
literal("\"") + tool_id(string_content('"')) + literal("\""),
|
|
tool_id(json_number())
|
|
})
|
|
);
|
|
inner_fields.push_back(optional(gen_id_parser + space() + optional(literal(",") + space())));
|
|
}
|
|
|
|
// Arguments — either wrapped in args_key or parsed directly
|
|
common_peg_parser args_parser = eps();
|
|
if (args_key.empty()) {
|
|
args_parser = tool_args(schema(json(), "tool-" + name + "-schema", params));
|
|
} else {
|
|
args_parser = literal("\"" + effective_args_key + "\"") + space() + literal(":") + space() +
|
|
tool_args(schema(json(), "tool-" + name + "-schema", params));
|
|
}
|
|
inner_fields.push_back(args_parser);
|
|
|
|
// Build inner object parser
|
|
common_peg_parser inner_object = eps();
|
|
if (args_key.empty() && inner_fields.size() == 1) {
|
|
inner_object = inner_fields[0];
|
|
} else {
|
|
inner_object = literal("{") + space();
|
|
for (size_t i = 0; i < inner_fields.size(); i++) {
|
|
inner_object = inner_object + inner_fields[i];
|
|
if (i < inner_fields.size() - 1) {
|
|
inner_object = inner_object + space();
|
|
}
|
|
}
|
|
inner_object = inner_object + space() + literal("}");
|
|
}
|
|
|
|
auto tool_parser = tool(
|
|
tool_open(literal("{")) + space() +
|
|
literal("\"") + tool_name(literal(name)) + literal("\"") +
|
|
space() + literal(":") + space() +
|
|
inner_object +
|
|
space() + tool_close(literal("}"))
|
|
);
|
|
|
|
tool_choices |= rule("tool-" + name, tool_parser);
|
|
}
|
|
|
|
return tool_choices;
|
|
}
|
|
|
|
// Mode 2: Nested keys (dot notation like "function.name")
|
|
common_peg_parser common_chat_peg_builder::build_json_tools_nested_keys(
|
|
const ordered_json & tools,
|
|
const std::string & effective_name_key,
|
|
const std::string & effective_args_key,
|
|
const std::string & call_id_key,
|
|
const std::string & gen_call_id_key) {
|
|
|
|
auto tool_choices = choice();
|
|
|
|
auto name_spec = parse_key_spec(effective_name_key);
|
|
auto args_spec = parse_key_spec(effective_args_key);
|
|
|
|
std::string nested_prefix = !name_spec.first.empty() ? name_spec.first : args_spec.first;
|
|
std::string nested_name_field = !name_spec.first.empty() ? name_spec.second : effective_name_key;
|
|
std::string nested_args_field = !args_spec.first.empty() ? args_spec.second : effective_args_key;
|
|
|
|
for (const auto & tool_def : tools) {
|
|
if (!tool_def.contains("function")) {
|
|
continue;
|
|
}
|
|
const auto & function = tool_def.at("function");
|
|
std::string name = function.at("name");
|
|
ordered_json params = function.contains("parameters") ? function.at("parameters") : ordered_json::object();
|
|
|
|
auto nested_name = literal("\"" + nested_name_field + "\"") + space() + literal(":") + space() +
|
|
atomic(literal("\"") + tool_name(literal(name)) + literal("\""));
|
|
auto nested_args = literal("\"" + nested_args_field + "\"") + space() + literal(":") + space() +
|
|
tool_args(schema(json(), "tool-" + name + "-schema", params));
|
|
|
|
auto nested_object = literal("{") + space() +
|
|
nested_name + space() + literal(",") + space() +
|
|
nested_args +
|
|
space() + literal("}");
|
|
|
|
// Format: { id?, "function": {...} }
|
|
auto tool_parser_body = tool_open(literal("{")) + space();
|
|
|
|
if (!call_id_key.empty()) {
|
|
auto id_spec = parse_key_spec(call_id_key);
|
|
if (id_spec.first.empty()) {
|
|
auto id_parser = atomic(
|
|
literal("\"" + call_id_key + "\"") + space() + literal(":") + space() +
|
|
literal("\"") + tool_id(string_content('"')) + literal("\"")
|
|
);
|
|
tool_parser_body = tool_parser_body + optional(id_parser + space() + literal(",") + space());
|
|
}
|
|
}
|
|
|
|
if (!gen_call_id_key.empty()) {
|
|
auto gen_id_spec = parse_key_spec(gen_call_id_key);
|
|
if (gen_id_spec.first.empty()) {
|
|
auto gen_id_parser = atomic(
|
|
literal("\"" + gen_call_id_key + "\"") + space() + literal(":") + space() +
|
|
choice({
|
|
literal("\"") + tool_id(string_content('"')) + literal("\""),
|
|
tool_id(json_number())
|
|
})
|
|
);
|
|
tool_parser_body = tool_parser_body + optional(gen_id_parser + space() + literal(",") + space());
|
|
}
|
|
}
|
|
|
|
auto nested_field = literal("\"" + nested_prefix + "\"") + space() + literal(":") + space() + nested_object;
|
|
tool_parser_body = tool_parser_body + nested_field + space() + tool_close(literal("}"));
|
|
|
|
tool_choices |= rule("tool-" + name, tool(tool_parser_body));
|
|
}
|
|
|
|
return tool_choices;
|
|
}
|
|
|
|
// Mode 3: Flat keys with optional ID fields and parameter ordering
|
|
common_peg_parser common_chat_peg_builder::build_json_tools_flat_keys(
|
|
const ordered_json & tools,
|
|
const std::string & effective_name_key,
|
|
const std::string & effective_args_key,
|
|
const std::string & call_id_key,
|
|
const std::string & gen_call_id_key,
|
|
const std::vector<std::string> & parameters_order) {
|
|
|
|
auto tool_choices = choice();
|
|
auto name_key_parser = literal("\"" + effective_name_key + "\"");
|
|
auto args_key_parser = literal("\"" + effective_args_key + "\"");
|
|
|
|
for (const auto & tool_def : tools) {
|
|
if (!tool_def.contains("function")) {
|
|
continue;
|
|
}
|
|
const auto & function = tool_def.at("function");
|
|
std::string name = function.at("name");
|
|
ordered_json params = function.contains("parameters") ? function.at("parameters") : ordered_json::object();
|
|
|
|
auto tool_name_ = name_key_parser + space() + literal(":") + space() +
|
|
atomic(literal("\"") + tool_name(literal(name)) + literal("\""));
|
|
auto tool_args_ = args_key_parser + space() + literal(":") + space() +
|
|
tool_args(schema(json(), "tool-" + name + "-schema", params));
|
|
|
|
// Build ID parsers if keys are provided
|
|
common_peg_parser id_parser = eps();
|
|
if (!call_id_key.empty()) {
|
|
id_parser = atomic(
|
|
literal("\"" + call_id_key + "\"") + space() + literal(":") + space() +
|
|
choice({
|
|
literal("\"") + tool_id(string_content('"')) + literal("\""),
|
|
tool_id(json_number())
|
|
})
|
|
);
|
|
}
|
|
|
|
common_peg_parser gen_id_parser = eps();
|
|
if (!gen_call_id_key.empty()) {
|
|
gen_id_parser = atomic(
|
|
literal("\"" + gen_call_id_key + "\"") + space() + literal(":") + space() +
|
|
choice({
|
|
literal("\"") + tool_id(string_content('"')) + literal("\""),
|
|
tool_id(json_number())
|
|
})
|
|
);
|
|
}
|
|
|
|
// Create (parser, key) pairs for all fields, then sort by parameters_order
|
|
std::vector<std::pair<common_peg_parser, std::string>> parser_pairs;
|
|
parser_pairs.emplace_back(tool_name_, effective_name_key);
|
|
parser_pairs.emplace_back(tool_args_, effective_args_key);
|
|
if (!call_id_key.empty()) {
|
|
parser_pairs.emplace_back(optional(id_parser), call_id_key);
|
|
}
|
|
if (!gen_call_id_key.empty()) {
|
|
parser_pairs.emplace_back(optional(gen_id_parser), gen_call_id_key);
|
|
}
|
|
|
|
std::sort(parser_pairs.begin(), parser_pairs.end(),
|
|
[¶meters_order](const auto & a, const auto & b) {
|
|
auto pos_a = std::find(parameters_order.begin(), parameters_order.end(), a.second);
|
|
auto pos_b = std::find(parameters_order.begin(), parameters_order.end(), b.second);
|
|
size_t idx_a = (pos_a == parameters_order.end()) ? parameters_order.size() : std::distance(parameters_order.begin(), pos_a);
|
|
size_t idx_b = (pos_b == parameters_order.end()) ? parameters_order.size() : std::distance(parameters_order.begin(), pos_b);
|
|
return idx_a < idx_b;
|
|
});
|
|
|
|
auto ordered_body = tool_open(literal("{")) + space();
|
|
for (size_t i = 0; i < parser_pairs.size(); i++) {
|
|
ordered_body = ordered_body + parser_pairs[i].first;
|
|
if (i < parser_pairs.size() - 1) {
|
|
ordered_body = ordered_body + space() + literal(",") + space();
|
|
}
|
|
}
|
|
ordered_body = ordered_body + space() + tool_close(literal("}"));
|
|
|
|
tool_choices |= rule("tool-" + name, tool(ordered_body));
|
|
}
|
|
|
|
return tool_choices;
|
|
}
|
|
|
|
common_peg_parser common_chat_peg_builder::prefix(const std::string & s, const std::string & delimiter) {
|
|
if (s.empty()) {
|
|
return eps();
|
|
}
|
|
if (delimiter.empty()) {
|
|
return literal(s);
|
|
}
|
|
return literal(s.substr(0, s.rfind(delimiter)));
|
|
}
|
|
|
|
common_peg_parser common_chat_peg_builder::standard_json_tools(
|
|
const std::string & section_start,
|
|
const std::string & section_end,
|
|
const ordered_json & tools,
|
|
bool parallel_tool_calls,
|
|
bool force_tool_calls,
|
|
const std::string & name_key,
|
|
const std::string & args_key,
|
|
bool array_wrapped,
|
|
bool function_is_key,
|
|
const std::string & call_id_key,
|
|
const std::string & gen_call_id_key,
|
|
const std::vector<std::string> & parameters_order) {
|
|
if (!tools.is_array() || tools.empty()) {
|
|
return eps();
|
|
}
|
|
|
|
std::string effective_name_key = name_key.empty() ? "name" : name_key;
|
|
std::string effective_args_key = args_key.empty() ? "arguments" : args_key;
|
|
|
|
// Dispatch to the appropriate builder based on the JSON layout mode
|
|
common_peg_parser tool_choices = eps();
|
|
if (function_is_key) {
|
|
tool_choices = build_json_tools_function_is_key(tools, args_key, effective_args_key, call_id_key, gen_call_id_key);
|
|
} else {
|
|
auto name_spec = parse_key_spec(effective_name_key);
|
|
auto args_spec = parse_key_spec(effective_args_key);
|
|
if (!name_spec.first.empty() || !args_spec.first.empty()) {
|
|
tool_choices = build_json_tools_nested_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key);
|
|
} else {
|
|
tool_choices = build_json_tools_flat_keys(tools, effective_name_key, effective_args_key, call_id_key, gen_call_id_key, parameters_order);
|
|
}
|
|
}
|
|
|
|
// Build the section with markers
|
|
auto tool_calls = tool_choices;
|
|
if (parallel_tool_calls) {
|
|
tool_calls = tool_calls + zero_or_more(space() + literal(",") + space() + tool_choices);
|
|
}
|
|
|
|
if (array_wrapped) {
|
|
tool_calls = literal("[") + space() + tool_calls + space() + literal("]");
|
|
}
|
|
|
|
auto section =
|
|
trigger_rule("tool-call", literal(section_start) + space() + tool_calls + space() + literal(section_end));
|
|
|
|
return force_tool_calls ? section : optional(section);
|
|
}
|
|
|
|
void common_chat_peg_gemma4_mapper::from_ast(const common_peg_ast_arena & arena, const common_peg_parse_result & result) {
|
|
for (const auto & node : result.nodes) {
|
|
visit(arena, node);
|
|
}
|
|
}
|
|
|
|
static std::string gemma4_to_json(const common_peg_ast_arena & arena, common_peg_ast_id id) {
|
|
const auto & node = arena.get(id);
|
|
|
|
if (node.text.empty()) {
|
|
return "";
|
|
}
|
|
|
|
if (node.rule == "gemma4-number" || node.rule == "gemma4-bool" || node.rule == "gemma4-null") {
|
|
return std::string(node.text);
|
|
}
|
|
|
|
if (node.rule == "gemma4-string-content") {
|
|
return escape_json_string_inner(std::string(node.text));
|
|
}
|
|
|
|
if (node.rule == "gemma4-string") {
|
|
std::string result = "\"";
|
|
if (!node.children.empty()) {
|
|
result += gemma4_to_json(arena, node.children[0]);
|
|
if (!node.is_partial) {
|
|
result += "\"";
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
if (node.rule == "gemma4-array") {
|
|
std::string result = "[";
|
|
|
|
bool add_comma = false;
|
|
for (auto child_id : node.children) {
|
|
if (add_comma) {
|
|
result += ',';
|
|
}
|
|
add_comma = true;
|
|
result += gemma4_to_json(arena, child_id);
|
|
}
|
|
|
|
if (!node.is_partial) {
|
|
result += ']';
|
|
}
|
|
return result;
|
|
}
|
|
|
|
if (node.rule == "gemma4-dict-key-name") {
|
|
return std::string(node.text);
|
|
}
|
|
|
|
if (node.rule == "gemma4-dict-key") {
|
|
std::string result = "\"";
|
|
if (!node.children.empty()) {
|
|
result += escape_json_string_inner(gemma4_to_json(arena, node.children[0]));
|
|
}
|
|
if (!node.is_partial) {
|
|
result += "\":";
|
|
}
|
|
return result;
|
|
}
|
|
|
|
if (node.rule == "gemma4-dict-kv") {
|
|
std::string result;
|
|
for (auto child_id : node.children) {
|
|
result += gemma4_to_json(arena, child_id);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
if (node.rule == "gemma4-dict") {
|
|
std::string result = "{";
|
|
|
|
bool add_comma = false;
|
|
for (auto child_id : node.children) {
|
|
if (add_comma) {
|
|
result += ',';
|
|
}
|
|
add_comma = true;
|
|
result += gemma4_to_json(arena, child_id);
|
|
}
|
|
|
|
if (!node.is_partial) {
|
|
result += '}';
|
|
}
|
|
return result;
|
|
}
|
|
|
|
if (node.rule == "gemma4-value") {
|
|
if (!node.children.empty()) {
|
|
return gemma4_to_json(arena, node.children[0]);
|
|
}
|
|
return "";
|
|
}
|
|
|
|
return "";
|
|
}
|
|
|
|
void common_chat_peg_gemma4_mapper::visit(const common_peg_ast_arena & arena, common_peg_ast_id id) {
|
|
const auto & node = arena.get(id);
|
|
|
|
if (node.tag == "reasoning") {
|
|
result.reasoning_content += std::string(node.text);
|
|
return;
|
|
}
|
|
|
|
if (node.tag == "content") {
|
|
result.content += std::string(node.text);
|
|
return;
|
|
}
|
|
|
|
if (node.tag == "tool") {
|
|
auto name_id = arena.find_by_tag(node, "tool-name");
|
|
auto args_id = arena.find_by_tag(node, "tool-args");
|
|
|
|
if (name_id != COMMON_PEG_INVALID_AST_ID && args_id != COMMON_PEG_INVALID_AST_ID) {
|
|
const auto & name_node = arena.get(name_id);
|
|
const auto & args_node = arena.get(args_id);
|
|
|
|
if (!name_node.is_partial) {
|
|
common_chat_tool_call call;
|
|
call.name = std::string(name_node.text);
|
|
if (!args_node.children.empty()) {
|
|
call.arguments = gemma4_to_json(arena, args_node.children[0]);
|
|
}
|
|
result.tool_calls.push_back(call);
|
|
}
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
for (auto child_id : node.children) {
|
|
visit(arena, child_id);
|
|
}
|
|
}
|