From e60810116cf95f7d968dce28b39446a4aabea8cf Mon Sep 17 00:00:00 2001 From: Nunze Date: Mon, 19 Oct 2026 14:43:02 +0200 Subject: [PATCH] chat: tagged calls whose name the opener opens -- GLM-5's NAME GLM-5 writes NAMEKV...: no prefix of the name's own and no suffix, the name ends at the first argument or at the call's close. The tagged family now takes an empty name_suffix when name_prefix opens the call (no call_open): the derivation from the template makes the per-call opener the prefix and its closer call_end, the grammar takes eps() for the suffix, and the streaming parser finds the name's end byte by byte (name_stop, name_plausible) and reads the closing tag as the first item of the body. arg_name_suffix and arg_value_prefix may both be set and are read back to back, so chat_format_markers keeps both tags. value_newlines comes from a probe render of the template rather than a constant (GLM and MiniCPM false, Qwen true). The ABI struct is unchanged; its comments say what an empty name_suffix means now. chatparse_test: GLM's template serves tools; the derived format equals the one a plugin would declare; every rendered reply in the corpus reads back as the message it rendered, split at every byte; and replies that stray from the grammar. Each fails without this change. The Gemma refusal names call_end. Co-Authored-By: Claude Opus 5.5 Co-Authored-By: Claude Fable 5.1 --- abi/rad_builder.h | 5 +- core/text/chatfmt.cpp | 60 +++++- core/text/chatfmt.h | 17 +- core/text/chatparse.cpp | 100 ++++++++- tests/chatparse_gemma4_test.cpp | 2 +- tests/chatparse_test.cpp | 345 +++++++++++++++++++++++++++++++- 6 files changed, 507 insertions(+), 22 deletions(-) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 70993b69..839904da 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1110,10 +1110,13 @@ typedef struct RadChatFormat { const char* call_open; /* around each call; "" when calls are not wrapped */ const char* call_close; const char* name_prefix; /* "" when the model has no tool calls */ + /* "" when nothing of its own ends the name: then the object's `{` does, or, for tagged + * arguments in an unwrapped call, the first arg_prefix or call_end, which begin the body */ const char* name_suffix; const char* call_end; const char* arg_prefix; - const char* arg_name_suffix; /* "" when arg_value_prefix alone ends the name */ + /* "" when arg_value_prefix alone ends the name; both set are written back to back */ + const char* arg_name_suffix; const char* arg_value_prefix; const char* arg_value_suffix; diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index df5a7b54..fb588d6f 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -7,6 +7,7 @@ * reply. */ #include "llama/common/chat.h" #include "llama/common/chat-auto-parser.h" +#include "llama/common/chat-auto-parser-helpers.h" #include "llama/common/json-schema-to-grammar.h" #include "shim/log.h" @@ -120,6 +121,29 @@ int reasoning_anywhere_check(const ChatFormat& f, std::string* why) { return RAD_OK; } +/* Does the template write an argument's value on lines of its own? Then one newline at each end + * is the tags' (ChatFormat::value_newlines). A template that writes it flush against its tags + * (`VALUE`) leaves those newlines to the value; reading them as the tags' + * would drop a written file's last line break. A render that fails counts as own lines. */ +bool value_on_own_lines(const common_chat_template& tmpl, const ChatFormat& c) { + static const char* const kValue = "RADIANCE_VALUE_PROBE"; + ojson call = { { "id", "call_0" }, { "type", "function" } }; + call["function"] = { { "name", "probe" }, { "arguments", { { "arg", kValue } } } }; + ojson reply = { { "role", "assistant" }, { "content", "" } }; + reply["tool_calls"] = ojson::array({ call }); + ojson params = { { "type", "object" } }; + params["properties"]["arg"]["type"] = "string"; + ojson tool = { { "type", "function" } }; + tool["function"] = { { "name", "probe" }, { "description", "probe" } }; + tool["function"]["parameters"] = params; + template_params tp; + tp.messages = ojson::array({ ojson{ { "role", "user" }, { "content", "hi" } }, reply }); + tp.tools = ojson::array({ tool }); + const std::string r = autoparser::apply_template(tmpl, tp); + const std::string flush = c.arg_name_suffix + c.arg_value_prefix + kValue + c.arg_value_suffix; + return r.find(flush) == std::string::npos; +} + } /* namespace */ /* ================================================================== validity */ @@ -162,9 +186,10 @@ int chat_format_check(const ChatFormat& f, std::string* why) { if (f.call_open.empty() && !f.call_close.empty()) return no("call_close without call_open"); const bool object = f.object_args(); - /* An object's own `{` may be what ends the name; anything else needs its suffix. */ - if (!object || !f.name_suffix.empty()) { - if (f.name_suffix.empty() || trim_ws(f.name_suffix).empty()) + /* 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"); if (is_ws((unsigned char)f.name_suffix[0])) return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace"); @@ -176,9 +201,17 @@ 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.arg_name_suffix.empty() && !f.arg_value_prefix.empty()) - return no("arg_name_suffix and arg_value_prefix are both set; the streaming parser " - "reads one delimiter between an argument's name and its value"); + 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.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"); + if (is_ws((unsigned char)f.arg_prefix[0])) + return no("arg_prefix " + show(f.arg_prefix) + " may not begin with whitespace " + "when it is what ends the function name"); + } if (f.string_value != ChatValue::Raw && f.string_value != ChatValue::Cdata) return no("string_value must be RAD_CHAT_VALUE_RAW or RAD_CHAT_VALUE_CDATA"); if ((uint32_t)f.other_value > (uint32_t)ChatValue::Json) @@ -362,9 +395,18 @@ int chat_format_from_template(const std::string& jinja, const std::string& bos, c.arg_name_suffix = t.arguments.name_suffix; c.arg_value_prefix = t.arguments.value_prefix; c.arg_value_suffix = t.arguments.value_suffix; + /* A name the per-call opener itself opens, with no tag of its own around it + * (GLM's `NAME`): the opener is the name's prefix and the + * per-call close the call's own, so the name ends at the first argument or close. */ + if (c.name_prefix.empty() && !c.call_open.empty() && c.call_end.empty()) { + c.name_prefix = c.call_open; + c.call_end = c.call_close; + c.call_open.clear(); + c.call_close.clear(); + } c.string_value = ChatValue::Cdata; c.other_value = ChatValue::Json; - c.value_newlines = true; + c.value_newlines = value_on_own_lines(tmpl, c); /* The section or per-call opener both triggers the lazy grammar and ends an * unclosed reasoning block. A format with neither gets no grammar and no break, * since its calls open with the name prefix, which a model also writes in prose. */ @@ -853,7 +895,9 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat if (!req_arms.empty()) args = seq({ any_arg, rep(seq({ space(), any_arg }), 0, -1) }); else if (!opt_arms.empty()) args = seq({ eps(), rep(seq({ space(), any_arg }), 0, -1) }); - G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), lit(f.name_suffix) })); + /* Without a suffix the name ends where its arguments or close begin. */ + G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), + f.name_suffix.empty() ? eps() : lit(f.name_suffix) })); G func = seq({ open, eps(), space(), args, space(), wrap(lit(f.call_end)) }); b.add_rule(rule_name("tool-" + name), render(func)); choices.push_back(rule_ref(rule_name("tool-" + name))); diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h index 43903b35..c2b72444 100644 --- a/core/text/chatfmt.h +++ b/core/text/chatfmt.h @@ -22,12 +22,16 @@ * Qwen3.6 / Qwen3.8 \n\n\nVALUE\n\n * \n * MiniCPM5 VALUE + * GLM-5 NAMEARGVALUE + * * * A call's name sits between a prefix and a suffix and the call ends with its own close; each * argument is a name between a prefix and a suffix, then a value ending at its own suffix; calls - * may be wrapped one by one. Arguments are typed by the tool's JSON schema: a string-typed one is - * raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as - * JSON is taken raw, since models often write Python literals into a tag. + * may be wrapped one by one. A name may also have no suffix of its own (GLM): it then ends where + * the first argument or the call's close begins, and that tag is read as what it is. Arguments + * are typed by the tool's JSON schema: a string-typed one is raw text (optionally CDATA-wrapped), + * any other type is JSON, and text that does not parse as JSON is taken raw, since models often + * write Python literals into a tag. * * Object family (ChatArgs::Object): a call is its name and one object holding the arguments. * @@ -107,8 +111,9 @@ struct ChatFormat { /* Around each call: "\n", "". When set, a call written without it * (name_prefix alone) is still read as a call (chatparse.h). */ std::string call_open, call_close; - /* "\n". In the object family name_suffix may be empty; the name then ends at - * the object's `{`. */ + /* "\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. */ std::string name_prefix, name_suffix; std::string call_end; /* "\n"; may be empty for an object */ @@ -120,6 +125,8 @@ struct ChatFormat { bool object_bare_keys = false; std::string arg_prefix; /* "", ""): + * they are then read as one delimiter, written back to back. */ std::string arg_name_suffix; /* ">\n" (MiniCPM: empty, the value prefix ends it) */ std::string arg_value_prefix; /* "" (MiniCPM: "\">") */ std::string arg_value_suffix; /* "\n" */ diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index d65c1c1d..5222a659 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -726,7 +726,8 @@ struct ReplyFormat::Impl { * second, since models often write a call without its wrapper; a wrapper written without * its trailing whitespace is read too. */ std::vector openers; - std::string name_end; /* what ends an argument name */ + /* What ends an argument name: arg_name_suffix and arg_value_prefix, back to back. */ + std::string name_end; /* The same two, whitespace-trimmed. A loose call is one the grammar never opened, so it was * written unconstrained; its argument tags, like its name and close, are read with their * surrounding whitespace optional. */ @@ -740,6 +741,9 @@ 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. */ + 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 * unclosed). Matched anchored, by first byte; chat_format_check keeps them distinct. */ @@ -788,8 +792,9 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr split_ws(f.call_open, &m.co_core, &m.co_trail); if (f.call_open.empty()) m.openers = { f.name_prefix }; else m.openers = { m.co_core, f.name_prefix }; - m.name_end = f.arg_name_suffix.empty() ? f.arg_value_prefix : f.arg_name_suffix; + m.name_end = f.arg_name_suffix + f.arg_value_prefix; m.object = f.has_tools() && f.object_args(); + m.name_open = f.has_tools() && !m.object && f.name_suffix.empty(); if (m.object && f.name_suffix.empty()) { m.ns_object = true; m.ns_core = "{"; @@ -976,7 +981,15 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse t.params.emplace(pname, p); } t.arms.insert(t.arms.end(), optional.begin(), optional.end()); - if (t.name.find(F.ns_core) != std::string::npos || + if (F.name_open) { + for (const std::string* d : { &F.f.arg_prefix, &F.end_core }) + if ((t.name + *d).find(*d) != t.name.size()) { + *why = "tool '" + t.name + "' has a name running into '" + *d + + "', which this model's tool-call format uses to end a function " + "name"; + return RAD_E_INVAL; + } + } else if (t.name.find(F.ns_core) != std::string::npos || (!F.ns_object && (t.name + F.f.name_suffix).find(F.f.name_suffix) != t.name.size())) { *why = "tool '" + t.name + "' has a name containing '" + F.ns_core + @@ -1053,7 +1066,8 @@ enum class St : uint8_t { OpenCoTail, /* the whitespace that ends call_open, after its core */ OpenWs, /* after call_open: whitespace */ OpenPrefix, /* name_prefix, after call_open */ - OpenName, /* the function name, to the core of name_suffix */ + OpenName, /* the function name, to the core of name_suffix (or, without one, to the + first argument or the call's end) */ OpenTail, /* the whitespace that ends name_suffix */ OpenPeek, /* a loose call's name is read: whitespace, then an argument or the close */ OpenPeekArg, /* ... and the first argument's name, which must close as a name */ @@ -1330,6 +1344,75 @@ struct ReplyStream::Impl { return false; } + /* A suffixless name (ReplyFormat::Impl::name_open) ends where arg_prefix or end_core begins. + * Returns which one ended it (0, 1), with *len the name's length before it; or -1, with *len + * the bytes that are the name's for certain, the rest possibly beginning either. */ + int name_stop(size_t* len) const { + const std::string* const stops[] = { &F.f.arg_prefix, &F.end_core }; + size_t pend = 0; + for (int i = 0; i < 2; ++i) { + const std::string& t = *stops[i]; + if (name.size() >= t.size() && name.compare(name.size() - t.size(), t.size(), t) == 0) { + *len = name.size() - t.size(); + return i; + } + for (size_t k = std::min(t.size() - 1, name.size()); k > pend; --k) + if (name.compare(name.size() - k, k, t, 0, k) == 0) { pend = k; break; } + } + *len = name.size() - pend; + return -1; + } + + /* Could these bytes, after any leading whitespace, still be a function name? One holds no + * '<' and no whitespace before more text, unless a declared name does. Without a tag of its + * own to close it, a name read from prose that mentions the opener would otherwise be held + * up to kMaxLooseName bytes. */ + bool name_plausible(std::string_view n) const { + size_t i = 0; + while (i < n.size() && is_ws((unsigned char)n[i])) ++i; + bool gap = false; + for (; i < n.size(); ++i) { + const unsigned char c = (unsigned char)n[i]; + if (c == '<') return declared_prefix(n); + if (is_ws(c)) gap = true; + else if (gap) return declared_prefix(n); + } + return true; + } + + /* OpenName for a suffixless name. The tag that ends it is read here, as the first of the + * call's body: an argument's opener, or the call's end. Whitespace around the name is + * dropped; before it, the grammar does not admit it. */ + const char* open_name_byte(const char* p) { + size_t len = 0; + const int stop = name_stop(&len); + if (stop < 0) { + if (len > kMaxLooseName || !name_plausible(std::string_view(name).substr(0, len))) + fail_attempt(); + return p + 1; + } + size_t a = 0; + while (a < len && is_ws((unsigned char)name[a])) ++a; + const std::string nm(trim_trailing_ws(std::string_view(name).substr(a, len - a))); + auto it = P.by_name.find(nm); + tool = it == P.by_name.end() ? -1 : (int)it->second; + if (tool < 0 && (nm.empty() || nm.find('<') != std::string::npos)) { + fail_attempt(); + return p + 1; + } + name = nm; + begin_call(a == 0); + lpos = 0; + lhold.clear(); + if (stop == 0) { + start_arg(); + } else { + finish_call_strictness(); + end_core_done(); + } + return p + 1; + } + /* The call opener has matched at `att`; whether a call follows is decided below. */ void begin_attempt(St from) { origin = from; @@ -1966,6 +2049,7 @@ struct ReplyStream::Impl { const char c = *p; att.push_back(c); name.push_back(c); + if (F.name_open) return open_name_byte(p); const size_t k = F.ns_core.size(); if (name.size() >= k && name.compare(name.size() - k, k, F.ns_core) == 0) { const std::string nm = name.substr(0, name.size() - k); @@ -2640,8 +2724,12 @@ struct ReplyStream::Impl { case St::OpenWs: case St::OpenPrefix: return true; - case St::OpenName: - return declared_prefix(name); + case St::OpenName: { + if (!F.name_open) return declared_prefix(name); + size_t len = 0; + name_stop(&len); + return declared_prefix(std::string_view(name).substr(0, len)); + } case St::OpenTail: return tool >= 0; default: diff --git a/tests/chatparse_gemma4_test.cpp b/tests/chatparse_gemma4_test.cpp index f2cdd0cb..6cf152e3 100644 --- a/tests/chatparse_gemma4_test.cpp +++ b/tests/chatparse_gemma4_test.cpp @@ -196,7 +196,7 @@ TEST(an_older_struct_reads_the_object_fields_as_zero) { CHECK(!f.object_bare_keys); CHECK(!f.reasoning_anywhere); CHECK(chat_format_check(f, &why) == RAD_E_UNSUPPORTED); - CHECK(why.find("name_suffix") != std::string::npos); + CHECK(why.find("call_end") != std::string::npos); } TEST(an_object_format_the_parser_cannot_read_is_refused_by_name) { diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index f9b821fd..53747dbe 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -995,6 +995,8 @@ TEST(the_derived_formats_are_the_ones_in_service) { CHECK(refused.empty()); CHECK_EQ(f.reasoning_open, std::string("\n")); CHECK_EQ(f.reasoning_close, std::string("\n\n\n")); + /* Qwen writes a value on lines of its own, MiniCPM flush against its tags. */ + CHECK_EQ(f.value_newlines, is_qwen(m)); if (is_qwen(m)) { CHECK_EQ(f.call_open, std::string("\n")); CHECK_EQ(f.call_close, std::string("")); @@ -1260,7 +1262,9 @@ TEST(a_format_the_parser_cannot_read_is_refused_by_name) { CHECK(refused([](RadChatFormat& c) { c.name_suffix = ""; }, "name_suffix")); CHECK(refused([](RadChatFormat& c) { c.call_end = ""; }, "call_end")); CHECK(refused([](RadChatFormat& c) { c.arg_value_suffix = ""; }, "arg_value_suffix")); - CHECK(refused([](RadChatFormat& c) { c.arg_value_prefix = "\""; }, "both set")); + CHECK(refused([](RadChatFormat& c) { + c.call_open = ""; c.call_close = ""; c.name_suffix = ""; c.arg_prefix = "\n" }; @@ -1442,6 +1446,48 @@ TEST(the_chat_bridge_derives_the_whole_request_from_one_format) { CHECK(why.find("a>b") != std::string::npos); } +/* GLM-5.3-Flash's template reads list items as `m.content.0.type`, jinja2's dotted index, and + * writes calls as `NAMEKV`. The + * capability probe renders with tools and tool calls, so a runtime that throws on the dotted index + * reports no tool support; and a name the opener opens, with no tag of its own, must be a format + * the derivation describes, or every request with tools is refused. */ +TEST(glm53_serves_tools_from_its_template) { + std::shared_ptr v = vocab_with(fixture("glm53")); + REQUIRE(v != nullptr); + server::ChatTemplateBridge br; + CHECK_OK(br.init(*v)); + CHECK(br.supports_tools()); + CHECK_EQ(br.tool_refusal(), std::string()); + const server::ChatRender r = bridge_render(br, agent_tools()); + REQUIRE(!r.prompt.empty()); + CHECK(r.prompt.find("") != std::string::npos); + for (const auto& t : agent_tools()) + CHECK(r.prompt.find("\"name\": \"" + t["function"]["name"].get() + "\"") != + std::string::npos); + CHECK(!r.grammar.empty()); + CHECK(r.grammar_lazy); + REQUIRE(r.grammar_triggers.size() == 1); + CHECK_EQ(r.grammar_triggers[0].type, 1); + CHECK_EQ(r.grammar_triggers[0].value, std::string("")); + /* Each tag is a marker of its own: one the decoder suppresses as a control token is + * structure the parser never sees. */ + for (const char* t : { "", "", "", "", "", + "", "", "" }) + CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), t) != + r.preserved_tokens.end()); + REQUIRE(r.parser != nullptr); + std::unique_ptr rd = r.parser->open(); + rd->feed("Look.\nreadpath/a" + "limit3", nullptr); + rd->finish(nullptr); + const server::ParsedMessage pm = rd->message(); + CHECK_EQ(pm.reasoning, std::string("Look.")); + CHECK_EQ(pm.content, std::string()); + REQUIRE(pm.tool_calls.size() == 1); + CHECK_EQ(pm.tool_calls[0].name, std::string("read")); + CHECK_EQ(pm.tool_calls[0].arguments, std::string("{\"path\":\"/a\",\"limit\":3}")); +} + /* A template writing each call as a JSON object is not a describable format: the model still * chats with reasoning split, and a request with tools is refused with the reason. */ TEST(a_template_whose_calls_cannot_be_described_refuses_tools_and_still_chats) { @@ -1654,6 +1700,302 @@ TEST(an_object_format_the_parser_cannot_read_is_refused) { "name_prefix is empty")); } +/* ================================================================== a name the opener opens + * + * GLM-5 writes a call as `NAMEKV... + * `: the per-call opener opens the name, nothing of its own closes it, and it ends at + * the first argument or the call's close. Values are flush against their tags, strings raw and + * anything else JSON. The legacy path reads the opener as a wrapper around a call with an empty + * name tag, which is a different format, so these replies are checked against the messages they + * were rendered from rather than against the old parser. */ + +static const char* const kGlmOpener[] = { "" }; + +static RadChatFormat glm_abi() { + RadChatFormat c; + std::memset(&c, 0, sizeof c); + c.struct_size = sizeof c; + c.name = "glm-declared"; + c.reasoning_open = ""; + c.reasoning_close = ""; + c.reasoning_breaks = kGlmOpener; + c.n_reasoning_breaks = 1; + c.name_prefix = ""; + c.name_suffix = ""; + c.call_end = ""; + c.arg_prefix = ""; + c.arg_name_suffix = ""; + c.arg_value_prefix = ""; + c.arg_value_suffix = ""; + c.string_value = RAD_CHAT_VALUE_CDATA; + c.other_value = RAD_CHAT_VALUE_JSON; + c.value_newlines = 0; + c.triggers = kGlmOpener; + c.n_triggers = 1; + return c; +} + +/* The agent's tools and one that takes no arguments. */ +static const json& glm_tools() { + static const json t = [] { + json v = agent_tools(); + v.push_back(json::parse(R"({"type":"function","function":{"name":"now", + "description":"The time.","parameters":{"type":"object","properties":{}}}})")); + return v; + }(); + return t; +} + +/* GLM's template, the format derived from it, and the request every reply here answers. */ +struct Glm { + ChatTemplate tmpl; + ChatFormat f; + ChatPrompt head; + std::shared_ptr parser; + std::string grammar; +}; + +static const Glm* glm() { + static std::unique_ptr g = []() -> std::unique_ptr { + auto g = std::make_unique(); + std::string why, refused; + const std::string src = fixture("glm53"); + if (g->tmpl.load(src, "", "<|user|>") < 0) return nullptr; + if (chat_format_from_template(src, "", "<|user|>", &g->f, &refused, &why) < 0 || + !refused.empty()) + return nullptr; + ChatOptions opt; + opt.parallel_tool_calls = true; + const json user = json::array({ { { "role", "user" }, { "content", "Fix the failing test in /work." } } }); + if (g->tmpl.apply(user, glm_tools(), opt, &g->head) < 0) return nullptr; + ReplyOptions ro; + ro.generation_prompt = g->head.generation_prompt; + ro.tools = &glm_tools(); + ro.terminators = { "<|user|>", "<|observation|>", "<|endoftext|>" }; + g->parser = parser_of(g->f, ro); + ChatGrammarRequest gq; + gq.tools = &glm_tools(); + gq.generation_prompt = g->head.generation_prompt; + ChatGrammar gr; + if (chat_format_grammar(g->f, gq, &gr, &why) < 0) return nullptr; + g->grammar = gr.text; + return g->parser ? std::move(g) : nullptr; + }(); + return g.get(); +} + +/* The assistant turn as GLM's template writes it after the generation prompt. */ +static std::string glm_reply(const Glm& g, const json& assistant) { + json msgs = json::array({ { { "role", "user" }, { "content", "Fix the failing test in /work." } } }); + msgs.push_back(assistant); + ChatOptions opt; + opt.add_generation_prompt = false; + opt.parallel_tool_calls = true; + ChatPrompt whole; + if (g.tmpl.apply(msgs, glm_tools(), opt, &whole) < 0) return ""; + const std::string& head = g.head.prompt; + if (whole.prompt.compare(0, head.size(), head) != 0) return ""; + std::string r = whole.prompt.substr(head.size()); + while (!r.empty() && r.back() == '\n') r.pop_back(); + return r; +} + +static bool no_markup(const std::string& s) { + for (const char* t : { "", "", "", "", "", + "", "", "" }) + if (s.find(t) != std::string::npos) return false; + return true; +} + +TEST(glm53_derives_a_name_the_opener_opens) { + const Glm* g = glm(); + REQUIRE(g != nullptr); + const ChatFormat& f = g->f; + CHECK_EQ(f.reasoning_open, std::string("")); + CHECK_EQ(f.reasoning_close, std::string("")); + CHECK(f.call_open.empty() && f.call_close.empty()); + CHECK_EQ(f.name_prefix, std::string("")); + CHECK(f.name_suffix.empty()); + CHECK_EQ(f.call_end, std::string("")); + CHECK_EQ(f.arg_prefix, std::string("")); + CHECK_EQ(f.arg_name_suffix, std::string("")); + CHECK_EQ(f.arg_value_prefix, std::string("")); + CHECK_EQ(f.arg_value_suffix, std::string("")); + /* The template writes a value flush against its tags, so its newlines are its own. */ + CHECK(!f.value_newlines); + CHECK(f.triggers == std::vector{ "" }); + CHECK(f.reasoning_breaks == std::vector{ "" }); + CHECK(g->head.generation_prompt.find("") != std::string::npos); + CHECK(g->parser->reasoning().starts_open); + + /* A plugin declares the same format through the ABI, unchanged, and gets the same grammar. */ + RadChatFormat c = glm_abi(); + ChatFormat declared; + std::string why; + CHECK_OK(chat_format_from_abi(&c, &declared, &why)); + CHECK_OK(chat_format_check(declared, &why)); + ChatFormat derived = f; + derived.name = declared.name; + CHECK_EQ(chat_format_describe(derived), chat_format_describe(declared)); + CHECK(chat_format_markers(derived) == chat_format_markers(declared)); + ChatGrammarRequest gq; + gq.tools = &glm_tools(); + gq.generation_prompt = g->head.generation_prompt; + ChatGrammar gr; + CHECK_OK(chat_format_grammar(declared, gq, &gr, &why)); + CHECK_EQ(gr.text, g->grammar); + CHECK(gr.lazy); + CHECK(gr.trigger_words == std::vector{ "" }); + + /* Wrapped, a suffixless name would make the bare name_prefix in prose a call. */ + c.call_open = ""; + c.call_close = ""; + static const char* const wrap[] = { "" }; + c.reasoning_breaks = wrap; + CHECK_OK(chat_format_from_abi(&c, &declared, &why)); + CHECK(chat_format_check(declared, &why) < 0); + CHECK(why.find("name_suffix") != std::string::npos); +} + +TEST(glm53_replies_read_back_as_the_messages_they_render) { + const Glm* g = glm(); + REQUIRE(g != nullptr); + const ReplyParser& p = *g->parser; + struct Case { const char* what; json msg; }; + const std::vector cases = { + { "one call, string and integer", + message("Look.", "", { call("read", { { "path", "/a" }, { "limit", 3 } }) }) }, + { "two calls", + message("Two.", "", { call("bash", { { "command", "ls -la" }, { "timeout", 30 } }), + call("read", { { "path", "/b" } }) }) }, + { "a call with no arguments", message("", "", { call("now", json::object()) }) }, + { "content, then a call", + message("Plan.", "I will read it.", { call("read", { { "path", "/c" } }) }) }, + { "values holding tags and newlines", + message("", "", { call("write", { { "path", "/x.html" }, + { "content", "\n

a & b

\nk " + "f\nend\n" } }) }) }, + { "a structured value", + message("", "", { call("edit", { { "path", "/d" }, + { "edits", json::parse(R"([{"oldText":"a","newText":"b"}])") } }) }) }, + }; + for (const Case& k : cases) { + const std::string reply = glm_reply(*g, k.msg); + REQUIRE(!reply.empty()); + bool strict = false; + const ReplyMessage m = reply_parse(p, reply, &strict); + const std::string where = std::string(k.what) + ": " + quote(reply) + "\n " + show(m); + if (!strict) ::radtest::fail(__FILE__, __LINE__, "left the grammar: " + where); + CHECK_EQ(m.reasoning, k.msg.value("reasoning_content", std::string())); + CHECK_EQ(m.content, k.msg["content"].get()); + CHECK(no_markup(m.content)); + const json& calls = k.msg["tool_calls"]; + if (m.calls.size() != calls.size()) { + ::radtest::fail(__FILE__, __LINE__, "call count: " + where); + continue; + } + for (size_t i = 0; i < calls.size(); ++i) { + const json& fn = calls[i]["function"]; + CHECK_EQ(m.calls[i].name, fn["name"].get()); + CHECK(m.calls[i].closed); + /* The arguments as written, in the reply's order; JSON values keep their spacing. */ + CHECK(json::parse(m.calls[i].arguments) == json::parse(fn["arguments"].get())); + } + const std::string s = stream_all(p, reply); + if (!s.empty()) ::radtest::fail(__FILE__, __LINE__, std::string(k.what) + ": " + s); + /* What constrained decoding admits from the trigger on is the reply's call text. */ + const size_t at = reply.find(""); + REQUIRE(at != std::string::npos); + CHECK_EQ(object_admits(g->grammar, reply.substr(at)), 1); + } + CHECK_EQ(reply_parse(p, glm_reply(*g, cases[0].msg)).calls[0].arguments, + std::string("{\"path\":\"/a\",\"limit\":3}")); + + /* Every message the other formats are checked with, too. */ + size_t n = 0; + for (const json& msg : rendered_corpus()) { + const std::string reply = glm_reply(*g, msg); + if (reply.empty()) continue; + const ReplyMessage m = reply_parse(p, reply); + const size_t want = msg.contains("tool_calls") ? msg["tool_calls"].size() : 0; + bool ok = m.calls.size() == want && no_markup(m.content); + for (size_t i = 0; ok && i < want; ++i) { + const json& fn = msg["tool_calls"][i]["function"]; + ok = m.calls[i].name == fn["name"].get() && + round_trips(json::parse(fn["arguments"].get()), + json::parse(m.calls[i].arguments), true); + } + if (!ok) ::radtest::fail(__FILE__, __LINE__, "rendered: " + quote(reply) + "\n " + show(m)); + const std::string s = stream_all(p, reply, 512); + if (!s.empty()) ::radtest::fail(__FILE__, __LINE__, "rendered: " + s + "\n " + quote(reply)); + ++n; + } + CHECK(n > 10); +} + +/* Without a tag of its own the name is read until something shows it is no name, so an opener + * in prose, a stray name and a reply cut off anywhere must all stay readable. */ +TEST(glm53_reads_what_strays_from_its_grammar) { + const Glm* g = glm(); + REQUIRE(g != nullptr); + const ReplyParser& p = *g->parser; + bool strict = true; + + ReplyMessage m = reply_parse(p, "
Wrap a call in tags, then stop.", &strict); + CHECK(m.calls.empty()); + CHECK_EQ(m.content, std::string("Wrap a call in tags, then stop.")); + + /* GLM-4.5 put newlines around its tags. */ + m = reply_parse(p, "read\npath/a\n" + "", &strict); + CHECK(strict); + REQUIRE(m.calls.size() == 1); + CHECK_EQ(m.calls[0].name, std::string("read")); + CHECK_EQ(m.calls[0].arguments, std::string("{\"path\":\"/a\"}")); + + m = reply_parse(p, "\nreadpath/a" + "", &strict); + CHECK(!strict); + REQUIRE(m.calls.size() == 1); + CHECK_EQ(m.calls[0].name, std::string("read")); + + m = reply_parse(p, "nopea1" + "", &strict); + CHECK(!strict); + REQUIRE(m.calls.size() == 1); + CHECK_EQ(m.calls[0].name, std::string("nope")); + CHECK_EQ(m.calls[0].arguments, std::string("{\"a\":\"1\"}")); + + /* An unclosed reasoning block ends where a call begins. */ + m = reply_parse(p, "thinkingnow", &strict); + CHECK_EQ(m.reasoning, std::string("thinking")); + REQUIRE(m.calls.size() == 1); + CHECK_EQ(m.calls[0].name, std::string("now")); + + /* Cut off anywhere, the reply holds no markup in its content and names no other call. */ + const std::string reply = glm_reply(*g, message("Look.", "Reading.", + { call("read", { { "path", "/a" }, { "limit", 3 } }), call("now", json::object()) })); + for (size_t k = 0; k <= reply.size(); ++k) { + const ReplyMessage t = reply_parse(p, reply.substr(0, k)); + if (!no_markup(t.content) || t.calls.size() > 2 || + (!t.calls.empty() && t.calls[0].name != "read") || + (t.calls.size() == 2 && t.calls[1].name != "now")) + ::radtest::fail(__FILE__, __LINE__, "cut at " + std::to_string(k) + ": " + + quote(reply.substr(0, k)) + "\n " + show(t)); + } + + /* A tool whose name runs into a tag that ends names is refused at admission, by name. */ + const json bad = json::parse(R"([{"type":"function","function":{"name":"ab"}}])"); + ReplyOptions ro; + ro.tools = &bad; + std::shared_ptr rf; + std::shared_ptr rp; + std::string why; + CHECK_OK(ReplyFormat::compile(g->f, &rf, &why)); + CHECK(ReplyParser::create(rf, ro, &rp, &why) < 0); + CHECK(why.find("ab") != std::string::npos); +} + /* ================================================================== cost * * The legacy path re-parses the whole reply per chunk, O(n^2). The parser's own count of what it @@ -1802,3 +2144,4 @@ TEST(a_long_reply_holds_a_constant_number_of_bytes) { } RAD_TEST_MAIN() +