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:

    <tool_call>read
    <arg_key>path</arg_key>
    <arg_value>/a</arg_value>
    </tool_call>

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.
This commit is contained in:
Victor Ionescu authored and StillDeadcode committed 2026-11-16 18:03:16 +01:00
1 parent bd3fa646bc
commit b988378e70
8 files changed
+275 -21

No files matched your search

+12 -3
View File
@@ -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;
+9
View File
@@ -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<const Vocab> 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<int32_t> 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<VocabView> 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. */
+31 -6
View File
@@ -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<int32_t>& 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<std::string> terminators_;
std::vector<int32_t> eog_call_markers_;
std::shared_ptr<const ReplyFormat> fmt_;
bool declared_ = false;
std::string tool_refusal_;
+12 -8
View File
@@ -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 `<tool_call>NAME\n<arg_key>`), 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");
+3 -1
View File
@@ -116,7 +116,9 @@ struct ChatFormat {
std::string call_open, call_close;
/* "<function=", ">\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
* (`<tool_call>NAME\n<arg_key>`, Ling 3.0), which the grammar still writes. */
std::string name_prefix, name_suffix;
std::string call_end; /* "</function>\n"; may be empty for an object */
+5 -3
View File
@@ -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<const ReplyFormat>
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 = "{";
+73
View File
@@ -34,6 +34,7 @@
#include <arch/rad_museglimmer_chat.h>
#include <arch/rad_deepseek41_chat.h>
#include <arch/rad_gemma4_chat.h>
#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<const ReplyParser> 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);
+130
View File
@@ -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 ==================== -#}
{{- '<role>SYSTEM</role>' }}
{%- 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 <tools></tools> XML tags:\n<tools>" }}
{%- for tool in tools %}
{{- "\n" }}
{{- tool | tojson }}
{%- endfor %}
{{- "\n</tools>\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<tool_call>{function-name}\n<arg_key>{arg-key-1}</arg_key>\n<arg_value>{arg-value-1}</arg_value>\n<arg_key>{arg-key-2}</arg_key>\n<arg_value>{arg-value-2}</arg_value>\n...\n</tool_call>\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('<tool_response>') and message.content.endswith('</tool_response>')) %}
{%- 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" %}
{{- '<role>HUMAN</role>' + message.content + '<|role_end|>' }}
{%- elif message.role == "system" and not loop.first %}
{{- '<role>SYSTEM</role>' + 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 '</think>' in content %}
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
{%- endif %}
{%- endif %}
{%- if preserved_thinking or loop.index0 > ns.last_query_index %}
{%- if reasoning_content != '' %}
{{- '<role>ASSISTANT</role>' + '\n<think>' + reasoning_content.strip('\n') + '</think>' + content.lstrip('\n') }}
{%- else %}
{{- '<role>ASSISTANT</role>\n<think></think>' + content }}
{%- endif %}
{%- else %}
{{- '<role>ASSISTANT</role>\n<think></think>' + 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 %}
{{- '<tool_call>' + tc.name }}
{% set _args = tc.arguments %}
{%- for k, v in _args.items() %}
{{- '<arg_key>' + k + '</arg_key>' }}
{{- '\n<arg_value>' }}
{%- if v is string %}
{{- v }}
{%- else %}
{{- v | tojson(ensure_ascii=False) }}
{%- endif %}
{{- '</arg_value>' }}
{%- endfor %}
{{- '\n</tool_call>' }}
{%- endfor %}
{%- endif %}
{{- '<|role_end|>' }}
{%- elif message.role == "tool" %}
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
{{- '<role>OBSERVATION</role>' }}
{%- endif %}
{{- '\n<tool_response>\n' }}
{{- content }}
{{- '\n</tool_response>' }}
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
{{- '<|role_end|>' }}
{%- endif %}
{%- endif %}
{%- endfor %}
{#- ==================== generation prompt ==================== -#}
{%- if add_generation_prompt %}
{{- '<role>ASSISTANT</role>' }}
{%- if thinking_option == 'on' %}
{{- '\n<think>' }}
{%- elif thinking_option == 'off' %}
{{- '\n<think></think>' }}
{%- endif %}
{%- endif %}