Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,17 @@
|
||||
--- a/src/unicode.cpp
|
||||
+++ b/src/unicode.cpp
|
||||
@@ -58,6 +58,14 @@
|
||||
throw std::invalid_argument("invalid character");
|
||||
}
|
||||
auto result = ((utf8[offset + 0] & 0x07) << 18) | ((utf8[offset + 1] & 0x3f) << 12) | ((utf8[offset + 2] & 0x3f) << 6) | (utf8[offset + 3] & 0x3f);
|
||||
+ // RADIANCE: lead bytes 0xF5..0xF7 decode above U+10FFFF, which unicode_cpt_to_utf8()
|
||||
+ // then refuses with a throw that nothing catches -- so four arbitrary bytes in a prompt
|
||||
+ // terminate the process. Rejecting here instead routes it through the invalid_argument
|
||||
+ // that unicode_cpts_from_utf8() already turns into U+FFFD. Only the out-of-range case
|
||||
+ // changes; every sequence upstream accepts still decodes to the same codepoint.
|
||||
+ if (result > 0x10ffff) {
|
||||
+ throw std::invalid_argument("invalid character");
|
||||
+ }
|
||||
offset += 4;
|
||||
return result;
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
|
||||
index db3a6cc..ed895b5 100644
|
||||
--- a/common/chat-auto-parser-generator.cpp
|
||||
+++ b/common/chat-auto-parser-generator.cpp
|
||||
@@ -121,13 +121,25 @@ common_peg_arena autoparser::build_parser(const generation_params & inputs, cons
|
||||
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 has_tools = inputs.tools.is_array() && !inputs.tools.empty();
|
||||
- bool has_response_format = inputs.json_schema.is_object() && !inputs.json_schema.empty();
|
||||
bool pure_content = reasoning.mode == reasoning_mode::NONE;
|
||||
|
||||
if (has_response_format) {
|
||||
@@ -156,12 +168,57 @@ common_peg_parser analyze_reasoning::build_parser(parser_build_context & ctx) co
|
||||
|
||||
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(trim_whitespace(end))) + p.optspace(end));
|
||||
+ 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(trim_whitespace(end))) + p.optspace(end));
|
||||
+ return p.optional(p.reasoning(p.until(trimmed_end)) + p.optspace(end));
|
||||
}
|
||||
}
|
||||
|
||||
diff --git a/common/chat-auto-parser.h b/common/chat-auto-parser.h
|
||||
index 7858f65..478edef 100644
|
||||
--- a/common/chat-auto-parser.h
|
||||
+++ b/common/chat-auto-parser.h
|
||||
@@ -228,6 +228,11 @@ struct parser_build_context {
|
||||
const analyze_reasoning * reasoning = nullptr;
|
||||
const analyze_content * content = nullptr;
|
||||
|
||||
+ // RADIANCE: markers that end an UNCLOSED reasoning block, in addition to its closing tag --
|
||||
+ // in practice the tool-call opener. Empty unless this turn can call tools. See the comment
|
||||
+ // in analyze_reasoning::build_parser for what goes wrong without it.
|
||||
+ std::vector<std::string> reasoning_terminators;
|
||||
+
|
||||
parser_build_context(common_chat_peg_builder & p, const generation_params & inputs);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
--- a/common/json-schema-to-grammar.cpp
|
||||
+++ b/common/json-schema-to-grammar.cpp
|
||||
@@ -343,13 +343,15 @@ private:
|
||||
rules.push_back(visit(alt_schemas[i], name + (name.empty() ? "alternative-" : "-") + std::to_string(i)));
|
||||
}
|
||||
return string_join(rules, " | ");
|
||||
}
|
||||
|
||||
std::string _visit_pattern(const std::string & pattern, const std::string & name) {
|
||||
- if (!(pattern.front() == '^' && pattern.back() == '$')) {
|
||||
+ // RADIANCE: front()/back() on an empty string is UB, and `pattern` is client data straight
|
||||
+ // off the wire. The size test has to come first.
|
||||
+ if (pattern.size() < 2 || !(pattern.front() == '^' && pattern.back() == '$')) {
|
||||
_errors.push_back("Pattern must start with '^' and end with '$'");
|
||||
return "";
|
||||
}
|
||||
std::string sub_pattern = pattern.substr(1, pattern.length() - 2);
|
||||
std::unordered_map<std::string, std::string> sub_rule_ids;
|
||||
|
||||
@@ -407,12 +409,18 @@ private:
|
||||
results.push_back(to_rule(item));
|
||||
}
|
||||
return std::make_pair(string_join(results, " "), false);
|
||||
};
|
||||
|
||||
while (i < length) {
|
||||
+ // RADIANCE: every arm below must consume at least one byte. The literal arm does not when
|
||||
+ // it meets a byte that is in NON_LITERAL_SET but that no arm above claims -- a
|
||||
+ // stray ']' or '}' -- so it breaks out with `literal` empty, nothing is pushed,
|
||||
+ // and the loop reconsiders the same byte forever. `pattern` is client data, so
|
||||
+ // that is a one-string denial of service. Checked at the bottom of the body.
|
||||
+ const size_t progress_at = i;
|
||||
char c = sub_pattern[i];
|
||||
if (c == '.') {
|
||||
seq.emplace_back(get_dot(), false);
|
||||
i++;
|
||||
} else if (c == '(') {
|
||||
i++;
|
||||
@@ -462,12 +470,17 @@ private:
|
||||
i++;
|
||||
seq.emplace_back(square_brackets, false);
|
||||
} else if (c == '|') {
|
||||
seq.emplace_back("|", false);
|
||||
i++;
|
||||
} else if (c == '*' || c == '+' || c == '?') {
|
||||
+ if (seq.empty()) {
|
||||
+ // RADIANCE: a leading quantifier, "^*$". back() on an empty vector is UB.
|
||||
+ _errors.push_back("Quantifier with nothing to repeat");
|
||||
+ break;
|
||||
+ }
|
||||
seq.back() = std::make_pair(to_rule(seq.back()) + c, false);
|
||||
i++;
|
||||
} else if (c == '{') {
|
||||
std::string curly_brackets = std::string(1, c);
|
||||
i++;
|
||||
while (i < length && sub_pattern[i] != '}') {
|
||||
@@ -496,12 +509,17 @@ private:
|
||||
}
|
||||
}
|
||||
} catch (const std::invalid_argument & e) {
|
||||
_errors.push_back("Invalid number in curly brackets");
|
||||
return std::make_pair("", false);
|
||||
}
|
||||
+ if (seq.empty()) {
|
||||
+ // RADIANCE: a leading "{n,m}" has nothing before it to repeat; back() would be UB.
|
||||
+ _errors.push_back("Quantifier with nothing to repeat");
|
||||
+ break;
|
||||
+ }
|
||||
auto &last = seq.back();
|
||||
auto &sub = last.first;
|
||||
auto sub_is_literal = last.second;
|
||||
|
||||
if (!sub_is_literal) {
|
||||
std::string & sub_id = sub_rule_ids[sub];
|
||||
@@ -545,12 +563,16 @@ private:
|
||||
}
|
||||
}
|
||||
if (!literal.empty()) {
|
||||
seq.emplace_back(literal, true);
|
||||
}
|
||||
}
|
||||
+ if (i == progress_at) {
|
||||
+ _errors.push_back("Unsupported pattern syntax");
|
||||
+ break;
|
||||
+ }
|
||||
}
|
||||
return join_seq();
|
||||
};
|
||||
return _add_rule(name, "\"\\\"\" (" + to_rule(transform()) + ") \"\\\"\" space");
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
--- a/common/json-schema-to-grammar.cpp
|
||||
+++ b/common/json-schema-to-grammar.cpp
|
||||
@@ -276,12 +276,24 @@ static std::regex GRAMMAR_LITERAL_ESCAPE_RE("[\r\n\"\\\\]");
|
||||
static std::regex GRAMMAR_RANGE_LITERAL_ESCAPE_RE("[\r\n\"\\]\\-\\\\]");
|
||||
static std::unordered_map<char, std::string> GRAMMAR_LITERAL_ESCAPES = {
|
||||
{'\r', "\\r"}, {'\n', "\\n"}, {'"', "\\\""}, {'-', "\\-"}, {']', "\\]"}, {'\\', "\\\\"}
|
||||
};
|
||||
|
||||
static std::unordered_set<char> NON_LITERAL_SET = {'|', '.', '(', ')', '[', ']', '{', '}', '*', '+', '?'};
|
||||
+
|
||||
+// RADIANCE: the escapes GBNF can actually spell. Anything else in a pattern is refused rather
|
||||
+// than copied into a grammar that will not load. See the use site in _visit_pattern.
|
||||
+static inline bool is_gbnf_escape(char c) {
|
||||
+ switch (c) {
|
||||
+ case 'x': case 'u': case 'U': case 't': case 'r': case 'n':
|
||||
+ case '\\': case '"': case '[': case ']':
|
||||
+ return true;
|
||||
+ default:
|
||||
+ return false;
|
||||
+ }
|
||||
+}
|
||||
static std::unordered_set<char> ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS = {'^', '$', '.', '[', ']', '(', ')', '|', '{', '}', '*', '+', '?'};
|
||||
|
||||
static std::string replacePattern(const std::string & input, const std::regex & regex, const std::function<std::string(const std::smatch &)> & replacement) {
|
||||
std::smatch match;
|
||||
std::string result;
|
||||
|
||||
@@ -545,12 +557,24 @@ private:
|
||||
char next = sub_pattern[i + 1];
|
||||
if (ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.find(next) != ESCAPED_IN_REGEXPS_BUT_NOT_IN_LITERALS.end()) {
|
||||
i++;
|
||||
literal += sub_pattern[i];
|
||||
i++;
|
||||
} else {
|
||||
+ // RADIANCE: GBNF knows \x \u \U \t \r \n \\ \" \[ \] and nothing
|
||||
+ // else. Copying an escape it cannot spell (\d \w \s \b \/ \-, a
|
||||
+ // backreference) produces a grammar that returns success here and
|
||||
+ // then fails to LOAD, which the caller sees as an internal error
|
||||
+ // on a schema we told it was fine.
|
||||
+ if (!is_gbnf_escape(next)) {
|
||||
+ _errors.push_back(
|
||||
+ std::string("Unsupported regex escape '\\") + next +
|
||||
+ "' in a pattern: GBNF cannot spell it, so the grammar "
|
||||
+ "would not load");
|
||||
+ return std::make_pair(std::string(), true);
|
||||
+ }
|
||||
literal += sub_pattern.substr(i, 2);
|
||||
i += 2;
|
||||
}
|
||||
} else if (sub_pattern[i] == '"') {
|
||||
literal += "\\\"";
|
||||
i++;
|
||||
@@ -791,12 +815,21 @@ public:
|
||||
for (auto & x : n) {
|
||||
visit_refs(x);
|
||||
}
|
||||
} else if (n.is_object()) {
|
||||
if (n.contains("$ref")) {
|
||||
std::string ref = n["$ref"];
|
||||
+ // RADIANCE: a sampler that reaches the network to decide what tokens are legal
|
||||
+ // is not a sampler we will ship. Upstream fetches through an injected callback
|
||||
+ // which the public entry point then stubs out to return null -- so a remote
|
||||
+ // $ref silently degrades into "accepts any object". Refuse, and fetch nothing.
|
||||
+ if (ref.rfind("http://", 0) == 0 || ref.rfind("https://", 0) == 0) {
|
||||
+ throw std::runtime_error(
|
||||
+ "remote $ref is not supported: '" + ref + "'. Inline the referenced "
|
||||
+ "schema; this converter does not fetch over the network.");
|
||||
+ }
|
||||
if (_refs.find(ref) == _refs.end()) {
|
||||
json target;
|
||||
if (ref.find("https://") == 0) {
|
||||
std::string base_url = ref.substr(0, ref.find('#'));
|
||||
auto it = _refs.find(base_url);
|
||||
if (it != _refs.end()) {
|
||||
@@ -860,12 +893,22 @@ public:
|
||||
|
||||
std::string visit(const json & schema, const std::string & name) {
|
||||
json schema_type = schema.contains("type") ? schema["type"] : json();
|
||||
std::string schema_format = schema.contains("format") ? schema["format"].get<std::string>() : "";
|
||||
std::string rule_name = is_reserved_name(name) ? name + "-" : name.empty() ? "root" : name;
|
||||
|
||||
+ // RADIANCE: "not" has no case below, so it falls through to a rule that accepts anything
|
||||
+ // -- a constraint the caller asked for, did not get, and is not told about. Complementing
|
||||
+ // a regular language is representable but the blowup is real; refusing beats pretending.
|
||||
+ if (schema.is_object() && schema.contains("not")) {
|
||||
+ _errors.push_back("Unsupported schema keyword \"not\": this converter cannot "
|
||||
+ "complement a grammar, and accepting the schema without it would "
|
||||
+ "silently drop the constraint");
|
||||
+ return "";
|
||||
+ }
|
||||
+
|
||||
if (schema.contains("$ref")) {
|
||||
return _add_rule(rule_name, _resolve_ref(schema["$ref"]));
|
||||
}
|
||||
if (schema.contains("oneOf") || schema.contains("anyOf")) {
|
||||
std::vector<json> alt_schemas = schema.contains("oneOf") ? schema["oneOf"].get<std::vector<json>>() : schema["anyOf"].get<std::vector<json>>();
|
||||
return _add_rule(rule_name, _generate_union_rule(name, alt_schemas));
|
||||
@@ -0,0 +1,46 @@
|
||||
diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp
|
||||
index 12e747d..111acd0 100644
|
||||
--- a/common/chat-peg-parser.cpp
|
||||
+++ b/common/chat-peg-parser.cpp
|
||||
@@ -36,6 +36,31 @@ static std::string_view trim(std::string_view sv) {
|
||||
return trim_trailing_space(trim_leading_space(sv, 1));
|
||||
}
|
||||
|
||||
+// RADIANCE: the delimiter around an XML argument value is a NEWLINE, not "whitespace". The
|
||||
+// template writes <parameter=old_string>\n return a + b\n</parameter>, and exactly the first
|
||||
+// and last newline are punctuation -- everything between them, INCLUDING the indentation, is the
|
||||
+// value the model meant to send. Stripping "one leading whitespace character" eats the first
|
||||
+// column of every indented hunk, so an agent's exact-match edit never applies and the model that
|
||||
+// wrote a perfectly good call gets the blame. Strip the delimiter and nothing else.
|
||||
+static std::string_view strip_one_leading_newline(std::string_view sv) {
|
||||
+ if (!sv.empty() && sv.front() == '\n') {
|
||||
+ sv.remove_prefix(1);
|
||||
+ } else if (sv.size() >= 2 && sv[0] == '\r' && sv[1] == '\n') {
|
||||
+ sv.remove_prefix(2);
|
||||
+ }
|
||||
+ return sv;
|
||||
+}
|
||||
+
|
||||
+static std::string_view strip_one_trailing_newline(std::string_view sv) {
|
||||
+ if (!sv.empty() && sv.back() == '\n') {
|
||||
+ sv.remove_suffix(1);
|
||||
+ if (!sv.empty() && sv.back() == '\r') {
|
||||
+ sv.remove_suffix(1);
|
||||
+ }
|
||||
+ }
|
||||
+ return sv;
|
||||
+}
|
||||
+
|
||||
// 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) {
|
||||
@@ -338,7 +363,8 @@ void common_chat_peg_mapper::map(const common_peg_ast_node & node) {
|
||||
}
|
||||
|
||||
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_content =
|
||||
+ std::string(strip_one_trailing_newline(strip_one_leading_newline(node.text)));
|
||||
|
||||
std::string value_to_add;
|
||||
if (value_content.empty() && is_arg_string_value) {
|
||||
@@ -0,0 +1,62 @@
|
||||
diff --git a/common/jinja/value.cpp b/common/jinja/value.cpp
|
||||
index 0b79098..16b8bbf 100644
|
||||
--- a/common/jinja/value.cpp
|
||||
+++ b/common/jinja/value.cpp
|
||||
@@ -261,6 +261,44 @@ static value tojson(const func_args & args) {
|
||||
return mk_val<value_string>(json_str);
|
||||
}
|
||||
|
||||
+/* jinja2's min()/max() over a sequence: the smallest (largest) ITEM, compared by `attribute`
|
||||
+ * where one is given, and undefined for an empty sequence. `case_sensitive` is accepted and
|
||||
+ * ignored, exactly as `sort` above it does. */
|
||||
+template<value_compare_op op>
|
||||
+static value minmax_fn(const func_args & args) {
|
||||
+ args.ensure_count(1, 3);
|
||||
+ if (!is_val<value_array>(args.get_pos(0))) {
|
||||
+ throw raised_exception("min/max: first argument must be an array");
|
||||
+ }
|
||||
+ value val = args.get_pos(0);
|
||||
+ value attribute = args.get_kwarg_or_pos("attribute", 2);
|
||||
+ const bool attr_is_int = is_val<value_int>(attribute);
|
||||
+ const int64_t attr_int = attr_is_int ? attribute->as_int() : 0;
|
||||
+ const std::vector<value> arr = val->as_array(); // copy, as sort does
|
||||
+ if (arr.empty()) {
|
||||
+ return mk_val<value_undefined>();
|
||||
+ }
|
||||
+ auto key = [&](const value & v) -> value {
|
||||
+ if (attribute->is_undefined()) {
|
||||
+ return v;
|
||||
+ }
|
||||
+ if (attr_is_int && is_val<value_array>(v)) {
|
||||
+ return v->at(attr_int);
|
||||
+ }
|
||||
+ if (!attr_is_int && is_val<value_object>(v)) {
|
||||
+ return v->at(attribute);
|
||||
+ }
|
||||
+ throw raised_exception("min/max: unsupported object attribute comparison on " + v->type());
|
||||
+ };
|
||||
+ value best = arr[0];
|
||||
+ for (size_t i = 1; i < arr.size(); ++i) {
|
||||
+ if (value_compare(key(arr[i]), key(best), op)) {
|
||||
+ best = arr[i];
|
||||
+ }
|
||||
+ }
|
||||
+ return best;
|
||||
+}
|
||||
+
|
||||
template<bool is_reject>
|
||||
static value selectattr(const func_args & args) {
|
||||
args.ensure_count(2, 4);
|
||||
@@ -1082,6 +1120,12 @@ const func_builtins & value_array_t::get_builtins() const {
|
||||
});
|
||||
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(arr)) : mk_val<value_array>(std::move(arr));
|
||||
}},
|
||||
+ /* RADIANCE: upstream has sort but neither min nor max, and a template that uses one
|
||||
+ * throws mid-render -- which the capability probe SWALLOWS, so the model is reported as
|
||||
+ * having no tool support at all instead of the engine being reported as short a filter.
|
||||
+ * MiniCPM5-2B's tool block is exactly that template. */
|
||||
+ {"min", minmax_fn<value_compare_op::lt>},
|
||||
+ {"max", minmax_fn<value_compare_op::gt>},
|
||||
{"reverse", [](const func_args & args) -> value {
|
||||
args.ensure_vals<value_array>();
|
||||
value val = args.get_pos(0);
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
diff --git a/common/chat-diff-analyzer.cpp b/common/chat-diff-analyzer.cpp
|
||||
index 0875c53..695765a 100644
|
||||
--- a/common/chat-diff-analyzer.cpp
|
||||
+++ b/common/chat-diff-analyzer.cpp
|
||||
@@ -25,6 +25,10 @@ static const std::string FUN_FIRST = "FFF_FIRST_FUN_F";
|
||||
static const std::string FUN_SECOND = "SSS_SECOND_FUN_S";
|
||||
static const std::string ARG_FIRST = "AA_ARG_FST_AA";
|
||||
static const std::string ARG_SECOND = "BB_ARG_SND_BB";
|
||||
+/* RADIANCE: the value the one- and two-argument probes give ARG_FIRST. Named so the split in
|
||||
+ * extract_argument_separator can find it rather than repeating the literal. */
|
||||
+static const std::string ARG_FIRST_VALUE = "XXXX";
|
||||
+static const std::string ARG_SECOND_VALUE = "YYYY";
|
||||
static const std::string USER_MSG = "U_USER_MSG Hello END_U";
|
||||
static const std::string USER_MSG_TWO = "V_USER_MSG Hello END_V";
|
||||
static const std::string ASSISTANT_MSG = "A_ASST_MSG I can help END_A";
|
||||
@@ -261,6 +265,7 @@ void autoparser::analyze_template(const common_chat_template & tmpl) {
|
||||
LOG_DBG("arg_name_suffix: '%s'\n", tools.arguments.name_suffix.c_str());
|
||||
LOG_DBG("arg_value_prefix: '%s'\n", tools.arguments.value_prefix.c_str());
|
||||
LOG_DBG("arg_value_suffix: '%s'\n", tools.arguments.value_suffix.c_str());
|
||||
+ LOG_DBG("arg_separator: '%s'\n", tools.arguments.separator.c_str()); /* RADIANCE */
|
||||
LOG_DBG("name_field: '%s'\n", tools.format.name_field.c_str());
|
||||
LOG_DBG("args_field: '%s'\n", tools.format.args_field.c_str());
|
||||
LOG_DBG("id_field: '%s'\n", tools.format.id_field.c_str());
|
||||
@@ -1355,6 +1360,80 @@ void analyze_tools::extract_argument_separator() {
|
||||
std::string separator = until_common_prefix(diff.right, ARG_FIRST, ARG_SECOND);
|
||||
arguments.separator = separator;
|
||||
}
|
||||
+
|
||||
+ /* RADIANCE: THE PER-ARGUMENT SUFFIX AND THE CALL CLOSE CAME OUT AS ONE STRING.
|
||||
+ *
|
||||
+ * analyze_arguments() takes everything after the argument value as `value_suffix` and then
|
||||
+ * trims `function.close`, `per_call_end` or `section_end` off it. A template that declares
|
||||
+ * none of the three has nothing to cut against. MiniCPM5-2B is one: its calls are
|
||||
+ * `<function name="F"><param name="A">V</param></function>`, so the suffix came out
|
||||
+ * `</param></function><|im_end|>\n` with an EMPTY close, and two things then cannot parse --
|
||||
+ * a call carrying a SECOND argument, because the suffix closes the whole call, and a call
|
||||
+ * carrying one, because a generated turn ends at `<|im_end|>` and never carries the newline
|
||||
+ * the template writes BETWEEN turns.
|
||||
+ *
|
||||
+ * The boundary is right here, in the render this function already has. Between the first
|
||||
+ * argument's value and the second argument's name marker is exactly the per-argument suffix.
|
||||
+ * Nothing is guessed: it is measured off a two-argument render, and every step declines
|
||||
+ * rather than assuming if the markers do not line up. */
|
||||
+ if (format.mode == tool_format::TAG_WITH_TAGGED && function.close.empty() &&
|
||||
+ !arguments.name_prefix.empty() && !arguments.value_suffix.empty()) {
|
||||
+ const std::string two = diff.prefix + diff.right + diff.suffix;
|
||||
+ const size_t v1 = two.find(ARG_FIRST_VALUE);
|
||||
+ const size_t a2 = v1 == std::string::npos ? std::string::npos : two.find(ARG_SECOND, v1);
|
||||
+ const size_t npx = a2 == std::string::npos
|
||||
+ ? std::string::npos : two.rfind(arguments.name_prefix, a2);
|
||||
+ if (npx != std::string::npos && npx >= v1 + ARG_FIRST_VALUE.size()) {
|
||||
+ const std::string per_arg = two.substr(v1 + ARG_FIRST_VALUE.size(),
|
||||
+ npx - (v1 + ARG_FIRST_VALUE.size()));
|
||||
+ const std::string tail = arguments.value_suffix;
|
||||
+ if (!per_arg.empty() && tail.size() > per_arg.size() &&
|
||||
+ tail.compare(0, per_arg.size(), per_arg) == 0) {
|
||||
+ arguments.value_suffix = per_arg;
|
||||
+ function.close = trim_trailing_whitespace(tail.substr(per_arg.size()));
|
||||
+
|
||||
+ /* AND THE CLOSE FROM A TWO-CALL RENDER, for the same reason and by the same
|
||||
+ * method. The tail above is what a template writes after the LAST call of a
|
||||
+ * turn, so it carries the turn terminator -- `</function><|im_end|>` -- and a
|
||||
+ * close that demands the terminator can only ever match a reply with exactly ONE
|
||||
+ * call in it. Between the end of the first call and the opener of the second
|
||||
+ * there is no terminator, so that render measures the close alone.
|
||||
+ *
|
||||
+ * Anchored on the first call's second argument VALUE rather than on a count of
|
||||
+ * openers: `<function name="` also appears in this template's own instructions to
|
||||
+ * the model, in the system prompt, so counting occurrences finds the wrong one. */
|
||||
+ json assistant_two_calls = json{
|
||||
+ { "role", "assistant" },
|
||||
+ { "content", "" },
|
||||
+ { "tool_calls", json::array({ first_tool_call, second_tool_call }) }
|
||||
+ };
|
||||
+ auto calls = compare_variants(*tmpl, params, [&](template_params & p) {
|
||||
+ p.messages = json::array({ user_msg, assistant_two_calls }); });
|
||||
+ if (calls) {
|
||||
+ const std::string c2 = calls->diff.prefix + calls->diff.right + calls->diff.suffix;
|
||||
+ const size_t lastv = c2.find(ARG_SECOND_VALUE);
|
||||
+ const size_t open2 = lastv == std::string::npos
|
||||
+ ? std::string::npos
|
||||
+ : c2.find(function.name_prefix,
|
||||
+ lastv + ARG_SECOND_VALUE.size());
|
||||
+ if (open2 != std::string::npos) {
|
||||
+ const std::string between =
|
||||
+ c2.substr(lastv + ARG_SECOND_VALUE.size(),
|
||||
+ open2 - (lastv + ARG_SECOND_VALUE.size()));
|
||||
+ if (between.size() > per_arg.size() &&
|
||||
+ between.compare(0, per_arg.size(), per_arg) == 0) {
|
||||
+ /* Trailing whitespace is between-turn layout, never part of a
|
||||
+ * generated close; the parser skips space between calls itself. */
|
||||
+ function.close = trim_trailing_whitespace(between.substr(per_arg.size()));
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ LOG_DBG("RADIANCE split: value_suffix '%s', func_close '%s'\n",
|
||||
+ arguments.value_suffix.c_str(), function.close.c_str());
|
||||
+
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
}
|
||||
|
||||
void analyze_tools::extract_args_markers() {
|
||||
Vendored
+174
@@ -0,0 +1,174 @@
|
||||
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
|
||||
index ed895b5..104fe47 100644
|
||||
--- a/common/chat-auto-parser-generator.cpp
|
||||
+++ b/common/chat-auto-parser-generator.cpp
|
||||
@@ -412,7 +412,11 @@ common_peg_parser analyze_tools::build_tool_parser_tag_json(parser_build_context
|
||||
|
||||
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);
|
||||
- return ctx.reasoning_parser + p.optional(p.content(content_before_tools)) + tool_calls + p.end();
|
||||
+ /* 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 {
|
||||
@@ -443,15 +447,38 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
for (const auto & [param_name, param_schema] : properties.items()) {
|
||||
bool is_required = required.find(param_name) != required.end();
|
||||
|
||||
+ /* 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 +
|
||||
- (schema_info.resolves_to_string(param_schema) ?
|
||||
- p.tool_arg_string_value(until_suffix) :
|
||||
- p.tool_arg_json_value(p.schema(
|
||||
- p.json(), "tool-" + name + "-arg-" + param_name + "-schema", param_schema, false)) +
|
||||
- p.space()) +
|
||||
+ 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);
|
||||
@@ -462,22 +489,33 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
}
|
||||
}
|
||||
|
||||
- // Build required arg sequence in definition order
|
||||
- common_peg_parser args_seq = p.eps();
|
||||
- for (size_t i = 0; i < required_parsers.size(); i++) {
|
||||
- if (i > 0) {
|
||||
- args_seq = args_seq + p.space();
|
||||
- }
|
||||
- args_seq = args_seq + required_parsers[i];
|
||||
+ /* 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;
|
||||
}
|
||||
|
||||
- // Build optional args with flexible ordering
|
||||
- if (!optional_parsers.empty()) {
|
||||
- common_peg_parser any_opt = p.choice();
|
||||
- for (const auto & opt : optional_parsers) {
|
||||
- any_opt |= opt;
|
||||
- }
|
||||
- args_seq = args_seq + p.repeat(p.space() + any_opt, 0, -1);
|
||||
+ 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()) {
|
||||
@@ -510,6 +548,12 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
|
||||
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()) {
|
||||
@@ -525,11 +569,28 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
(format.section_end.empty() ? p.end() : p.literal(format.section_end) + p.space()));
|
||||
}
|
||||
} else {
|
||||
- std::string separator = ", "; // Default
|
||||
+ /* 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(separator + tool_choice) + p.space() +
|
||||
+ p.zero_or_more(next_call) + p.space() +
|
||||
format.section_end);
|
||||
} else {
|
||||
tool_calls = p.trigger_rule(
|
||||
@@ -541,7 +602,18 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
tool_calls = p.optional(tool_calls);
|
||||
}
|
||||
|
||||
- std::string trigger_marker = !format.section_start.empty() ? format.section_start : format.per_call_start;
|
||||
+ /* 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();
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
diff --git a/common/chat-peg-parser.cpp b/common/chat-peg-parser.cpp
|
||||
index 111acd0..b674d6e 100644
|
||||
--- a/common/chat-peg-parser.cpp
|
||||
+++ b/common/chat-peg-parser.cpp
|
||||
@@ -51,6 +51,54 @@ static std::string_view strip_one_leading_newline(std::string_view sv) {
|
||||
return sv;
|
||||
}
|
||||
|
||||
+// RADIANCE: A CDATA SECTION IS PUNCTUATION, NOT CONTENT. MiniCPM5's template tells the model
|
||||
+// verbatim: "If it contains <, & or newline characters, wrap it in a CDATA block:
|
||||
+// <param name="param-name"><![CDATA[...multi-line value...]]></param>" -- so every source file an
|
||||
+// agent writes arrives wrapped, and handing `<![CDATA[def main():...]]>` to a write tool puts
|
||||
+// those characters into the file.
|
||||
+//
|
||||
+// THE TWO ENDS ARE STRIPPED INDEPENDENTLY, AND THAT IS THE WHOLE POINT. A streamed value is
|
||||
+// parsed again from the top on every chunk, and what the server sends the client is the part
|
||||
+// that is new -- so a value already emitted cannot be taken back. Requiring both delimiters
|
||||
+// before removing either means the opener escapes in the first chunk, every time, and the
|
||||
+// closing `]]>` is then half-eaten by the suffix match: the agent's files came out starting
|
||||
+// `<![CDATA[` and ending `]]`, the model saw its own output corrupted, and it spent the rest of
|
||||
+// the session trying to edit the markers back out.
|
||||
+//
|
||||
+// While a value is still partial, a trailing `]` or `]]` is held back: it is either the start of
|
||||
+// the closer or the end of a JSON array, and withholding is safe either way -- what is emitted
|
||||
+// stays a prefix of the finished value, which is the contract the streaming diff needs.
|
||||
+static void unwrap_cdata(std::string_view & sv, bool is_partial) {
|
||||
+ static constexpr std::string_view cd_open = "<![CDATA[";
|
||||
+ static constexpr std::string_view cd_close = "]]>";
|
||||
+ if (sv.size() < cd_open.size()) {
|
||||
+ /* Not enough of it to tell yet. While the value is still arriving, anything that could
|
||||
+ * still BECOME the opener is held back whole -- `<![CDATA` went out as content once and
|
||||
+ * could never be taken back. A complete value this short is just a short value. */
|
||||
+ if (is_partial && !sv.empty() && cd_open.compare(0, sv.size(), sv) == 0) {
|
||||
+ sv = std::string_view();
|
||||
+ }
|
||||
+ return;
|
||||
+ }
|
||||
+ if (sv.compare(0, cd_open.size(), cd_open) != 0) {
|
||||
+ return;
|
||||
+ }
|
||||
+ sv.remove_prefix(cd_open.size());
|
||||
+ if (sv.size() >= cd_close.size() &&
|
||||
+ sv.compare(sv.size() - cd_close.size(), cd_close.size(), cd_close) == 0) {
|
||||
+ sv.remove_suffix(cd_close.size());
|
||||
+ return;
|
||||
+ }
|
||||
+ if (!is_partial) {
|
||||
+ return;
|
||||
+ }
|
||||
+ size_t hold = 0;
|
||||
+ while (hold + 1 < cd_close.size() && sv.size() > hold && sv[sv.size() - 1 - hold] == ']') {
|
||||
+ ++hold;
|
||||
+ }
|
||||
+ sv.remove_suffix(hold);
|
||||
+}
|
||||
+
|
||||
static std::string_view strip_one_trailing_newline(std::string_view sv) {
|
||||
if (!sv.empty() && sv.back() == '\n') {
|
||||
sv.remove_suffix(1);
|
||||
@@ -363,8 +411,10 @@ void common_chat_peg_mapper::map(const common_peg_ast_node & node) {
|
||||
}
|
||||
|
||||
if ((is_arg_value || is_arg_string_value) && current_tool) {
|
||||
- std::string value_content =
|
||||
- std::string(strip_one_trailing_newline(strip_one_leading_newline(node.text)));
|
||||
+ std::string_view value_view =
|
||||
+ strip_one_trailing_newline(strip_one_leading_newline(node.text));
|
||||
+ unwrap_cdata(value_view, node.is_partial);
|
||||
+ std::string value_content = std::string(value_view);
|
||||
|
||||
std::string value_to_add;
|
||||
if (value_content.empty() && is_arg_string_value) {
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
diff --git a/common/chat-auto-parser-generator.cpp b/common/chat-auto-parser-generator.cpp
|
||||
index 104fe47..b682578 100644
|
||||
--- a/common/chat-auto-parser-generator.cpp
|
||||
+++ b/common/chat-auto-parser-generator.cpp
|
||||
@@ -511,6 +511,41 @@ common_peg_parser analyze_tools::build_tool_parser_tag_tagged(parser_build_conte
|
||||
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);
|
||||
@@ -0,0 +1,33 @@
|
||||
diff --git a/common/chat.cpp b/common/chat.cpp
|
||||
index ef15169..1398152 100644
|
||||
--- a/common/chat.cpp
|
||||
+++ b/common/chat.cpp
|
||||
@@ -2354,8 +2354,26 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
|
||||
params.grammar = inputs.grammar;
|
||||
params.now = inputs.now;
|
||||
params.add_generation_prompt = inputs.add_generation_prompt;
|
||||
- params.add_bos = tmpls->add_bos;
|
||||
- params.add_eos = tmpls->add_eos;
|
||||
+ /* RADIANCE: `add_bos` HAS TO COME FROM THE INPUTS, OR THE INPUT FIELD IS DEAD.
|
||||
+ *
|
||||
+ * `common_chat_templates_inputs` carries add_bos/add_eos and every caller fills them, but
|
||||
+ * this conversion overwrote both from the TEMPLATES object -- which is only ever set inside
|
||||
+ * common_chat_templates_init, from a llama_vocab. A host that passes `model = nullptr` and
|
||||
+ * supplies the vocabulary's facts as overrides (which is what radiance does: the container
|
||||
+ * carries the template, the BOS/EOS spellings and the add flags, so there is no llama_model
|
||||
+ * to read them off) therefore had both flags stuck at false no matter what it asked for.
|
||||
+ *
|
||||
+ * What the flag does is strip a BOS the TEMPLATE rendered, because the tokeniser is about to
|
||||
+ * add one -- so with it stuck off, a container whose tokeniser adds BOS and whose template
|
||||
+ * also writes `bos_token` gets TWO. The Llama-family templates write it; Qwen's do not,
|
||||
+ * which is why this stayed invisible here.
|
||||
+ *
|
||||
+ * The two upstream callers that do set it -- common_chat_format_single and
|
||||
+ * common_chat_format_example -- assign `inputs.add_bos = tmpls->add_bos` immediately before
|
||||
+ * calling apply, which is exactly the redundancy you would expect if apply were meant to read
|
||||
+ * the inputs. Falling back to the templates object keeps them working unchanged. */
|
||||
+ params.add_bos = inputs.add_bos || tmpls->add_bos;
|
||||
+ params.add_eos = inputs.add_eos || tmpls->add_eos;
|
||||
|
||||
params.continue_final_message = inputs.continue_final_message;
|
||||
if (params.continue_final_message != COMMON_CHAT_CONTINUATION_NONE) {
|
||||
Reference in new issue
Block a user