From b988378e70ef07c41c6152281d01fcc4550bfeea Mon Sep 17 00:00:00 2001 From: Victor Ionescu Date: Mon, 16 Nov 2026 15:18:15 +0200 Subject: [PATCH] chat: read a function name that ends at whitespace (Ling 3.0) Ling-3.0-flash's template writes a call as the opener, the function name, a newline, and only then the argument tags: read path /a The differential analysis names the function between the opener and the first argument tag, so its end is the bare newline and name_suffix comes out as whitespace alone. chat_format_check refused that, so every request carrying tools answered 501 with "this model's tool calls cannot be read back: name_suffix must end the function name with something besides whitespace" -- the whole tool-calling surface, for every Ling-3.0 checkpoint. A suffix with no core of its own is the suffixless ending written out: the name stops at the whitespace. The reader now takes it that way (name_open keys on the trimmed core, so the name runs to the first arg_prefix or call_end, whitespace trimmed), while the grammar still writes the template's newline. The object family has no such terminator -- its brace ends the name -- and keeps the refusal, as does the wrapped format whose bare name_prefix would otherwise read as a call. Adds the real template as a fixture and a regression test that derives the format, builds the grammar, and reads a two-call reply built from the derived fields; a second test pins the object family's refusal. --- core/engine.cpp | 15 ++- core/engine.h | 9 ++ core/server/adapters.h | 37 +++++- core/text/chatfmt.cpp | 20 ++-- core/text/chatfmt.h | 4 +- core/text/chatparse.cpp | 8 +- tests/chatparse_test.cpp | 73 ++++++++++++ tests/data/chat/ling3/chat_template.jinja | 130 ++++++++++++++++++++++ 8 files changed, 275 insertions(+), 21 deletions(-) create mode 100644 tests/data/chat/ling3/chat_template.jinja diff --git a/core/engine.cpp b/core/engine.cpp index a39ac2c6..57a18461 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2213,11 +2213,11 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) { * drive the KV rollback, the conv cursor and the emitted text) say how far the step * really got. */ acc = accept_cut_at_eog(out, acc, - [&](int32_t t) { return vocab_ && vocab_->is_eog(t); }); + [&](int32_t t) { return is_eog(t); }); so.accepted[i] = acc; so.token[i] = out[acc]; - so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0; + so.eos[i] = is_eog(so.token[i]) ? 1 : 0; if (tree) { if (so.path.empty()) so.path.assign(plan.e.size() * RAD_SCHED_MAX_SPEC, 0); for (int32_t t = 0; t < acc; ++t) so.path[i * RAD_SCHED_MAX_SPEC + t] = path[t]; @@ -2254,7 +2254,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) { continue; } so.token[i] = so.rows[(size_t)so.first_row[i]]; - so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0; + so.eos[i] = is_eog(so.token[i]) ? 1 : 0; if (e.req && e.req->sp.n_probs >= 0) RAD_TRY(row_logprobs(so, so.first_row[i], so.token[i])); /* Advance the grammar on every rank: each builds the mask for its own vocabulary shard from @@ -3392,6 +3392,15 @@ int Engine::run_server() { const bool have_tpl = !gen_ && vocab_ && !vocab_->chat_template().empty() && chat_bridge.init(*vocab_, declared_format, plugins_.arch_plugin) >= 0 && chat_bridge.ready(); + /* A token this format writes as one of its own call delimiters is a call boundary, not a + * turn's: a reply that closes a call with it must be able to write the next one, and text + * after it. A container that also declares it end-of-generation would cut every tool-calling + * turn there, so the id leaves the decoder's stop set. */ + eog_demoted_ = chat_bridge.eog_call_markers(); + for (int32_t id : eog_demoted_) + RAD_WARN("vocab: token %d \"%s\" is end-of-generation and one of this model's " + "tool-call delimiters; a turn no longer ends on it", id, + vocab_->text(id).c_str()); if (embedding_) { /* No chat endpoint: the model's template, when it has one, renders a `messages` input. */ if (have_tpl) embed_info.tpl = &chat_bridge; diff --git a/core/engine.h b/core/engine.h index e93ebb83..2d17448b 100644 --- a/core/engine.h +++ b/core/engine.h @@ -419,6 +419,15 @@ private: /* The text frontend, loaded from the container. The sampler's grammars walk `vocab_view_`, * which references `vocab_` and must not outlive it. */ std::shared_ptr vocab_; + /* End-of-generation ids the chat format also writes as a call delimiter: a call boundary is + * not a turn's, so the decoder does not stop on them (run_server demotes them). */ + std::vector eog_demoted_; + /* End-of-generation as the decoder sees it: the vocabulary's set, minus the demoted ids. */ + bool is_eog(int32_t id) const { + if (!vocab_ || !vocab_->is_eog(id)) return false; + for (int32_t d : eog_demoted_) if (d == id) return false; + return true; + } std::unique_ptr vocab_view_; /* The container's second vocabulary (rad-convert --tokenizer2), which an image generator that * declares `aux_tokens` reads its prompt through; null without one. */ diff --git a/core/server/adapters.h b/core/server/adapters.h index 0c085442..9a4991b2 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -526,12 +526,7 @@ public: * derive it from the template. A declaration the parser cannot run is refused at startup. */ int init(const Vocab& v, const RadChatFormat* declared = nullptr, const std::string& plugin = std::string()) { - /* The spellings, resolved once. See ReplyOptions::terminators. */ - terminators_.clear(); - for (int32_t id : v.eog()) { - const std::string s = v.text(id); - if (!s.empty()) terminators_.push_back(s); - } + eog_call_markers_.clear(); const int st = t_.load_from_vocab(v); if (st < 0) return st; @@ -569,9 +564,38 @@ public: RAD_INFO("chat: reply format %s", chat_format_describe(f).c_str()); if (t_.caps().tools && !tool_refusal_.empty()) RAD_WARN("chat: tool calls are refused for this model: %s", tool_refusal_.c_str()); + + /* A container can name a token end-of-generation that this format writes as one of its + * own call delimiters (a converted checkpoint that lists its tool-call close). A turn + * ending there loses a second call and anything after it, and a reply that quotes the tag + * is cut mid-sentence; the engine drops these ids from the decoder's set + * (Vocab::drop_eog). */ + eog_call_markers_.clear(); + if (f.has_tools()) + for (const std::string& m : chat_format_markers(f)) + for (int32_t id : v.eog()) + if (v.text(id) == m && + std::find(eog_call_markers_.begin(), eog_call_markers_.end(), id) == + eog_call_markers_.end()) + eog_call_markers_.push_back(id); + /* The spellings, resolved once. See ReplyOptions::terminators. A call delimiter the + * container also declares terminal is left out here too: the parser must read it as the + * call boundary it is, not as the end of the reply. */ + terminators_.clear(); + for (int32_t id : v.eog()) { + if (std::find(eog_call_markers_.begin(), eog_call_markers_.end(), id) != + eog_call_markers_.end()) + continue; + const std::string s = v.text(id); + if (!s.empty()) terminators_.push_back(s); + } return RAD_OK; } + /* End-of-generation ids whose spelling is one of the format's call delimiters: a call + * boundary the container also declares a turn boundary. Empty for a model without tools. */ + const std::vector& eog_call_markers() const { return eog_call_markers_; } + bool ready() const { return t_.ready() && fmt_ != nullptr; } bool supports_tools() const override { return t_.caps().tools; } std::string tools_probe_error() const override { return t_.caps().probe_error; } @@ -752,6 +776,7 @@ private: ChatTemplate t_; std::vector terminators_; + std::vector eog_call_markers_; std::shared_ptr fmt_; bool declared_ = false; std::string tool_refusal_; diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index a8ba4e2d..a9a2a3f6 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -202,10 +202,13 @@ int chat_format_check(const ChatFormat& f, std::string* why) { if (object && !f.section_open.empty()) return no("section-wrapped object arguments are not supported"); /* Without a suffix the name ends at what follows it: the object's `{`, or a tagged call's - * first argument or close. */ - if (!f.name_suffix.empty()) { - if (trim_ws(f.name_suffix).empty()) - return no("name_suffix must end the function name with something besides whitespace"); + * first argument or close. A suffix of nothing but whitespace is that same ending, written + * out: the name stops at the whitespace (Ling 3.0's `NAME\n`), so the + * reader treats it as a suffixless name, while the grammar still writes the template's + * newline. The object family has no such terminator -- its `{` ends the name -- and keeps + * the refusal. */ + const bool name_by_ws = !object && !f.name_suffix.empty() && trim_ws(f.name_suffix).empty(); + if (!f.name_suffix.empty() && !name_by_ws) { if (is_ws((unsigned char)f.name_suffix[0])) return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace"); } @@ -216,10 +219,11 @@ int chat_format_check(const ChatFormat& f, std::string* why) { if (f.arg_name_suffix.empty() && f.arg_value_prefix.empty()) return no("nothing ends an argument name: arg_name_suffix and arg_value_prefix are " "empty"); - if (f.name_suffix.empty()) { - /* The name runs to the first arg_prefix or call_end. A wrapped format also reads - * name_prefix alone as a call, told from prose only by its closed name tag, and - * without a suffix there is none. */ + if (f.name_suffix.empty() || name_by_ws) { + /* The name runs to the first arg_prefix or call_end, written either with no suffix + * or with the whitespace that ends it. A wrapped format also reads name_prefix + * alone as a call, told from prose only by its closed name tag, and without a + * suffix there is none. */ if (!f.call_open.empty()) return no("name_suffix is empty, which a tagged call allows only when name_prefix " "opens it, and call_open is set"); diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h index 978bb2ed..5cec3b7e 100644 --- a/core/text/chatfmt.h +++ b/core/text/chatfmt.h @@ -116,7 +116,9 @@ struct ChatFormat { std::string call_open, call_close; /* "\n". name_suffix may be empty: in the object family the name then ends at * the object's `{`; in the tagged family, where name_prefix must open the call (no - * call_open), at the first arg_prefix or call_end, which stay part of the call's body. */ + * call_open), at the first arg_prefix or call_end, which stay part of the call's body. A + * suffix of only whitespace is read as that second ending: the name stops at the whitespace + * (`NAME\n`, Ling 3.0), which the grammar still writes. */ std::string name_prefix, name_suffix; std::string call_end; /* "\n"; may be empty for an object */ diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index dc8a744f..def51207 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -746,8 +746,8 @@ struct ReplyFormat::Impl { /* Object family. `object`: a call's arguments are one object. `ns_object`: the object's own * `{` ends the name (name_suffix empty), and ns_core is "{". */ bool object = false, ns_object = false; - /* Tagged family, name_suffix empty: a call's name ends where arg_prefix or end_core begins, - * and that tag is the first of the call's body. */ + /* Tagged family, no core in name_suffix (empty, or whitespace alone): a call's name ends + * where arg_prefix or end_core begins, and that tag is the first of the call's body. */ bool name_open = false; /* Where a key or value may begin, besides the object's punctuation: the dialect string's * opener, and the call's close and end (written there by a reply that leaves its object @@ -810,7 +810,9 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr m.name_end = f.arg_name_suffix + f.arg_value_prefix; if (f.typed_tags()) m.name_end_json = f.arg_name_suffix + f.arg_json_value_prefix; m.object = f.has_tools() && f.object_args(); - m.name_open = f.has_tools() && !m.object && f.name_suffix.empty(); + /* A suffix with no core of its own ends the name at whitespace, and the name then runs to + * the first argument tag or the call's end, as it does without a suffix (Ling 3.0). */ + m.name_open = f.has_tools() && !m.object && m.ns_core.empty(); if (m.object && f.name_suffix.empty()) { m.ns_object = true; m.ns_core = "{"; diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index 62cb42bf..8af9e419 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -34,6 +34,7 @@ #include #include +#include #include "util/json.h" @@ -2380,6 +2381,78 @@ TEST(glm53_derives_a_name_the_opener_opens) { CHECK(why.find("name_suffix") != std::string::npos); } +/* Ling 3.0's template ends the function name with a newline and only then writes the argument + * tags, so the analysis derives a name_suffix of whitespace alone. The reader treats that as the + * suffixless ending -- the name stops at the first argument tag, whitespace trimmed -- while the + * grammar keeps the newline the template writes. Before it was allowed, every request carrying + * tools was refused: "name_suffix must end the function name with something besides + * whitespace". */ +TEST(ling3_reads_a_name_that_ends_at_whitespace) { + ChatFormat f; + std::string why, refused; + CHECK_OK(chat_format_from_template(fixture("ling3"), "", "<|role_end|>", &f, &refused, &why)); + CHECK(refused.empty()); + /* The spellings of this shape are pinned by glm53_derives_a_name_the_opener_opens; Ling's + * difference is the newline between the name and the first argument tag. */ + CHECK(f.call_open.empty() && f.call_close.empty()); + CHECK(!f.name_prefix.empty() && f.name_prefix[0] == '<'); + CHECK(!f.name_suffix.empty() && + f.name_suffix.find_first_not_of(" \t\r\n") == std::string::npos); + CHECK(!f.call_end.empty()); + CHECK(!f.arg_prefix.empty() && !f.arg_name_suffix.empty() && !f.arg_value_prefix.empty() && + !f.arg_value_suffix.empty()); + CHECK_OK(chat_format_check(f, &why)); + + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + ChatGrammar g; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + CHECK(g.lazy); + CHECK(!g.trigger_words.empty()); + + /* A reply built the way the template writes it reads back as the calls it renders, newline + * after the name and no whitespace between one argument's close and the next argument's + * tag. */ + std::string reply = "Look."; + auto arg = [&](const std::string& k, const std::string& v) { + return f.arg_prefix + k + f.arg_name_suffix + f.arg_value_prefix + v + f.arg_value_suffix; + }; + reply += f.name_prefix + "read" + f.name_suffix + arg("path", "/a") + arg("limit", "3") + + f.call_end; + reply += f.name_prefix + "ping" + f.name_suffix + f.call_end; + + ReplyOptions ro; + ro.tools = &agent_tools(); + ro.terminators = { "<|role_end|>" }; + const std::shared_ptr p = parser_of(f, ro); + REQUIRE(p != nullptr); + bool strict = false; + const ReplyMessage m = reply_parse(*p, reply, &strict); + CHECK_EQ(m.content, std::string("Look.")); + REQUIRE(m.calls.size() == 2); + CHECK_EQ(m.calls[0].name, std::string("read")); + CHECK_EQ(m.calls[0].arguments, std::string("{\"path\":\"/a\",\"limit\":3}")); + CHECK(m.calls[0].closed); + CHECK_EQ(m.calls[1].name, std::string("ping")); + CHECK(m.calls[1].closed); + CHECK(strict); + const std::string stream_error = stream_all(*p, reply); + if (!stream_error.empty()) ::radtest::fail(__FILE__, __LINE__, stream_error); +} + +/* The relaxation is for the tagged family only: an object family's name ends at its `{`, so a + * whitespace suffix there still describes a format nothing reads. */ +TEST(a_whitespace_name_suffix_is_refused_for_object_arguments) { + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(rad::arch::gemma4_chat_format(), &f, &why)); + CHECK(f.object_args()); + CHECK_OK(chat_format_check(f, &why)); + f.name_suffix = "\n"; + CHECK(chat_format_check(f, &why) < 0); + CHECK(why.find("whitespace") != std::string::npos); +} + TEST(glm53_replies_read_back_as_the_messages_they_render) { const Glm* g = glm(); REQUIRE(g != nullptr); diff --git a/tests/data/chat/ling3/chat_template.jinja b/tests/data/chat/ling3/chat_template.jinja new file mode 100644 index 00000000..ed32bb97 --- /dev/null +++ b/tests/data/chat/ling3/chat_template.jinja @@ -0,0 +1,130 @@ +{#- Bailing V3 chat template -#} +{#- Supports: thinking option, tool calling -#} + +{#- ==================== thinking option normalization ==================== -#} +{%- if enable_thinking is defined %} + {%- if enable_thinking %} + {%- set thinking_option = 'on' %} + {%- else %} + {%- set thinking_option = 'off' %} + {%- endif %} +{%- elif thinking_option is not defined %} + {%- set thinking_option = 'on' %} +{%- endif %} + +{#- ==================== preserved thinking ==================== -#} +{% set preserved_thinking = true %} + +{#- ==================== system message ==================== -#} +{{- 'SYSTEM' }} +{%- if tools %} + {%- if messages[0].role == 'system' %} + {{- messages[0].content + '\n' }} + {%- endif %} + {{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within XML tags:\n" }} + {%- for tool in tools %} + {{- "\n" }} + {{- tool | tojson }} + {%- endfor %} + {{- "\n\n\nIf none of the functions can be used, point it out. If the given question lacks the parameters required by the function, also point it out.\nIf you need to use a function, for each function call, output the function name and arguments within the following XML format:\n{function-name}\n{arg-key-1}\n{arg-value-1}\n{arg-key-2}\n{arg-value-2}\n...\n\n" }} + {%- if messages[0].role == 'system' and messages[0].content is string and ('detailed thinking on' in messages[0].content or 'detailed thinking off' in messages[0].content) %} + {{- '<|role_end|>' }} + {%- else %} + {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }} + {%- endif %} +{%- else %} + {%- if messages[0].role == 'system' %} + {%- if 'detailed thinking on' in messages[0].content or 'detailed thinking off' in messages[0].content %} + {{- messages[0].content + '<|role_end|>' }} + {%- else %} + {{- messages[0].content + '\n' }} + {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }} + {%- endif %} + {% else %} + {{- 'detailed thinking ' + thinking_option + '<|role_end|>' }} + {%- endif %} +{%- endif %} +{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %} +{%- for message in messages[::-1] %} + {%- set index = (messages|length - 1) - loop.index0 %} + {%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('') and message.content.endswith('')) %} + {%- set ns.multi_step_tool = false %} + {%- set ns.last_query_index = index %} + {%- endif %} +{%- endfor %} +{%- for message in messages %} + {%- if message.content is string %} + {%- set content = message.content %} + {%- else %} + {%- set content = '' %} + {%- endif %} + {%- if message.role == "user" %} + {{- 'HUMAN' + message.content + '<|role_end|>' }} + {%- elif message.role == "system" and not loop.first %} + {{- 'SYSTEM' + message.content + '<|role_end|>' }} + {%- elif message.role == "assistant" %} + {%- set reasoning_content = '' %} + {%- if message.reasoning_content is string and message.reasoning_content != '' %} + {%- set reasoning_content = message.reasoning_content %} + {%- else %} + {%- if '' in content %} + {%- set reasoning_content = content.split('')[0].rstrip('\n').split('')[-1].lstrip('\n') %} + {%- set content = content.split('')[-1].lstrip('\n') %} + {%- endif %} + {%- endif %} + {%- if preserved_thinking or loop.index0 > ns.last_query_index %} + {%- if reasoning_content != '' %} + {{- 'ASSISTANT' + '\n' + reasoning_content.strip('\n') + '' + content.lstrip('\n') }} + {%- else %} + {{- 'ASSISTANT\n' + content }} + {%- endif %} + {%- else %} + {{- 'ASSISTANT\n' + content }} + {%- endif %} + {%- if message.tool_calls %} + {%- for tool_call in message.tool_calls %} + {%- if (loop.first and content) or (not loop.first) %} + {{- '\n' }} + {%- endif %} + {%- set tc = tool_call %} + {%- if tool_call.function %} + {%- set tc = tool_call.function %} + {%- endif %} + {{- '' + tc.name }} + {% set _args = tc.arguments %} + {%- for k, v in _args.items() %} + {{- '' + k + '' }} + {{- '\n' }} + {%- if v is string %} + {{- v }} + {%- else %} + {{- v | tojson(ensure_ascii=False) }} + {%- endif %} + {{- '' }} + {%- endfor %} + {{- '\n' }} + {%- endfor %} + {%- endif %} + {{- '<|role_end|>' }} + {%- elif message.role == "tool" %} + {%- if loop.first or (messages[loop.index0 - 1].role != "tool") %} + {{- 'OBSERVATION' }} + {%- endif %} + {{- '\n\n' }} + {{- content }} + {{- '\n' }} + {%- if loop.last or (messages[loop.index0 + 1].role != "tool") %} + {{- '<|role_end|>' }} + {%- endif %} + {%- endif %} +{%- endfor %} + +{#- ==================== generation prompt ==================== -#} +{%- if add_generation_prompt %} + {{- 'ASSISTANT' }} + {%- if thinking_option == 'on' %} + {{- '\n' }} + {%- elif thinking_option == 'off' %} + {{- '\n' }} + {%- endif %} +{%- endif %} \ No newline at end of file