This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/vendor/llama/common/chat-auto-parser-generator.cpp
T
Deadcode 8ddb77e03c radiance 1.0.1
- Up to 32 sequences a step on every model. The DSpark drafter (MiniCPM5) no longer rejects every
  draft from the tenth sequence on, and the step batch's block tables and media staging are
  charged to the VRAM budget instead of the headroom kernels load into.
- A tool parameter whose schema accepts no value ({"not": {}}, as TypeBox and Arktype export
  `never`) is an argument no call writes, instead of failing the request. oh-my-pi's task tool
  works.
- --served-model-name NAME and --override-chat-template PATH.
- The startup session count counts only the part of the KV pool that holds context.
- Compose files and README run --max-num-seqs 32 where it keeps a 200K-token request.
2026-10-04 15:07:32 +02:00

668 lines
34 KiB
C++

#include "chat-auto-parser-helpers.h"
#include "chat-auto-parser.h"
#include "chat-peg-parser.h"
#include "chat.h"
#include "common.h"
#include "json-schema-to-grammar.h"
#include "log.h"
#include "nlohmann/json.hpp"
#include "peg-parser.h"
#include <stdexcept>
#include <string>
using json = nlohmann::ordered_json;
// Helper to iterate over tools/functions
static void foreach_function(const json & tools, const std::function<void(const json &)> & fn) {
for (const auto & tool : tools) {
if (!tool.contains("type") || tool.at("type") != "function" || !tool.contains("function")) {
continue;
}
fn(tool);
}
}
namespace autoparser {
parser_build_context::parser_build_context(common_chat_peg_builder & p, const generation_params & inputs) :
p(p),
inputs(inputs),
reasoning_parser(p.eps()) {}
common_chat_params peg_generator::generate_parser(const common_chat_template & tmpl,
const struct generation_params & inputs) {
// Run differential analysis to extract template structure
struct autoparser autoparser;
autoparser.analyze_template(tmpl);
return generate_parser(tmpl, inputs, autoparser);
}
common_chat_params peg_generator::generate_parser(const common_chat_template & tmpl,
const struct generation_params & inputs,
const autoparser & autoparser) {
// Create the result structure
common_chat_params data;
data.prompt = common_chat_template_direct_apply(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt(tmpl, inputs);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.preserved_tokens = autoparser.preserved_tokens;
std::string parser_generation_prompt = data.generation_prompt;
if (inputs.continue_final_message != COMMON_CHAT_CONTINUATION_NONE && !inputs.continue_msg.empty()) {
// Build up generation prompt manually
const auto & msg = inputs.continue_msg;
if (!autoparser.reasoning.start.empty()) {
data.generation_prompt = data.generation_prompt.substr(0, data.generation_prompt.find(autoparser.reasoning.start));
data.generation_prompt += autoparser.reasoning.start + msg.reasoning_content;
if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
data.generation_prompt += autoparser.reasoning.end;
}
}
if (inputs.continue_final_message == COMMON_CHAT_CONTINUATION_CONTENT) {
data.generation_prompt += msg.render_content();
}
data.prompt += data.generation_prompt;
}
auto parser = autoparser.build_parser(inputs, parser_generation_prompt);
data.parser = parser.save();
// Build grammar if tools are present
bool has_tools =
autoparser.tools.format.mode != tool_format::NONE && inputs.tools.is_array() && !inputs.tools.empty();
std::string trigger_marker = !autoparser.tools.format.section_start.empty() ? autoparser.tools.format.section_start :
autoparser.tools.format.per_call_start;
bool has_response_format = !inputs.json_schema.empty() && inputs.json_schema.is_object();
bool include_grammar = has_response_format || (has_tools &&
((inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO && !trigger_marker.empty()) ||
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED));
if (include_grammar) {
data.grammar_lazy = !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO;
data.grammar = build_grammar([&](const common_grammar_builder & builder) {
foreach_function(inputs.tools, [&](const json & tool) {
const auto & function = tool.at("function");
auto schema = function.contains("parameters") ? function.at("parameters") : json::object();
builder.resolve_refs(schema);
});
if (has_response_format) {
auto schema = inputs.json_schema;
builder.resolve_refs(schema);
}
parser.build_grammar(builder, data.grammar_lazy);
});
// Set grammar triggers based on tool section markers (fall back to per-call markers)
if (data.grammar_lazy) {
data.grammar_triggers = {
{ COMMON_GRAMMAR_TRIGGER_TYPE_WORD, trigger_marker }
};
}
}
return data;
}
common_peg_arena autoparser::build_parser(const generation_params & inputs, const std::string & generation_prompt) const {
if (!analysis_complete) {
throw std::invalid_argument("Cannot call build_parser on autoparser without performing analysis first, call analyze_template(...)");
}
return build_chat_peg_parser([&](common_chat_peg_builder & p) {
parser_build_context ctx(p, inputs);
bool extract_reasoning = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;
ctx.extracting_reasoning = extract_reasoning && reasoning.mode != reasoning_mode::NONE;
ctx.content = &content;
ctx.reasoning = &reasoning;
bool has_tools = inputs.tools.is_array() && !inputs.tools.empty();
bool has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
// RADIANCE: tell the reasoning parser where a tool call starts, so an unclosed reasoning
// block cannot swallow one. This is the same marker the tool parsers below use to split
// content from calls, computed here because only this scope can see both analyzers.
if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE && jinja_caps.supports_tool_calls) {
const std::string & marker = !tools.format.section_start.empty()
? tools.format.section_start
: tools.format.per_call_start;
if (!marker.empty()) {
ctx.reasoning_terminators.push_back(marker);
}
}
// Build reasoning parser
ctx.reasoning_parser = reasoning.build_parser(ctx);
auto parser = p.eps();
bool pure_content = reasoning.mode == reasoning_mode::NONE;
if (has_response_format) {
auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)));
parser = ctx.reasoning_parser + p.space() + p.choice({
p.literal("```json") + p.space() + response_format + p.space() + p.literal("```"),
response_format
}) + p.end();
pure_content = false;
} else if (has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE && jinja_caps.supports_tool_calls) {
parser = tools.build_parser(ctx);
pure_content = false;
} else {
parser = content.build_parser(ctx);
}
return pure_content ? p.prefix(generation_prompt, reasoning.start) + parser : p.prefix(generation_prompt, reasoning.start) << parser;
});
}
common_peg_parser analyze_reasoning::build_parser(parser_build_context & ctx) const {
auto & p = ctx.p;
if (!ctx.extracting_reasoning) {
return p.eps();
}
if (mode == reasoning_mode::TAG_BASED || mode == reasoning_mode::TOOLS_ONLY) {
if (!end.empty()) {
const std::string trimmed_end = trim_whitespace(end);
// RADIANCE: `until(end)` runs to the END OF THE INPUT when the closing tag never
// arrives, so a reasoning block the model forgot to close swallowed the entire
// reply -- including a <tool_call> written from inside it, which meant the call was
// parsed as reasoning text and LOST. The turn then carried no tool call and no
// content, and an agent driving it simply stopped. Templates in the wild carry
// explicit self-heals for this shape, which is how we know models emit it.
//
// The repair is an ORDERED CHOICE whose first branch is GUARDED BY A LOOKAHEAD, so
// it can only win in the one situation it was written for. The unclosed branch runs
// `until` over both the closing tag and the tool-call opener and then REQUIRES, on a
// peek that consumes nothing, that what stopped it was the opener. So:
//
// reasoning </think> <tool_call> -> stops at </think>, peek fails, upstream rule
// reasoning <tool_call> -> stops at the opener, peek holds, call parsed
// reasoning, no tag, no call -> runs to EOF, peek fails, upstream rule
//
// The guard is what makes this additive: every reply that closes its reasoning block
// takes the second branch, which is upstream's rule byte for byte. It also keeps
// reasoning that merely MENTIONS an opener on the upstream path, because such a reply
// still has its closing tag and the peek therefore never fires.
//
// Ordering matters and is not free to swap: `until` returns "need more input" rather
// than failing when it reaches the end of the input, so a closed branch placed first
// would short-circuit before its required closing literal was ever checked, and the
// unclosed branch would be unreachable. That is the bug this comment cost.
if (!ctx.reasoning_terminators.empty()) {
std::vector<std::string> stops = ctx.reasoning_terminators;
stops.insert(stops.begin(), trimmed_end);
std::vector<common_peg_parser> openers;
openers.reserve(ctx.reasoning_terminators.size());
for (const auto & t : ctx.reasoning_terminators) {
openers.push_back(p.literal(t));
}
auto unclosed = p.reasoning(p.until_one_of(stops)) + p.peek(p.choice(openers));
auto closed = p.reasoning(p.until(trimmed_end)) + p.optspace(end);
if (!start.empty()) {
return p.optional(p.choice({ p.optspace(start) + unclosed,
p.optspace(start) + closed }));
}
return p.optional(p.choice({ unclosed, closed }));
}
if (!start.empty()) {
// Standard tag-based: optional(<think>reasoning</think>)
return p.optional(p.optspace(start) + p.reasoning(p.until(trimmed_end)) + p.optspace(end));
}
// Delimiter-style (empty start)
return p.optional(p.reasoning(p.until(trimmed_end)) + p.optspace(end));
}
}
return p.eps();
}
common_peg_parser analyze_content::build_parser(parser_build_context & ctx) const {
auto & p = ctx.p;
if (is_always_wrapped()) {
if (ctx.extracting_reasoning) {
return ctx.reasoning_parser + start + p.content(p.until(end)) + end + p.end();
}
return p.content(p.until(start)) + start + p.content(p.until(end)) + end + p.end();
}
return ctx.reasoning_parser + p.content(p.rest()) + p.end();
}
common_peg_parser analyze_content::build_optional_wrapped(parser_build_context & ctx) const {
auto & p = ctx.p;
if (is_always_wrapped()) {
return p.optional(start + p.content(p.until(end)) + end);
}
return p.eps();
}
common_peg_parser analyze_tools::build_parser(parser_build_context & ctx) const {
switch (format.mode) {
case tool_format::JSON_NATIVE:
return build_tool_parser_json_native(ctx);
case tool_format::TAG_WITH_JSON:
return build_tool_parser_tag_json(ctx);
case tool_format::TAG_WITH_TAGGED:
return build_tool_parser_tag_tagged(ctx);
default:
LOG_ERR("[ERROR] Template seems to support tool calls, but failed to determine tool format. Tool calling will not work properly. "
"Check for a fixed template for your model in the models/templates directory of your llama.cpp installation or "
"report an issue at https://github.com/ggml-org/llama.cpp/issues\n");
return ctx.p.eps();
}
}
common_peg_parser analyze_tools::build_tool_parser_json_native(parser_build_context & ctx) const {
auto & p = ctx.p;
const auto & inputs = ctx.inputs;
// Build effective field names with dot notation if function_field is set
std::string name_field = format.name_field;
std::string args_field = format.args_field;
if (!format.function_field.empty() && format.function_field != "function" &&
name_field.find('.') == std::string::npos) {
name_field = format.function_field + "." + name_field;
args_field = format.function_field + "." + args_field;
}
auto tools_parser = p.eps();
if (format.section_start.empty() && !format.per_call_start.empty()) {
auto single_tool_parser = p.standard_json_tools(
format.per_call_start, format.per_call_end, inputs.tools, inputs.parallel_tool_calls,
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED, name_field, args_field, format.tools_array_wrapped,
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order);
tools_parser = p.trigger_rule("tool-calls", p.one_or_more(single_tool_parser + p.space()));
} else {
tools_parser = p.standard_json_tools(
format.section_start, format.section_end, inputs.tools, inputs.parallel_tool_calls,
inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED, name_field, args_field, format.tools_array_wrapped,
format.fun_name_is_key, format.id_field, format.gen_id_field, format.parameter_order);
}
// Handle content wrappers if present
if (ctx.content && ctx.content->is_always_wrapped()) {
auto wrapped_content = ctx.content->build_optional_wrapped(ctx);
return ctx.reasoning_parser + wrapped_content + tools_parser + p.end();
}
std::string tool_start = "{";
if (!format.section_start.empty()) {
tool_start = format.section_start;
} else if (!format.per_call_start.empty()) {
tool_start = format.per_call_start;
}
return ctx.reasoning_parser + p.optional(p.content(p.until(tool_start))) + tools_parser + p.end();
}
common_peg_parser analyze_tools::build_func_parser(common_chat_peg_builder & p, const std::string & name,
const common_peg_parser & call_id_section, bool have_call_id,
const common_peg_parser & args,
std::optional<common_peg_parser> atomic_peek) const {
auto open = p.tool_open(function.name_prefix + p.tool_name(p.literal(name)) + function.name_suffix);
bool matched_atomic = false;
common_peg_parser func_parser = p.eps();
if (!function.name_suffix.empty()) {
func_parser = open + call_id_section + p.space() + args;
matched_atomic = true;
} else if (have_call_id) {
func_parser = p.atomic(open + call_id_section) + p.space() + args;
matched_atomic = true;
} else if (atomic_peek.has_value()) {
func_parser = p.atomic(open + call_id_section + p.space() + *atomic_peek) + args;
matched_atomic = true;
} else {
func_parser = open + call_id_section + p.space() + args;
}
if (!function.close.empty()) {
func_parser = func_parser + p.space() + p.tool_close(p.literal(function.close));
} else if (!format.per_call_end.empty()) {
// When there's no func_close but there is a per_call_end marker, use peek() to ensure
// we only emit tool_close when we can actually see the closing marker. This prevents
// premature closing during partial parsing when we've seen e.g. "</" which could be
// either "</tool_call>" (end) or "<arg_key>" prefix that failed to match.
func_parser = func_parser + p.tool_close(p.peek(p.literal(format.per_call_end)));
} else {
func_parser = func_parser + p.tool_close(p.space()); // force this to process tool closing callbacks in mapper
}
if (!matched_atomic) {
func_parser = p.atomic(func_parser);
}
return func_parser;
}
common_peg_parser analyze_tools::build_tool_parser_tag_json(parser_build_context & ctx) const {
auto & p = ctx.p;
const auto & inputs = ctx.inputs;
common_peg_parser tool_choice = p.choice();
foreach_function(inputs.tools, [&](const json & tool) {
const auto & func = tool.at("function");
std::string name = func.at("name");
const auto & schema = func.contains("parameters") ? func.at("parameters") : json::object();
// Build call_id parser based on position (if supported)
bool have_call_id = false;
common_peg_parser call_id_section = p.eps();
if (call_id.pos == call_id_position::BETWEEN_FUNC_AND_ARGS && !call_id.prefix.empty() &&
(!call_id.suffix.empty() || !arguments.start.empty())) {
if (!call_id.suffix.empty()) {
call_id_section = p.optional(call_id.prefix + p.tool_id(p.until(call_id.suffix))) + call_id.suffix;
} else {
call_id_section = p.optional(call_id.prefix + p.tool_id(p.until(arguments.start)));
}
have_call_id = true;
}
auto args_parser = p.tool_args(p.schema(p.json(), "tool-" + name + "-schema", schema));
if (!arguments.start.empty()) {
args_parser = p.literal(arguments.start) + args_parser;
}
if (!arguments.end.empty()) {
args_parser = args_parser + p.literal(arguments.end);
}
auto atomic_peek = !arguments.start.empty() ? std::optional(p.peek(p.literal(arguments.start))) : std::nullopt;
auto func_parser = build_func_parser(p, name, call_id_section, have_call_id, args_parser, atomic_peek);
tool_choice |= p.rule("tool-" + name, func_parser);
});
auto require_calls = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED;
common_peg_parser tool_calls = p.eps();
if (!format.per_call_start.empty()) {
auto wrapped_call = format.per_call_start + tool_choice + format.per_call_end;
if (inputs.parallel_tool_calls) {
tool_calls = p.trigger_rule("tool-call", wrapped_call + p.zero_or_more(p.space() + wrapped_call));
} else {
tool_calls = p.trigger_rule("tool-call", wrapped_call);
}
if (!format.section_start.empty()) {
tool_calls = p.trigger_rule("tool-calls",
p.literal(format.section_start) + p.space() + tool_calls + p.space() +
(format.section_end.empty() ? p.end() : p.literal(format.section_end)));
}
} else {
std::string separator = ", "; // Default
if (inputs.parallel_tool_calls) {
tool_calls = p.trigger_rule("tool-call", format.section_start + tool_choice +
p.zero_or_more(separator + tool_choice) + format.section_end);
} else {
tool_calls = p.trigger_rule("tool-call", format.section_start + tool_choice + format.section_end);
}
}
if (!require_calls) {
tool_calls = p.optional(tool_calls);
}
std::string trigger_marker = !format.section_start.empty() ? format.section_start : format.per_call_start;
auto content_before_tools = trigger_marker.empty() ? p.eps() : p.until(trigger_marker);
/* RADIANCE: and anything AFTER the last call is content too. p.end() immediately after the
* calls means a model that signs off -- "Created the file." -- fails the whole parse for it,
* which is the same trap as the one above with the ends swapped. */
return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls +
p.optional(p.content(p.rest())) + p.end();
}
common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_context & ctx) const {
auto & p = ctx.p;
const auto & inputs = ctx.inputs;
auto until_suffix = p.rule("until-suffix", p.until(arguments.value_suffix));
common_peg_parser tool_choice = p.choice();
foreach_function(inputs.tools, [&](const json & tool) {
const auto & func = tool.at("function");
std::string name = func.at("name");
auto params = func.contains("parameters") ? func.at("parameters") : json::object();
const auto & properties = params.contains("properties") ? params.at("properties") : json::object();
std::set<std::string> required;
if (params.contains("required")) {
params.at("required").get_to(required);
}
auto schema_info = common_schema_info();
schema_info.resolve_refs(params);
// Build parser for each argument, separating required and optional
std::vector<common_peg_parser> required_parsers;
std::vector<common_peg_parser> optional_parsers;
for (const auto & [param_name, param_schema] : properties.items()) {
bool is_required = required.find(param_name) != required.end();
/* RADIANCE: AN OPTIONAL ARGUMENT NO VALUE SATISFIES IS ONE NO CALL WRITES -- an
* Arktype "never", exported as `{"not": {}}` (oh-my-pi's `task` tool declares its batch
* form's `model` so). It gets no arm: a schema-checked arm for it is a grammar for a
* value that does not exist, and the converter refuses to build one. A model that
* writes it anyway reaches the undeclared-argument arm below, as any name outside the
* schema does, and the tool says what is wrong. Required, it goes through the schema
* and is refused there by name. */
if (!is_required && schema_info.unsatisfiable(param_schema)) {
continue;
}
/* RADIANCE: A NON-STRING ARGUMENT THAT IS NOT VALID JSON IS STILL AN ARGUMENT.
*
* An array or object parameter is matched by a schema-constrained JSON parser, and
* models do not reliably write JSON inside an XML tag. MiniCPM5 writes Python:
* `<param name="edits">[{'oldText': 'a', 'newText': 'b'}]</param>`. The JSON parser
* cannot begin on a single quote, so the argument does not match, the call does not
* match, and p.end() makes that the whole reply -- which comes back as prose with
* the tags in it. The model reads that as the tool rejecting its call and tries
* again, differently and just as fruitlessly; in one session it went round four
* times, and once rewrote the call with the arguments reordered to appease it.
*
* Strict JSON is still tried FIRST, so nothing that parses today parses differently.
* The fallback takes the value the way a string argument takes it -- as the text up
* to `</param>`, which is what actually delimits it in this format -- and the mapper
* already normalises a Python-style container to JSON from there
* (normalize_container_value in chat-peg-parser.cpp). What is given up is schema
* VALIDATION of the argument, and a mistyped argument reaching the tool as a mistyped
* argument is strictly better than a correct call reaching the user as prose. */
common_peg_parser value_parser = p.choice();
if (schema_info.resolves_to_string(param_schema)) {
value_parser = p.tool_arg_string_value(until_suffix);
} else {
value_parser |= p.tool_arg_json_value(p.schema(
p.json(), "tool-" + name + "-arg-" + param_name + "-schema",
param_schema, false)) + p.space();
value_parser |= p.tool_arg_json_value(until_suffix);
}
auto arg =
p.tool_arg(p.tool_arg_open(arguments.name_prefix + p.tool_arg_name(p.literal(param_name)) +
arguments.name_suffix) +
arguments.value_prefix + value_parser +
p.tool_arg_close(p.literal(arguments.value_suffix)));
auto named_arg = p.rule("tool-" + name + "-arg-" + param_name, arg);
if (is_required) {
required_parsers.push_back(named_arg);
} else {
optional_parsers.push_back(named_arg);
}
}
/* RADIANCE: A NAMED ARGUMENT CARRIES ITS OWN NAME, SO ITS POSITION MEANS NOTHING.
*
* Required arguments were required IN SCHEMA ORDER. This format writes them as
* `<param name="path">..</param><param name="content">..</param>` -- the name is right
* there in the tag -- and a model emits them in whatever order it composed them, which
* for a write is very often the content first, because that is the part it was thinking
* about. The sequence then does not match, and since the rule ends in p.end() the failure
* is TOTAL: the call comes back to the client as prose with the tags still in it, which
* looks exactly like a model that cannot call tools.
*
* Every argument is accepted in any order here, required and optional alike. What the
* grammar gives up -- checking that each required argument appears exactly once -- was
* never its job: a call missing one is a bad call, and arriving at the tool AS a bad call
* says so, where arriving as prose says nothing at all. */
common_peg_parser any_arg = p.choice();
for (const auto & req : required_parsers) {
any_arg |= req;
}
for (const auto & opt : optional_parsers) {
any_arg |= opt;
}
/* RADIANCE: AN ARGUMENT THE SCHEMA DOES NOT DECLARE MUST NOT TAKE THE REPLY DOWN WITH IT.
*
* Every arm above matches its parameter name as a LITERAL, so a name outside the schema
* matches nothing, the call matches nothing, and p.end() makes that the whole reply --
* which comes back to the caller as prose with the XML in it. Observed on MiniCPM5-2B
* calling a `read` tool whose only parameter is `path`:
*
* <function name="read"><param name="action">read</param></function>
*
* one hallucinated argument name, and the turn was lost. The model then reads its own
* call echoed back as text, concludes the tool is broken, and rewrites it.
*
* Tried LAST, so every declared name still binds to its own schema-checked arm and
* nothing that parses today parses differently. The value is taken the way a string
* argument takes it -- the text up to the value suffix, which is what delimits it in
* this format. What is given up is knowing that the argument was undeclared; the TOOL
* gets to say so, which it can do properly, and which a reply that never arrives cannot.
* Same argument as the non-JSON container fallback above. */
/* WHAT ENDS THE NAME IS NOT ALWAYS `name_suffix`. This format decomposes
* `<param name="path">v</param>` as prefix `<param name="`, name_suffix EMPTY and
* value_prefix `">` -- so a generic name runs until value_prefix here, and the first
* cut of this arm guarded on `!name_suffix.empty()` and silently never built itself. */
const std::string & name_end =
arguments.name_suffix.empty() ? arguments.value_prefix : arguments.name_suffix;
if (!arguments.name_prefix.empty() && !name_end.empty() &&
!arguments.value_suffix.empty()) {
auto unknown_arg =
p.tool_arg(p.tool_arg_open(arguments.name_prefix +
p.tool_arg_name(p.until(name_end)) +
arguments.name_suffix) +
arguments.value_prefix + p.tool_arg_string_value(until_suffix) +
p.tool_arg_close(p.literal(arguments.value_suffix)));
any_arg |= p.rule("tool-" + name + "-arg-undeclared", unknown_arg);
}
common_peg_parser args_seq = p.eps();
if (!required_parsers.empty()) {
args_seq = any_arg + p.repeat(p.space() + any_arg, 0, -1);
} else if (!optional_parsers.empty()) {
args_seq = args_seq + p.repeat(p.space() + any_arg, 0, -1);
}
if (!arguments.start.empty()) {
args_seq = p.literal(arguments.start) + args_seq;
}
if (!arguments.end.empty()) {
args_seq = args_seq + p.literal(arguments.end);
}
// Build call_id parser based on position (if supported)
common_peg_parser call_id_section = p.eps();
bool have_call_id = false;
if (call_id.pos == call_id_position::BETWEEN_FUNC_AND_ARGS && !call_id.prefix.empty() &&
(!call_id.suffix.empty() || !arguments.start.empty())) {
have_call_id = true;
if (!call_id.suffix.empty()) {
call_id_section = p.optional(call_id.prefix + p.tool_id(p.until(call_id.suffix)) + call_id.suffix);
} else {
call_id_section = p.optional(call_id.prefix + p.tool_id(p.until(arguments.start)));
}
}
// Only peek for an arg tag when there are required args that must follow.
// When all args are optional, the model may emit no arg tags at all (#20650).
auto atomic_peek = (!arguments.name_prefix.empty() && !required_parsers.empty()) ?
std::optional(p.peek(p.literal(arguments.name_prefix))) : std::nullopt;
auto func_parser = build_func_parser(p, name, call_id_section, have_call_id, args_seq, atomic_peek);
tool_choice |= p.rule("tool-" + name, func_parser);
});
auto require_tools = inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED;
/* RADIANCE: what opens a call, and therefore what content is read up to. See the return
* statement; computed here because the between-calls rule below needs it too. */
std::string trigger_marker = !format.section_start.empty() ? format.section_start
: !format.per_call_start.empty() ? format.per_call_start
: function.name_prefix;
common_peg_parser tool_calls = p.eps();
if (!format.per_call_start.empty()) {
auto wrapped_call = format.per_call_start + p.space() + tool_choice + p.space() + format.per_call_end;
if (inputs.parallel_tool_calls) {
tool_calls = p.trigger_rule("tool-call", wrapped_call + p.zero_or_more(p.space() + wrapped_call) + p.space());
} else {
tool_calls = p.trigger_rule("tool-call", wrapped_call + p.space());
}
if (!format.section_start.empty()) {
tool_calls = p.trigger_rule("tool-calls",
p.literal(format.section_start) + p.space() + tool_calls + p.space() +
(format.section_end.empty() ? p.end() : p.literal(format.section_end) + p.space()));
}
} else {
/* RADIANCE: A TAGGED CALL IS SELF-DELIMITING, SO THE SEPARATOR IS WHITESPACE.
*
* This used a literal ", " -- the separator of a JSON ARRAY of calls -- for a format
* whose calls are tags. MiniCPM5-2B writes
* `<function name="ls">..</function>\n<function name="bash">..</function>`, and the
* second call was required to begin with a comma and a space. It never does, so the
* rule failed -- and because the whole thing ends in p.end(), the failure is not "one
* call and some text", it is NO MATCH AT ALL: every reply with two calls in it came back
* as raw prose with the reasoning and the tags still in it. One call parsed, two never.
*
* A tagged call opens with its own name prefix and closes with its own close, so nothing
* between them is needed to tell one from the next. p.space() accepts the newline these
* models put there and the nothing that a template writing them adjacently produces. */
/* RADIANCE: and a model narrates BETWEEN calls too -- "Let me look at the tree." then a
* call, "Now the tests." then another. Only whitespace was allowed between them. */
common_peg_parser next_call =
p.space() + (trigger_marker.empty() ? p.eps() : p.optional(p.content(p.until(trigger_marker)))) +
tool_choice;
if (inputs.parallel_tool_calls) {
tool_calls = p.trigger_rule("tool-call", format.section_start + p.space() + tool_choice +
p.zero_or_more(next_call) + p.space() +
format.section_end);
} else {
tool_calls = p.trigger_rule(
"tool-call", format.section_start + p.space() + tool_choice + p.space() + format.section_end);
}
}
if (!require_tools) {
tool_calls = p.optional(tool_calls);
}
/* RADIANCE: WITH NO SECTION OR PER-CALL MARKER, NOTHING WAS ALLOWED BEFORE THE CALL.
*
* `content_before_tools` is what lets a model say something and THEN call a tool. It is
* driven by the section or per-call opener, and a format with neither -- this one -- got
* p.eps(), which permits no content at all. So a reply that opens with a sentence ("The
* workspace is empty. I will create a Tic Tac Toe implementation.") and then makes a
* perfectly well-formed call does not match, and p.end() turns that into a whole-parse
* failure: the call comes back as prose.
*
* What opens a call in a tagged format is the function name prefix, `<function name="`, so
* that is the marker to read up to. It is only a fallback -- a format that really does have
* a section or per-call opener still uses it, because that one starts earlier in the text. */
auto content_before_tools = trigger_marker.empty() ? p.eps() : p.until(trigger_marker);
return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls + p.end();
}
} // namespace autoparser