From d59e0bb003bb8a406dc349412c5ab4704d27a668 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Sat, 10 Oct 2026 12:41:05 +0000 Subject: [PATCH] gemma4: declare the reply format -- the thought channel and calls as one object Gemma 4's template is one llama.cpp reads with a hand-written handler, so the template analysis found no format in it: the server warned "this model's reply format cannot be described", returned the thought channel as content and refused every request with tools (HTTP 400). The plugin now states the format its tokenizer_config.json declares (`response_template`), in gemma4_chat_format.h, exported through RAD_ARCH_CHAT_FORMAT: thinking <|channel>thought\n ... , reasoning_anywhere calls <|tool_call>call:NAME{...}, repeated, triggers on <|tool_call> the object bare keys, strings between <|"|> and <|"|>, other values as JSON writes them The template closes an empty channel in the generation prompt when thinking is off and opens one after a tool response when it is on; RAD_CHAT_THINK_FROM_PROMPT reads both. llama.cpp's handler records an extra thought channel after the answer and a lone ; reasoning_anywhere reads the first as reasoning and drops the second, so neither reaches the content. chatparse_gemma4_test, against the model's own template (tests/data/chat/gemma4) and llama.cpp's Gemma 4 parser as the oracle (tests/legacy, which now takes a declared format): every reply the template renders reads back as the message it rendered, byte for byte as llama.cpp reads it; the shapes the model writes and the ways it leaves the format; thinking on, off, and after a tool response; reasoning_format none; a conversation with role:tool results rendered into the open turn and continued; every truncation, fuzzed replies and a 200 KB string under the streaming contract; the call grammar against llama.cpp's on rendered calls, tool_choice required and a response format; and the chat bridge serving it, with the decoder rendering <|"|>. arch_test holds the export to the header. End to end on the 31B QAT checkpoint, two R9700 at TP 2: 60 requests over greedy and temperature 1.0 / top_k 64 / top_p 0.95, streaming and not, thinking on and off. Every request with tools came back with finish_reason "tool_calls" and JSON arguments -- one call, two parallel calls, integer and boolean arguments -- every follow-up with role:tool results as an answer with finish_reason "stop", and no <|channel>, , <|tool_call> or <|"|> reached any content or reasoning_content. With thinking off the model writes <|channel>thought\n itself before its answer to a tool result; it is read as an empty thought. --- arch/gemma4_bf16/gemma4_bf16.cpp | 6 + arch/gemma4_bf16/gemma4_chat_format.h | 60 ++ tests/CMakeLists.txt | 2 +- tests/arch_test.cpp | 25 + tests/chatparse_gemma4_test.cpp | 849 +++++++++++++++++++++ tests/data/chat/gemma4/chat_template.jinja | 390 ++++++++++ tests/legacy/chatdiff.cpp | 5 + tests/legacy/chatdiff.h | 5 + 8 files changed, 1341 insertions(+), 1 deletion(-) create mode 100644 arch/gemma4_bf16/gemma4_chat_format.h create mode 100644 tests/chatparse_gemma4_test.cpp create mode 100644 tests/data/chat/gemma4/chat_template.jinja diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 8005148f..a12acb94 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -10,6 +10,8 @@ */ #include +#include "gemma4_chat_format.h" + #include #include #include @@ -879,11 +881,15 @@ static void step(RadCtx* c, const RadBatch* batch) { } } +/* The reply format: gemma4_chat_format.h. */ +const RadChatFormat* chat_format(const RadModelMeta*) { return chat_format_decl(); } + #ifndef RAD_ARCH_NO_EXPORTS RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0", "Gemma 4 dense (text-only), w4a8 from its CT-INT4 (compressed-tensors) release: " "sliding-window and proportional-RoPE global attention over a GemmaRMSNorm stream " "with GELU feed-forward, per-layer scalar scaling and soft-capped logits") +RAD_ARCH_CHAT_FORMAT(gemma4_bf16) #endif } /* namespace gemma4_bf16 */ diff --git a/arch/gemma4_bf16/gemma4_chat_format.h b/arch/gemma4_bf16/gemma4_chat_format.h new file mode 100644 index 00000000..7520d298 --- /dev/null +++ b/arch/gemma4_bf16/gemma4_chat_format.h @@ -0,0 +1,60 @@ +/* gemma4_chat_format.h -- how Gemma 4 spells a turn: its reasoning and its tool calls, as data. + * + * The chat template is one llama.cpp reads with a hand-written handler, so the template analysis + * finds nothing in it, and the engine would serve the model with no reasoning split and refuse + * every request that sends tools. The model's own tokenizer_config.json states the format instead + * (`response_template`), and this is that statement in the engine's terms: + * + * thinking <|channel>thought\n ... + * tool calls <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3,flag:true}, repeated + * the object unquoted keys, strings between <|"|> and <|"|> with their text verbatim, every + * other value as JSON writes it + * the turn ends at ; after its calls the model writes <|tool_response> and stops + * (generation_config.json names it beside and ) + * + * llama.cpp's handler records two habits of the model beyond that: an extra thought channel after + * the answer, and a lone . `reasoning_anywhere` reads the first as reasoning and drops + * the second, so neither reaches the content. + * + * Kept in a header of its own so the reply-format tests read the declaration the plugin exports + * rather than a copy of it. */ +#pragma once +#include "rad_builder.h" + +namespace gemma4_bf16 { + +inline const RadChatFormat* chat_format_decl() { + static const char* const kBreaks[] = { "<|tool_call>" }; + static const char* const kTriggers[] = { "<|tool_call>" }; + static const RadChatFormat f = [] { + RadChatFormat c{}; + c.struct_size = (uint32_t)sizeof(RadChatFormat); + c.name = "plugin:gemma4"; + c.reasoning_open = "<|channel>thought\n"; + c.reasoning_close = ""; + /* A call that starts inside an unclosed thought ends it there. */ + c.reasoning_breaks = kBreaks; + c.n_reasoning_breaks = 1; + /* Thinking off, the template closes an empty channel in the generation prompt; on, the + * model opens its own -- or, after a tool response, the prompt has opened it. */ + c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT; + c.reasoning_anywhere = 1; + + c.call_open = "<|tool_call>"; + c.call_close = ""; + c.name_prefix = "call:"; + c.name_suffix = ""; /* the name ends at the object's `{` */ + c.call_end = ""; /* and the object's `}` ends the call */ + c.args_form = RAD_CHAT_ARGS_OBJECT; + c.object_string_open = "<|\"|>"; + c.object_string_close = "<|\"|>"; + c.object_bare_keys = 1; + + c.triggers = kTriggers; + c.n_triggers = 1; + return c; + }(); + return &f; +} + +} /* namespace gemma4_bf16 */ diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 308cd96c..2e959c40 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -41,7 +41,7 @@ add_library(rad_legacy_toolparse STATIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy/toolp ${CMAKE_CURRENT_SOURCE_DIR}/legacy/chatdiff.cpp) target_link_libraries(rad_legacy_toolparse PUBLIC rad_core) target_include_directories(rad_legacy_toolparse PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy) -set(RAD_TESTS_WITH_LEGACY chatparse_test) +set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test) # relayout_parity_test holds each kernel library's relayout of libquant's planes to the recorded # hash of the bytes that library stores. libr4d needs a HIP toolchain to build and its layouts do diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 17ef69c2..527fe57c 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -3156,6 +3156,31 @@ TEST(declare_is_a_gemma4_trunk) { CHECK_EQ(count_op(b, "all_reduce"), 0); /* world 1 */ } +/* The reply format is the plugin's to state: Gemma 4's template is one the template analysis + * cannot read. Its calls are the object family -- a name and one object in Gemma's dialect -- + * and its thought channel may open again after the answer. The parser's reading of it is + * chatparse_gemma4_test's; this holds the export to what the header declares. */ +TEST(gemma4_declares_its_reply_format) { + RadModelMeta meta = gemma4_meta(); + const RadChatFormat* f = gemma4_bf16::chat_format(&meta); + REQUIRE(f != nullptr); + CHECK_EQ(f->struct_size, (uint32_t)sizeof(RadChatFormat)); + CHECK_EQ(f->args_form, (uint32_t)RAD_CHAT_ARGS_OBJECT); + CHECK_EQ(std::string(f->call_open), std::string("<|tool_call>")); + CHECK_EQ(std::string(f->call_close), std::string("")); + CHECK_EQ(std::string(f->name_prefix), std::string("call:")); + CHECK_EQ(std::string(f->name_suffix), std::string("")); + CHECK_EQ(std::string(f->object_string_open), std::string("<|\"|>")); + CHECK_EQ(std::string(f->object_string_close), std::string("<|\"|>")); + CHECK(f->object_bare_keys != 0); + CHECK_EQ(std::string(f->reasoning_open), std::string("<|channel>thought\n")); + CHECK_EQ(std::string(f->reasoning_close), std::string("")); + CHECK(f->reasoning_anywhere != 0); + REQUIRE(f->n_triggers == 1); + CHECK_EQ(std::string(f->triggers[0]), std::string("<|tool_call>")); + CHECK(f->arg_prefix == nullptr && f->arg_value_suffix == nullptr); +} + TEST(gemma4_declares_two_kv_groups_and_binds_the_schedule) { RadBuilder b; RadModelMeta meta = gemma4_meta(); diff --git a/tests/chatparse_gemma4_test.cpp b/tests/chatparse_gemma4_test.cpp new file mode 100644 index 00000000..6e62a944 --- /dev/null +++ b/tests/chatparse_gemma4_test.cpp @@ -0,0 +1,849 @@ +/* chatparse_gemma4_test.cpp -- Gemma 4's reply format: a reasoning channel, and calls written as a + * name and ONE object in a dialect of JSON. + * + * Gemma 4's template is one llama.cpp reads with a hand-written handler, so the template analysis + * finds no format in it and the plugin declares one (arch/gemma4_bf16/gemma4_chat_format.h): + * + * <|channel>thought\n ... reasoning + * <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3} a call, repeated for more + * + * Every case reads a reply under a request rendered through the model's REAL template + * (tests/data/chat/gemma4), and where the reply is within the format the answer is held, byte for + * byte, to llama.cpp's own Gemma 4 parser -- the PEG grammar and value mapper its handler builds + * (tests/legacy, the `old` side). Every reply is also streamed cut every way (chatdiff.h + * check_stream): each delta a prefix of the finished value, the deltas adding up to it, the bytes + * held under the format's bound, and a closed call's arguments JSON. + * + * The object family itself -- JSON behind a name tag or a function tag -- is chatparse_test's. + */ +#include "rad_test.h" + +#include "chatdiff.h" +#include "rad_builder.h" +#include "sample/gbnf.h" +#include "sample/vocab_view.h" +#include "server/adapters.h" +#include "text/chat.h" +#include "text/chatfmt.h" +#include "text/chatparse.h" +#include "text/tokenizer.h" + +#include "../arch/gemma4_bf16/gemma4_chat_format.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rad; +using namespace rad::chatdiff; +using json = nlohmann::ordered_json; + +/* ================================================================== fixtures */ + +static std::string fixture() { + std::ifstream f(std::string(RAD_CHAT_FIXTURES) + "/gemma4/chat_template.jinja"); + std::ostringstream ss; + ss << f.rdbuf(); + return ss.str(); +} + +/* The vocabulary's spellings: generation_config.json ends a turn on , and + * <|tool_response>. */ +static const Model& gemma() { + static const Model m = { "gemma4", "gemma4", "", "", + { "", "", "<|tool_response>" }, + gemma4_bf16::chat_format_decl() }; + return m; +} + +static Bench* bench(const ChatRequest& rq, const json& tools = agent_tools()) { + static std::map> cache; + const std::string key = describe(rq) + "|" + tools.dump(); + auto it = cache.find(key); + if (it != cache.end()) return it->second.get(); + auto b = std::make_unique(); + std::string why; + if (b->load(gemma(), fixture(), &why) < 0 || b->bind(rq, tools, &why) < 0) { + ::radtest::fail(__FILE__, __LINE__, "gemma4 (" + describe(rq) + "): " + why); + return nullptr; + } + return (cache[key] = std::move(b)).get(); +} + +static ChatRequest thinking(bool on) { + ChatRequest r; + r.thinking = on; + return r; +} + +static std::string quote(const std::string& s) { + return json(s).dump(-1, ' ', false, json::error_handler_t::replace); +} + +/* One call as the model writes it. `args` is the object's inside. */ +static std::string G(const std::string& name, const std::string& args) { + return "<|tool_call>call:" + name + "{" + args + "}"; +} +static const std::string Q = "<|\"|>"; +static std::string S(const std::string& text) { return Q + text + Q; } + +/* ================================================================== the streaming checks */ + +static std::vector every(size_t n, size_t step) { + std::vector c; + for (size_t i = step; i < n; i += step) c.push_back(i); + return c; +} + +/* Every cut of the reply against its one-shot parse: one piece, byte by byte, token-sized pieces, + * and every two-way split. */ +static std::string stream_all(const ReplyParser& p, const std::string& text) { + const ReplyMessage expect = reply_parse(p, text); + std::string err = check_stream(p, text, {}, expect); + if (err.empty()) err = check_stream(p, text, every(text.size(), 1), expect); + std::mt19937 rng(11); + for (int k = 0; err.empty() && k < 3; ++k) { + std::vector c; + for (size_t at = 1 + rng() % 5; at < text.size(); at += 1 + rng() % 7) c.push_back(at); + err = check_stream(p, text, c, expect); + } + for (size_t k = 1; err.empty() && k < text.size() && text.size() <= 2048; ++k) + err = check_stream(p, text, { k }, expect); + return err; +} + +static void streams(const ReplyParser& p, const std::string& text, const std::string& what) { + const std::string err = stream_all(p, text); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, what + ": " + err + "\n reply: " + quote(text)); + ++::radtest::checks(); +} + +static ReplyMessage parse(const ReplyParser& p, const std::string& text, bool* strict = nullptr) { + return reply_parse(p, text, strict); +} + +static std::shared_ptr parser(const std::string& gp, bool tools = true, + bool reasoning = true, bool parallel = true) { + static std::shared_ptr rf = [] { + ChatFormat f; + std::string why; + std::shared_ptr r; + if (chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why) < 0 || + ReplyFormat::compile(f, &r, &why) < 0) + ::radtest::fail(__FILE__, __LINE__, "gemma4 format: " + why); + return r; + }(); + ReplyOptions ro; + ro.generation_prompt = gp; + ro.extract_reasoning = reasoning; + ro.tools = tools ? &agent_tools() : nullptr; + ro.parallel_tool_calls = parallel; + ro.terminators = gemma().terminators; + std::shared_ptr p; + std::string why; + if (ReplyParser::create(rf, ro, &p, &why) < 0) + ::radtest::fail(__FILE__, __LINE__, "gemma4 parser: " + why); + return p; +} + +/* The three generation prompts a reply follows: a turn with thinking off (the template closes an + * empty channel), a turn with thinking on (the model opens its own), and the continuation after a + * tool response with thinking on (the template has opened the channel). With thinking off a + * continuation has no generation prompt at all. */ +static const std::string kOff = "<|turn>model\n<|channel>thought\n"; +static const std::string kOn = "<|turn>model\n"; +static const std::string kAfter = "<|channel>thought\n"; + +/* ================================================================== the declaration */ + +TEST(the_declaration_is_a_format_the_parser_runs) { + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + CHECK_OK(chat_format_check(f, &why)); + CHECK(f.object_args()); + CHECK(f.reasoning_anywhere); + CHECK_EQ(f.object_string_open, Q); + CHECK_EQ(chat_format_describe(f), + std::string("plugin:gemma4: reasoning \"<|channel>thought\\n\"..\"\" " + "anywhere; calls \"<|tool_call>\"\"call:\"NAME\"\" {OBJECT, strings " + "\"<|\\\"|>\"..\"<|\\\"|>\", bare keys} \"\"\"\"; grammar on " + "\"<|tool_call>\"")); + /* What the decoder must render as text: every delimiter, the string's included -- without it + * a string argument reaches the parser with its quotes gone. */ + const std::vector m = chat_format_markers(f); + for (const char* want : { "<|channel>thought", "", "<|tool_call>", "", + "call:", "<|\"|>" }) + CHECK(std::find(m.begin(), m.end(), std::string(want)) != m.end()); +} + +/* A plugin compiled against the header before the object family reads its new fields as zero: + * the tagged family, no dialect, reasoning at the start only -- and Gemma's declaration read that + * way is refused by name rather than run wrongly. */ +TEST(an_older_struct_reads_the_object_fields_as_zero) { + RadChatFormat c = *gemma4_bf16::chat_format_decl(); + c.struct_size = (uint32_t)offsetof(RadChatFormat, args_form); + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(&c, &f, &why)); + CHECK(!f.object_args()); + CHECK(f.object_string_open.empty()); + 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); +} + +TEST(an_object_format_the_parser_cannot_read_is_refused_by_name) { + auto refused = [](void (*edit)(RadChatFormat&), const char* word) { + RadChatFormat c = *gemma4_bf16::chat_format_decl(); + edit(c); + ChatFormat f; + std::string why; + if (chat_format_from_abi(&c, &f, &why) < 0) return false; + const bool no = chat_format_check(f, &why) == RAD_E_UNSUPPORTED; + if (!no || why.find(word) == std::string::npos) + ::radtest::fail(__FILE__, __LINE__, std::string("expected a refusal naming '") + + word + "', got: " + (no ? why : "accepted")); + return no; + }; + CHECK(refused([](RadChatFormat& c) { c.arg_prefix = ""; }, "arg_*")); + CHECK(refused([](RadChatFormat& c) { c.object_string_close = nullptr; }, "together")); + CHECK(refused([](RadChatFormat& c) { c.object_string_open = c.object_string_close = " "; }, + "whitespace")); + CHECK(refused([](RadChatFormat& c) { c.object_string_open = "q"; }, "bare word")); + CHECK(refused([](RadChatFormat& c) { + c.object_string_open = c.object_string_close = ""; c.call_close = ""; }, "closes the call")); + CHECK(refused([](RadChatFormat& c) { c.call_close = ""; }, "punctuation")); + CHECK(refused([](RadChatFormat& c) { c.call_close = "<|"; }, "told apart")); + CHECK(refused([](RadChatFormat& c) { c.args_form = 7; }, "RAD_CHAT_ARGS")); + CHECK(refused([](RadChatFormat& c) { c.reasoning_open = ""; }, "reasoning_anywhere")); + CHECK(refused([](RadChatFormat& c) { c.call_open = "<|channel>thought"; c.reasoning_breaks = nullptr; + c.n_reasoning_breaks = 0; }, "content")); + /* The tagged family is untouched: a dialect field there is refused, not ignored. */ + CHECK(refused([](RadChatFormat& c) { + c.args_form = RAD_CHAT_ARGS_TAGGED; + c.name_suffix = ">"; c.call_end = ""; c.arg_prefix = "render_reply(msg); + REQUIRE(!reply.empty()); + bool strict = false; + const ReplyMessage m = b->new_parse(reply, &strict); + const legacy::Answer o = b->old_parse(reply); + + /* The calls come back as the message had them, arguments as JSON values. */ + const size_t ncalls = msg.contains("tool_calls") ? msg["tool_calls"].size() : 0; + REQUIRE_EQ(m.calls.size(), ncalls); + for (size_t i = 0; i < ncalls; ++i) { + const json& want = msg["tool_calls"][i]["function"]; + CHECK_EQ(m.calls[i].name, want["name"].get()); + CHECK(m.calls[i].closed); + /* Compared as values: the template writes keys in sorted order. */ + CHECK(nlohmann::json::parse(m.calls[i].arguments) == + nlohmann::json::parse(want["arguments"].get())); + } + const std::string r = msg.contains("reasoning_content") ? msg["reasoning_content"].get() : ""; + CHECK_EQ(m.reasoning, r.empty() ? r : r + "\n"); + CHECK_EQ(m.content, msg["content"].get()); + + /* llama.cpp's parser reads the same calls and reasoning, byte for byte. Where the template + * wrote content AFTER the calls -- its order for a past turn, not the model's -- the old + * parser drops that content and the new one keeps it, leniently. */ + CHECK_EQ(o.calls.size(), m.calls.size()); + for (size_t i = 0; i < std::min(o.calls.size(), m.calls.size()); ++i) { + CHECK_EQ(o.calls[i].name, m.calls[i].name); + CHECK_EQ(o.calls[i].arguments, m.calls[i].arguments); + } + CHECK_EQ(o.reasoning, m.reasoning); + const bool after = ncalls > 0 && !msg["content"].get().empty(); + CHECK_EQ(strict, !after); + if (!after) CHECK_EQ(o.content, m.content); + streams(b->parser(), reply, "rendered reply"); + ++read; + } + CHECK(read > 10); +} + +/* Every prefix of a rendered reply -- a reply the decoder stopped anywhere -- streams to its own + * one-shot parse, and a call the reply ended inside reads back as its text. */ +TEST(every_truncation_of_a_rendered_reply_keeps_the_contract) { + Bench* b = bench(thinking(true)); + REQUIRE(b != nullptr); + for (const json& msg : rendered_corpus()) { + const std::string reply = b->render_reply(msg); + for (size_t n = 1; n <= reply.size(); n += 1 + n / 64) { + const std::string cut = sanitize(reply.substr(0, n)); + const std::string err = check_stream(b->parser(), cut, every(cut.size(), 3), + reply_parse(b->parser(), cut)); + if (!err.empty()) + ::radtest::fail(__FILE__, __LINE__, err + "\n reply: " + quote(cut)); + std::unique_ptr s = b->parser().open(); + s->feed(cut, nullptr); + s->finish(nullptr); + const ReplyMessage& m = s->message(); + if (!m.calls.empty() && !m.calls.back().closed) { + const std::string text = s->content_with_open_call(cut); + CHECK(text.find("<|tool_call>call:") != std::string::npos); + } + } + ++::radtest::checks(); + } +} + +/* ================================================================== the decided shapes + * + * Replies written the way the model writes them, and the ways it leaves its format. Each reads as + * stated, streams under the contract, and -- where `oracle` says so -- agrees with llama.cpp's + * parser byte for byte. */ + +struct Call { std::string name, args; bool closed = true; }; +struct Shape { + const char* what; + std::string gp; + std::string reply; + std::string content, reasoning; + std::vector calls; + bool strict; + bool oracle; /* llama.cpp's parser reads it the same */ +}; + +static std::vector shapes() { + const std::string ls = G("bash", "command:" + S("ls")); + const std::string LS = "{\"command\":\"ls\"}"; + std::vector v = { + { "an answer", kOff, "The answer is 4.", "The answer is 4.", "", {}, true, true }, + { "a call", kOff, ls, "", "", { { "bash", LS } }, true, true }, + { "a sentence, then a call", kOff, "Let me look.\n" + ls, "Let me look.", "", + { { "bash", LS } }, true, true }, + { "two calls", kOff, ls + G("read", "limit:40,path:" + S("/a")), "", "", + { { "bash", LS }, { "read", "{\"limit\":40,\"path\":\"/a\"}" } }, true, true }, + { "two calls on two lines", kOff, ls + "\n" + G("read", "path:" + S("/a")), "", "", + { { "bash", LS }, { "read", "{\"path\":\"/a\"}" } }, true, false }, + { "every kind of value", kOff, + G("configure", "extra:{a:[1,2,[]],b:{c:null},d:{}},label:" + S("") + + ",level:-1.5e3,mode:" + S("fast") + ",tags:[" + S("x") + "," + S("y") + + "],verbose:false"), + "", "", { { "configure", "{\"extra\":{\"a\":[1,2,[]],\"b\":{\"c\":null},\"d\":{}}," + "\"label\":\"\",\"level\":-1.5e3,\"mode\":\"fast\"," + "\"tags\":[\"x\",\"y\"],\"verbose\":false}" } }, true, true }, + { "a call that takes no arguments", kOff, G("ping", ""), "", "", { { "ping", "{}" } }, + true, true }, + { "a string holding what JSON escapes", kOff, + G("write", "content:" + S("a \"q\" \\ b\n\tc\x01 Γ© πŸš€") + ",path:" + S("/x")), "", "", + { { "write", "{\"content\":\"a \\\"q\\\" \\\\ b\\n\\tc\\u0001 Γ© πŸš€\",\"path\":\"/x\"}" } }, + true, true }, + { "a string holding the format's own punctuation", kOff, + G("write", "content:" + S("{a:1,} [<|tool_call>call:x{}] <|\" .") + + ",path:" + S("/x")), "", "", + { { "write", "{\"content\":\"{a:1,} [<|tool_call>call:x{}] <|\\\" .\"," + "\"path\":\"/x\"}" } }, true, true }, + /* Text ending in the start of the delimiter reads as written. (No grammar of this shape + * can write it -- llama.cpp's cannot either.) */ + { "a string ending in the start of its own delimiter", kOff, + G("write", "content:" + S("a <|\"") + ",path:" + S("/x")), "", "", + { { "write", "{\"content\":\"a <|\\\"\",\"path\":\"/x\"}" } }, true, true }, + /* llama.cpp's key rule takes everything up to the colon, delimiters included, and + * hands the client a key `<|"|>path<|"|>`. */ + { "a key written as a string", kOff, G("read", S("path") + ":" + S("/a")), "", "", + { { "read", "{\"path\":\"/a\"}" } }, true, false }, + /* And keeps the blank after a number, `"limit":3 }`, which is no JSON. */ + { "whitespace inside the object", kOff, G("read", " path: " + S("/a") + ",\n limit: 3 "), + "", "", { { "read", "{\"path\":\"/a\",\"limit\":3}" } }, true, false }, + + /* reasoning */ + { "thinking on: a thought, then an answer", kOn, + "<|channel>thought\nIt is two plus two.\nThe answer is 4.", "The answer is 4.", + "It is two plus two.\n", {}, true, true }, + { "thinking on: no thought at all", kOn, "The answer is 4.", "The answer is 4.", "", {}, + true, true }, + { "thinking on: a thought, then a call", kOn, + "<|channel>thought\nList it.\n" + ls, "", "List it.\n", { { "bash", LS } }, true, + true }, + { "a thought never closed before a call", kOn, "<|channel>thought\nList it.\n" + ls, "", + "List it.\n", { { "bash", LS } }, true, false }, + { "after a tool response, thinking on", kAfter, + "The tool says 18.\nIt is 18 degrees.", "It is 18 degrees.", + "The tool says 18.\n", {}, true, false }, + { "after a tool response, thinking off", "", "It is 18 degrees.", "It is 18 degrees.", "", + {}, true, false }, + { "an empty thought after the answer", kOff, "The answer is 4.<|channel>thought\n", + "The answer is 4.", "", {}, true, true }, + { "a thought in the middle of the answer", kOff, + "First.\n<|channel>thought\nhm\nSecond.", "First.\nSecond.", "hm\n", {}, true, + true }, + { "a close with no thought open", kOff, "The answer is 4.", "The answer is 4.", "", + {}, false, false }, + { "the turn's terminator left on", kOff, "The answer is 4.", "The answer is 4.", "", + {}, true, false }, + + /* leaving the object */ + { "a JSON string", kOff, G("bash", "command:\"ls -la\""), "", "", + { { "bash", "{\"command\":\"ls -la\"}" } }, false, false }, + { "JSON escapes, a pair and a stray surrogate", kOff, + G("bash", "command:\"a\\\"b\\\\c\\u00e9\\ud83d\\ude00\\ud800x\\q\""), "", "", + { { "bash", "{\"command\":\"a\\\"b\\\\c\\u00e9\\ud83d\\ude00\\ufffdx\\\\q\"}" } }, false, + false }, + { "Python literals", kOff, G("configure", "verbose:True,nothing:None"), "", "", + { { "configure", "{\"verbose\":true,\"nothing\":null}" } }, false, false }, + { "a bare word", kOff, G("configure", "mode:fast,level:01"), "", "", + { { "configure", "{\"mode\":\"fast\",\"level\":\"01\"}" } }, false, false }, + { "a trailing comma", kOff, G("read", "path:" + S("/a") + ","), "", "", + { { "read", "{\"path\":\"/a\"}" } }, false, false }, + { "a missing comma", kOff, G("read", "path:" + S("/a") + " limit:3"), "", "", + { { "read", "{\"path\":\"/a\",\"limit\":3}" } }, false, false }, + { "a key with no value", kOff, G("read", "path:,limit"), "", "", + { { "read", "{\"path\":null,\"limit\":null}" } }, false, false }, + { "the wrong closing bracket", kOff, G("configure", "tags:[" + S("x") + "}"), "", "", + { { "configure", "{\"tags\":[\"x\"]}" } }, false, false }, + { "an object the call's close cuts off", kOff, + "<|tool_call>call:configure{extra:{a:[1,{b:" + S("c") + "" + ls, "", "", + { { "configure", "{\"extra\":{\"a\":[1,{\"b\":\"c\"}]}}" }, { "bash", LS } }, false, false }, + /* llama.cpp's grammar has no arm for it and reads no call at all. */ + { "a call to a function that is not a tool", kOff, G("frobnicate", "x:1"), "", "", + { { "frobnicate", "{\"x\":1}" } }, false, false }, + { "a call written without its wrapper", kOff, "call:bash{command:" + S("ls") + "}", "", "", + { { "bash", LS } }, false, false }, + { "the name prefix in prose", kOff, "This is what I call: a plan, and call:me{ maybe.", + "This is what I call: a plan, and call:me{ maybe.", "", {}, true, true }, + { "a reply that ends inside a call", kOff, + "<|tool_call>call:write{path:" + S("/a") + ",content:" + Q + "half", "", "", + { { "write", "{\"path\":\"/a\",\"content\":\"half", false } }, true, false }, + }; + return v; +} + +TEST(what_gemma_writes_reads_as_decided) { + for (const Shape& s : shapes()) { + std::shared_ptr p = parser(s.gp); + bool strict = false; + const ReplyMessage m = parse(*p, s.reply, &strict); + const std::string tag = std::string(s.what) + ": " + quote(s.reply) + "\n got " + show(m); + if (m.content != s.content || m.reasoning != s.reasoning || m.calls.size() != s.calls.size() || + strict != s.strict) + ::radtest::fail(__FILE__, __LINE__, tag + (strict ? " (strict)" : " (lenient)")); + for (size_t i = 0; i < std::min(m.calls.size(), s.calls.size()); ++i) + if (m.calls[i].name != s.calls[i].name || m.calls[i].arguments != s.calls[i].args || + m.calls[i].closed != s.calls[i].closed) + ::radtest::fail(__FILE__, __LINE__, tag); + for (const ReplyCall& c : m.calls) + if (c.closed && !json::accept(c.arguments)) + ::radtest::fail(__FILE__, __LINE__, tag + "\n arguments are no JSON"); + streams(*p, s.reply, s.what); + } +} + +/* Where the reply is within the format, llama.cpp's own Gemma 4 parser -- run on the generation + * prompt and the reply, as its handler runs it -- reads exactly what this one reads. */ +TEST(the_shapes_in_the_format_read_as_llama_cpp_reads_them) { + int compared = 0; + for (const Shape& s : shapes()) { + if (!s.oracle) continue; + const bool on = s.gp == kOn; + Bench* b = bench(thinking(on)); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->prompt().generation_prompt, s.gp); + const legacy::Answer o = b->old_parse(s.reply); + const ReplyMessage m = b->new_parse(s.reply); + bool same = !o.strict_failed && o.content == m.content && o.reasoning == m.reasoning && + o.calls.size() == m.calls.size(); + for (size_t i = 0; same && i < o.calls.size(); ++i) + same = o.calls[i].name == m.calls[i].name && o.calls[i].arguments == m.calls[i].arguments; + if (!same) + ::radtest::fail(__FILE__, __LINE__, std::string(s.what) + ": " + quote(s.reply) + + "\n old: " + show(o) + "\n new: " + show(m)); + ++compared; + } + CHECK(compared >= 15); +} + +/* ================================================================== the request switches */ + +TEST(thinking_off_starts_the_reply_after_the_closed_channel) { + Bench* b = bench(thinking(false)); + REQUIRE(b != nullptr); + CHECK_EQ(b->prompt().generation_prompt, kOff); + const ReasoningMarkers rm = b->parser().reasoning(); + CHECK_EQ(rm.open, std::string("<|channel>thought")); + CHECK_EQ(rm.close, std::string("")); + CHECK(!rm.starts_open); + + Bench* on = bench(thinking(true)); + REQUIRE(on != nullptr); + CHECK_EQ(on->prompt().generation_prompt, kOn); + CHECK(!on->parser().reasoning().starts_open); + /* The system turn carries the thinking switch. */ + CHECK(on->prompt().prompt.find("<|turn>system\n<|think|>\n") != std::string::npos); + CHECK(b->prompt().prompt.find("<|think|>") == std::string::npos); + + CHECK(parser(kAfter)->reasoning().starts_open); + CHECK(!parser("")->reasoning().starts_open); +} + +/* reasoning_format "none": the channel stays in the content as the model wrote it, and with it + * the call grammar's break -- a call still ends the text before it. */ +TEST(reasoning_format_none_keeps_the_channel_in_the_content) { + std::shared_ptr p = parser(kOn, true, /*reasoning=*/false); + const std::string reply = "<|channel>thought\nhm\nYes." + + G("bash", "command:" + S("ls")); + const ReplyMessage m = parse(*p, reply); + CHECK_EQ(m.content, std::string("<|channel>thought\nhm\nYes.")); + CHECK(m.reasoning.empty()); + REQUIRE_EQ(m.calls.size(), (size_t)1); + streams(*p, reply, "reasoning none"); +} + +/* A request that sent no tools reads call syntax as the text it is -- but the thought channel is + * still the model's reasoning, wherever it opens. */ +TEST(without_tools_a_call_is_text_and_a_late_channel_is_still_reasoning) { + std::shared_ptr p = parser(kOff, /*tools=*/false); + const std::string reply = "Use <|tool_call>call:bash{} to run it.<|channel>thought\nx\n"; + const ReplyMessage m = parse(*p, reply); + CHECK_EQ(m.content, std::string("Use <|tool_call>call:bash{} to run it.")); + CHECK_EQ(m.reasoning, std::string("x\n")); + CHECK(m.calls.empty()); + streams(*p, reply, "no tools"); +} + +TEST(parallel_tool_calls_false_still_reads_a_second_call) { + std::shared_ptr p = parser(kOff, true, true, /*parallel=*/false); + bool strict = true; + const ReplyMessage m = parse(*p, G("bash", "command:" + S("ls")) + G("bash", "command:" + S("pwd")), &strict); + CHECK_EQ(m.calls.size(), (size_t)2); + CHECK(!strict); +} + +/* ================================================================== a conversation + * + * The turn after a call: the assistant message carries the call, a `role: tool` message its + * result, and the template writes both into the model's own turn -- the call in the model's + * spelling, the result as a response block -- and leaves the turn open for the model to go on. */ +static json conversation(bool two_calls) { + json calls = json::array(); + calls.push_back({ { "id", "c1" }, { "type", "function" }, + { "function", { { "name", "read" }, { "arguments", "{\"path\":\"/a\",\"limit\":3}" } } } }); + if (two_calls) + calls.push_back({ { "id", "c2" }, { "type", "function" }, + { "function", { { "name", "bash" }, { "arguments", "{\"command\":\"ls\"}" } } } }); + json msgs = json::array({ { { "role", "user" }, { "content", "Read /a." } }, + { { "role", "assistant" }, { "content", "" }, { "tool_calls", calls } }, + { { "role", "tool" }, { "tool_call_id", "c1" }, { "content", "line one" } } }); + if (two_calls) + msgs.push_back({ { "role", "tool" }, { "tool_call_id", "c2" }, { "content", "a.txt" } }); + return msgs; +} + +TEST(a_tool_result_renders_into_the_open_turn_and_the_reply_goes_on) { + for (bool on : { false, true }) { + for (bool two : { false, true }) { + ChatTemplate t; + CHECK_OK(t.load(fixture(), "", "")); + ChatOptions opt; + opt.enable_thinking = on; + ChatPrompt p; + REQUIRE_EQ(t.apply(conversation(two), agent_tools(), opt, &p), RAD_OK); + const std::string want = + "<|turn>model\n<|tool_call>call:read{limit:3,path:<|\"|>/a<|\"|>}" + + std::string(two ? "<|tool_call>call:bash{command:<|\"|>ls<|\"|>}" : "") + + "<|tool_response>response:read{value:<|\"|>line one<|\"|>}" + + std::string(two ? "<|tool_response>response:bash{value:<|\"|>a.txt<|\"|>}" + : ""); + if (p.prompt.find(want) == std::string::npos) + ::radtest::fail(__FILE__, __LINE__, "the turn is not rendered as " + quote(want) + + "\n prompt: " + quote(p.prompt)); + /* The model goes on in the same turn: thinking off with nothing written for it, + * thinking on inside a channel the template opened. */ + CHECK_EQ(p.generation_prompt, std::string(on ? kAfter : "")); + CHECK(p.prompt.size() >= want.size() && + p.prompt.compare(p.prompt.size() - p.generation_prompt.size() - 0, + p.generation_prompt.size(), p.generation_prompt) == 0); + + std::shared_ptr rp = parser(p.generation_prompt); + const std::string reply = on ? "The file has one line.\nIt reads \"line one\"." + : "It reads \"line one\"."; + const ReplyMessage m = parse(*rp, reply); + CHECK_EQ(m.content, std::string("It reads \"line one\".")); + CHECK_EQ(m.reasoning, std::string(on ? "The file has one line.\n" : "")); + streams(*rp, reply, "after a tool result"); + } + } +} + +/* ================================================================== fuzz */ + +static std::vector fragments() { + return { "<|tool_call>", "", "call:", "call:bash", "call:read", "{", "}", "[", "]", + ",", ":", Q, "<|\"", "<|", "|>", "<|channel>thought\n", "", "<|channel>", + "\"", "\\", "\\u", "\\ud83d", "true", "None", "-1.5e3", "path", "command", "x", "\n", + " ", "δΈ­", "πŸš€", "", "", "<|tool_response>" }; +} + +TEST(fuzzed_replies_keep_the_contract) { + std::mt19937 rng(3); + const std::vector frag = fragments(); + const std::vector seeds = { + G("configure", "extra:{a:[1,{b:" + S("c") + "}]},tags:[" + S("x") + "]"), + "Sure.\n" + G("bash", "command:" + S("ls -la")) + G("read", "path:" + S("/a") + ",limit:3"), + "<|channel>thought\nPlan.\nDone.<|channel>thought\n", + G("write", "content:\"a\\nb\\u00e9\",path:" + S("/x")), + }; + int n = 0; + for (const std::string& gp : { kOff, kOn, kAfter }) { + std::shared_ptr p = parser(gp); + for (const std::string& seed : seeds) + for (int k = 0; k < 60; ++k) { + const std::string text = sanitize(mutate(rng, seed, frag)); + const std::string err = check_stream(*p, text, every(text.size(), 1), + reply_parse(*p, text)); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err + "\n reply: " + quote(text)); + ++n; + } + } + CHECK(n > 0); +} + +/* A long reply holds a bounded number of bytes, whatever it holds: a file written into a string + * streams as it arrives. */ +TEST(a_long_string_streams_and_holds_a_bounded_number_of_bytes) { + std::string file; + while (file.size() < 200000) file += " x = compute(a, b) # & \"quoted\" <| ]] \\n\n"; + const std::string reply = "<|channel>thought\nWriting it.\n" + + G("write", "content:" + S(file) + ",path:" + S("/big.py")); + std::shared_ptr p = parser(kOn); + const std::string err = check_stream(*p, reply, every(reply.size(), 7), reply_parse(*p, reply)); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + const ReplyMessage m = parse(*p, reply); + REQUIRE_EQ(m.calls.size(), (size_t)1); + CHECK(json::parse(m.calls[0].arguments)["content"] == file); +} + +/* ================================================================== the grammar */ + +static const SimpleVocab& printable() { + static const SimpleVocab v = [] { + SimpleVocab s; + for (int c = 32; c < 127; ++c) s.add(std::string(1, (char)c)); + s.add("\n"); + s.add("\t"); + return s; + }(); + return v; +} + +/* 1 complete, 0 admitted but unfinished or refused, -1 does not compile. */ +static int admits(const std::string& gbnf, const std::string& prefix, const std::string& text) { + std::unique_ptr gr; + std::string err; + if (GbnfGrammar::create(gbnf, "root", &printable(), false, {}, {}, &gr, &err) < 0) return -1; + if (gr->accept_str(prefix) < 0 || gr->accept_str(text) < 0) return 0; + return gr->complete() ? 1 : 0; +} + +static std::string grammar_for(const ChatGrammarRequest& gq) { + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + ChatGrammar g; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + return g.text; +} + +/* The lazy call grammar admits every call the template writes and every strict call above, as + * llama.cpp's own Gemma 4 grammar does; it refuses what leaves the dialect. */ +TEST(the_call_grammar_admits_what_the_model_writes_and_refuses_the_rest) { + Bench* b = bench(thinking(true)); + REQUIRE(b != nullptr); + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + gq.generation_prompt = b->prompt().generation_prompt; + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + ChatGrammar g; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + CHECK(g.lazy); + CHECK(g.trigger_words == std::vector{ "<|tool_call>" }); + const std::string& vendored = b->prompt().grammar; + + int seen = 0; + for (const json& msg : rendered_corpus()) { + std::string reply = b->render_reply(msg); + const size_t at = reply.find("<|tool_call>"); + if (at == std::string::npos) continue; + reply = reply.substr(at, reply.rfind("") + 12 - at); + if (reply.find_first_of("\x01") != std::string::npos) continue; + CHECK_EQ(admits(g.text, "", reply), 1); + CHECK_EQ(admits(vendored, "", reply), 1); + ++seen; + } + CHECK(seen > 8); + for (const Shape& s : shapes()) { + if (!s.strict || s.calls.empty() || s.reply.find("\x01") != std::string::npos) continue; + const size_t at = s.reply.find("<|tool_call>"); + if (at == std::string::npos || !s.calls.back().closed) continue; + const std::string calls = s.reply.substr(at, s.reply.rfind("") + 12 - at); + if (s.reply.find("\n<|tool_call>") != std::string::npos) continue; /* a line between calls */ + if (std::string(s.what) == "whitespace inside the object" || + std::string(s.what) == "a string ending in the start of its own delimiter") + continue; + if (admits(g.text, "", calls) != 1) + ::radtest::fail(__FILE__, __LINE__, std::string("refused: ") + s.what + " " + quote(calls)); + } + for (const std::string& bad : { + G("bash", "command:ls"), /* a bare word */ + G("bash", "command:\"ls\""), /* a JSON string */ + G("bash", "command:" + S("ls") + ","), /* a trailing comma */ + "<|tool_call>call:bash{command:" + S("ls") + "", /* the object unclosed */ + G("frobnicate", "x:1"), /* not a tool */ + "<|tool_call>call:bash {command:" + S("ls") + "}", /* a space after the name */ + G("bash", "command:True"), + }) + CHECK_EQ(admits(g.text, "", bad), 0); +} + +/* tool_choice "required" makes the grammar the whole reply: from the generation prompt, an + * optional thought, then the calls and nothing after them; a named function admits that one, and + * parallel_tool_calls false one call. */ +TEST(a_required_call_is_the_whole_reply) { + for (const std::string& gp : { kOff, kOn }) { + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + gq.generation_prompt = gp; + gq.require_call = true; + const std::string any = grammar_for(gq); + gq.parallel_tool_calls = false; + const std::string one = grammar_for(gq); + gq.parallel_tool_calls = true; + gq.only_tool = "read"; + const std::string rd = grammar_for(gq); + const std::string ls = G("bash", "command:" + S("ls")), ra = G("read", "path:" + S("/a")); + const std::string T = gp == kOn ? "<|channel>thought\nPlan.\n" : ""; + CHECK_EQ(admits(any, gp, T + ls), 1); + CHECK_EQ(admits(any, gp, T + ls + ra), 1); + CHECK_EQ(admits(any, gp, T + "The answer."), 0); + CHECK_EQ(admits(any, gp, T + ls + "Done."), 0); + CHECK_EQ(admits(one, gp, T + ls), 1); + CHECK_EQ(admits(one, gp, T + ls + ra), 0); + CHECK_EQ(admits(rd, gp, T + ra), 1); + CHECK_EQ(admits(rd, gp, T + ls), 0); + } +} + +TEST(a_response_format_is_the_whole_reply) { + const json schema = json::parse(R"({"type":"object","properties":{"n":{"type":"integer"}},"required":["n"]})"); + ChatGrammarRequest gq; + gq.json_schema = &schema; + gq.generation_prompt = kOff; + const std::string g = grammar_for(gq); + CHECK_EQ(admits(g, kOff, "{\"n\": 3}"), 1); + CHECK_EQ(admits(g, kOff, "```json\n{\"n\": 3}\n```"), 1); + CHECK_EQ(admits(g, kOff, "{\"n\": \"x\"}"), 0); +} + +/* ================================================================== the server's view + * + * The chat bridge serves the model from the plugin's declaration: tool requests are no longer + * refused, the grammar comes from the format, and the decoder renders the dialect's string + * delimiter -- a control token like the format's tags -- so the parser sees it. */ +static std::shared_ptr gemma_vocab() { + VocabBuild vb; + vb.tokens = { "", "", "", "a", "<|tool_call>", "", "<|tool_response>", + "", "<|\"|>", "<|channel>", "", "<|turn>", "", + "thought", "call:" }; + vb.types.assign(vb.tokens.size(), RAD_TT_CONTROL); + vb.types[3] = vb.types[13] = vb.types[14] = RAD_TT_NORMAL; + /* The letters the markers' text is spelled with, so a marker tokenises whole. */ + for (const char* c : { "t", "h", "o", "u", "g", "c", "l", ":" }) { + vb.tokens.push_back(c); + vb.types.push_back(RAD_TT_NORMAL); + } + vb.bos = 2; + vb.eos = 1; + vb.chat_template = fixture(); + /* generation_config.json: eos_token_id [1, 106, 50] -- here , , <|tool_response>. */ + vb.eos_ids = { 1, 12, 6 }; + auto v = std::make_shared(); + return v->load(std::move(vb)) >= 0 ? v : nullptr; +} + +TEST(the_chat_bridge_serves_gemma_from_its_declaration) { + std::shared_ptr v = gemma_vocab(); + REQUIRE(v != nullptr); + CHECK(v->is_eog(6)); /* <|tool_response>: after its calls the model stops there */ + server::ChatTemplateBridge br; + CHECK_OK(br.init(*v, gemma4_bf16::chat_format_decl(), "gemma4_bf16")); + CHECK(br.supports_tools()); + CHECK(br.tool_refusal().empty()); + + server::ChatRenderOptions opt; + opt.enable_thinking = false; + server::ChatRender r; + std::string why; + const json msgs = json::array({ { { "role", "user" }, { "content", "List /work." } } }); + REQUIRE_EQ(br.apply(msgs, agent_tools(), opt, &r, &why), RAD_OK); + CHECK_EQ(r.generation_prompt, kOff); + CHECK(r.grammar_lazy); + REQUIRE_EQ(r.grammar_triggers.size(), (size_t)1); + CHECK_EQ(r.grammar_triggers[0].value, std::string("<|tool_call>")); + CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), Q) != r.preserved_tokens.end()); + CHECK(!r.think_starts_open); + REQUIRE(r.parser != nullptr); + + /* The decoder renders every control token the markers are made of, the string's among them; + * the turn's terminators it does not. */ + Detokenizer d(v, {}, false, r.preserved_tokens); + std::string text; + for (int32_t id : { 9, 13, 3, 10, 4, 14, 3, 8, 3, 8, 5 }) text += d.push(id); + text += d.flush(); + CHECK_EQ(text, std::string("<|channel>thoughta<|tool_call>call:a<|\"|>a<|\"|>")); + + std::unique_ptr rd = r.parser->open(); + std::vector deltas; + const std::string reply = "On it." + G("bash", "command:" + S("ls")); + for (char c : reply) rd->feed(std::string(1, c), &deltas); + rd->finish(&deltas); + const server::ParsedMessage pm = rd->message(); + CHECK_EQ(pm.content, std::string("On it.")); + REQUIRE_EQ(pm.tool_calls.size(), (size_t)1); + CHECK_EQ(pm.tool_calls[0].name, std::string("bash")); + CHECK_EQ(pm.tool_calls[0].arguments, std::string("{\"command\":\"ls\"}")); + CHECK(!pm.open_call); + std::string args; + int begins = 0, ends = 0; + for (const server::ReplyDelta& dl : deltas) { + if (dl.kind == server::ReplyDelta::CallBegin) ++begins; + if (dl.kind == server::ReplyDelta::CallArgs) args += dl.text; + if (dl.kind == server::ReplyDelta::CallEnd) ++ends; + } + CHECK_EQ(begins, 1); + CHECK_EQ(ends, 1); + CHECK_EQ(args, pm.tool_calls[0].arguments); + + /* A tool whose name the object's opening would end is refused at admission, by name. */ + const json bad = json::parse(R"([{"type":"function","function":{"name":"a{b"}}])"); + server::ChatRender rb; + CHECK(br.apply(msgs, bad, opt, &rb, &why) < 0); + CHECK(why.find("a{b") != std::string::npos); +} + +RAD_TEST_MAIN() diff --git a/tests/data/chat/gemma4/chat_template.jinja b/tests/data/chat/gemma4/chat_template.jinja new file mode 100644 index 00000000..4741bf6e --- /dev/null +++ b/tests/data/chat/gemma4/chat_template.jinja @@ -0,0 +1,390 @@ +{# + Template: Google Gemma 4 Canonical Chat Template + Author: Google Gemma Engineering Team + Published: 2026-07-09 + Context: Fixed tool-calling loops, turn closures, and thinking content-ordering. +#} +{%- macro format_parameters(properties, required, filter_keys=false) -%} + {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%} + {%- set ns = namespace(found_first=false) -%} + {%- for key, value in properties | dictsort -%} + {%- set add_comma = false -%} + {%- if not filter_keys or key not in standard_keys -%} + {%- if ns.found_first %},{% endif -%} + {%- set ns.found_first = true -%} + {{ key }}:{ + {%- if value['description'] -%} + description:<|"|>{{ value['description'] }}<|"|> + {%- set add_comma = true -%} + {%- endif -%} + {%- if value['type'] | upper == 'STRING' -%} + {%- if value['enum'] -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + enum:{{ format_argument(value['enum']) }} + {%- endif -%} + {%- elif value['type'] | upper == 'ARRAY' -%} + {%- if value['items'] is mapping and value['items'] -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + items:{ + {%- set ns_items = namespace(found_first=false) -%} + {%- for item_key, item_value in value['items'] | dictsort -%} + {%- if item_value is not none -%} + {%- if ns_items.found_first %},{% endif -%} + {%- set ns_items.found_first = true -%} + {%- if item_key == 'properties' -%} + properties:{ + {%- if item_value is mapping -%} + {{- format_parameters(item_value, value['items']['required'] | default([])) -}} + {%- endif -%} + } + {%- elif item_key == 'required' -%} + required:[ + {%- for req_item in item_value -%} + <|"|>{{- req_item -}}<|"|> + {%- if not loop.last %},{% endif -%} + {%- endfor -%} + ] + {%- elif item_key == 'type' -%} + {%- if item_value is string -%} + type:{{ format_argument(item_value | upper) }} + {%- else -%} + type:{{ format_argument(item_value | map('upper') | list) }} + {%- endif -%} + {%- else -%} + {{ item_key }}:{{ format_argument(item_value) }} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + } + {%- endif -%} + {%- endif -%} + {%- if value['nullable'] %} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + nullable:true + {%- endif -%} + {%- if value['type'] | upper == 'OBJECT' -%} + {%- if value['properties'] is defined and value['properties'] is mapping -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + properties:{ + {{- format_parameters(value['properties'], value['required'] | default([])) -}} + } + {%- elif value is mapping -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + properties:{ + {{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}} + } + {%- endif -%} + {%- if value['required'] -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + required:[ + {%- for item in value['required'] | default([]) -%} + <|"|>{{- item -}}<|"|> + {%- if not loop.last %},{% endif -%} + {%- endfor -%} + ] + {%- endif -%} + {%- endif -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + type:<|"|>{{ value['type'] | upper }}<|"|>} + {%- endif -%} + {%- endfor -%} +{%- endmacro -%} +{%- macro format_function_declaration(tool_data) -%} + declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|> + {%- set params = tool_data['function']['parameters'] -%} + {%- if params -%} + ,parameters:{ + {%- if params['properties'] -%} + properties:{ {{- format_parameters(params['properties'], params['required']) -}} }, + {%- endif -%} + {%- if params['required'] -%} + required:[ + {%- for item in params['required'] -%} + <|"|>{{- item -}}<|"|> + {{- ',' if not loop.last -}} + {%- endfor -%} + ], + {%- endif -%} + {%- if params['type'] -%} + type:<|"|>{{- params['type'] | upper -}}<|"|>} + {%- endif -%} + {%- endif -%} + {%- if 'response' in tool_data['function'] -%} + {%- set response_declaration = tool_data['function']['response'] -%} + ,response:{ + {%- if response_declaration['description'] -%} + description:<|"|>{{- response_declaration['description'] -}}<|"|>, + {%- endif -%} + {%- if response_declaration['type'] | upper == 'OBJECT' -%} + type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>} + {%- endif -%} + {%- endif -%} + } +{%- endmacro -%} +{%- macro format_argument(argument, escape_keys=True) -%} + {%- if argument is none -%} + {{- 'null' -}} + {%- elif argument is string -%} + {{- '<|"|>' + argument + '<|"|>' -}} + {%- elif argument is boolean -%} + {{- 'true' if argument else 'false' -}} + {%- elif argument is mapping -%} + {{- '{' -}} + {%- set ns = namespace(found_first=false) -%} + {%- for key, value in argument | dictsort -%} + {%- if ns.found_first %},{% endif -%} + {%- set ns.found_first = true -%} + {%- if escape_keys -%} + {{- '<|"|>' + key + '<|"|>' -}} + {%- else -%} + {{- key -}} + {%- endif -%} + :{{- format_argument(value, escape_keys=escape_keys) -}} + {%- endfor -%} + {{- '}' -}} + {%- elif argument is sequence -%} + {{- '[' -}} + {%- for item in argument -%} + {{- format_argument(item, escape_keys=escape_keys) -}} + {%- if not loop.last %},{% endif -%} + {%- endfor -%} + {{- ']' -}} + {%- else -%} + {{- argument -}} + {%- endif -%} +{%- endmacro -%} +{%- macro strip_thinking(text) -%} + {%- set ns = namespace(result='') -%} + {%- for part in text.split('') -%} + {%- if '<|channel>' in part -%} + {%- set ns.result = ns.result + part.split('<|channel>')[0] -%} + {%- else -%} + {%- set ns.result = ns.result + part -%} + {%- endif -%} + {%- endfor -%} + {{- ns.result | trim -}} +{%- endmacro -%} + +{%- macro format_tool_response_block(tool_name, response) -%} + {{- '<|tool_response>' -}} + {%- if response is mapping -%} + {{- 'response:' + tool_name + '{' -}} + {%- for key, value in response | dictsort -%} + {{- key -}}:{{- format_argument(value, escape_keys=False) -}} + {%- if not loop.last %},{% endif -%} + {%- endfor -%} + {{- '}' -}} + {%- else -%} + {{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}} + {%- endif -%} + {{- '' -}} +{%- endmacro -%} + +{#- ===== SETUP ===== -#} +{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%} +{%- set loop_messages = messages -%} +{%- set enable_thinking = enable_thinking | default(false) -%} +{%- set preserve_thinking = preserve_thinking | default(false) -%} +{{- bos_token -}} +{#- Handle System/Tool Definitions Block -#} +{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%} + {{- '<|turn>system\n' -}} + {#- Inject Thinking token at the very top of the FIRST system turn -#} + {%- if enable_thinking -%} + {{- '<|think|>\n' -}} + {%- set ns.prev_message_type = 'think' -%} + {%- endif -%} + {%- if messages and messages[0]['role'] in ['system', 'developer'] -%} + {%- if messages[0]['content'] is string -%} + {{- messages[0]['content'] | trim -}} + {%- elif messages[0]['content'] is sequence -%} + {%- for item in messages[0]['content'] -%} + {{- item['text'] | trim + ' '-}} + {%- endfor -%} + {%- endif -%} + {%- set loop_messages = messages[1:] -%} + {%- endif -%} + {%- if tools -%} + {%- for tool in tools %} + {{- '<|tool>' -}} + {{- format_function_declaration(tool) | trim -}} + {{- '' -}} + {%- endfor %} + {%- set ns.prev_message_type = 'tool' -%} + {%- endif -%} + {{- '\n' -}} +{%- endif %} + +{#- Pre-scan: find last user message index for reasoning guard -#} +{%- set ns_turn = namespace(last_user_idx=-1) -%} +{%- for i in range(loop_messages | length) -%} + {%- if loop_messages[i]['role'] == 'user' -%} + {%- set ns_turn.last_user_idx = i -%} + {%- endif -%} +{%- endfor -%} + +{#- Loop through messages -#} +{%- for message in loop_messages -%} + {%- if message['role'] != 'tool' -%} + {%- set ns.prev_message_type = None -%} + {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%} + {#- Detect continuation using tracked state β€” O(1) instead of O(n) backward scan -#} + {%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%} + {%- if not continue_same_model_turn -%} + {{- '<|turn>' + role + '\n' }} + + {%- endif -%} + + {#- Render reasoning/reasoning_content as thinking channel -#} + {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%} + {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%} + {%- if thinking_text and thinking_gate -%} + {{- '<|channel>thought\n' + thinking_text + '\n' -}} + {%- endif -%} + + {%- if message.get('tool_calls') -%} + {%- for tool_call in message.get('tool_calls') -%} + {%- set function = tool_call['function'] -%} + {{- '<|tool_call>call:' + function['name'] + '{' -}} + {%- if function['arguments'] is mapping -%} + {%- set ns_args = namespace(found_first=false) -%} + {%- for key, value in function['arguments'] | dictsort -%} + {%- if ns_args.found_first %},{% endif -%} + {%- set ns_args.found_first = true -%} + {{- key -}}:{{- format_argument(value, escape_keys=False) -}} + {%- endfor -%} + {%- elif function['arguments'] is none -%} + {%- else -%} + {{- raise_exception( + "chat_template: tool_calls[].function.arguments must be a " + "JSON object (mapping), not a string. Deserialize arguments " + "before passing to the template." + ) -}} + {%- endif -%} + {{- '}' -}} + {%- endfor -%} + {%- set ns.prev_message_type = 'tool_call' -%} + {%- endif -%} + + {%- set ns_tr_out = namespace(flag=false) -%} + {%- if message.get('tool_responses') -%} + {#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#} + {%- for tool_response in message.get('tool_responses') -%} + {{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}} + {%- set ns_tr_out.flag = true -%} + {%- set ns.prev_message_type = 'tool_response' -%} + {%- endfor -%} + {%- elif message.get('tool_calls') -%} + {#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#} + {%- set ns_tool_scan = namespace(stopped=false) -%} + {%- for k in range(loop.index0 + 1, loop_messages | length) -%} + {%- if ns_tool_scan.stopped -%} + {%- elif loop_messages[k]['role'] != 'tool' -%} + {%- set ns_tool_scan.stopped = true -%} + {%- else -%} + {%- set follow = loop_messages[k] -%} + {#- Resolve tool_call_id to function name -#} + {%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%} + {%- for tc in message.get('tool_calls') -%} + {%- if tc.get('id') == follow.get('tool_call_id') -%} + {%- set ns_tname.name = tc['function']['name'] -%} + {%- endif -%} + {%- endfor -%} + {#- Handle content as string or content-parts array -#} + {%- set tool_body = follow.get('content') -%} + {%- if tool_body is string -%} + {{- format_tool_response_block(ns_tname.name, tool_body) -}} + {%- elif tool_body is sequence and tool_body is not string -%} + {%- set ns_txt = namespace(s='') -%} + {%- for part in tool_body -%} + {%- if part.get('type') == 'text' -%} + {%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%} + {%- endif -%} + {%- endfor -%} + {{- format_tool_response_block(ns_tname.name, ns_txt.s) -}} + {%- for part in tool_body -%} + {%- if part.get('type') in ['image', 'image_url'] -%} + {{- '<|image|>' -}} + {%- elif part.get('type') in ['audio', 'input_audio'] -%} + {{- '<|audio|>' -}} + {%- elif part.get('type') == 'video' -%} + {{- '<|video|>' -}} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{- format_tool_response_block(ns_tname.name, tool_body) -}} + {%- endif -%} + {%- set ns_tr_out.flag = true -%} + {%- set ns.prev_message_type = 'tool_response' -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + + {%- set captured_content -%} + {%- if message.get('content') is string -%} + {%- if role == 'model' -%} + {{- strip_thinking(message['content']) -}} + {%- else -%} + {{- message['content'] | trim -}} + {%- endif -%} + {%- elif message.get('content') is sequence -%} + {%- for item in message['content'] -%} + {%- if item.get('type') == 'text' -%} + {%- if role == 'model' -%} + {{- strip_thinking(item['text']) -}} + {%- else -%} + {{- item['text'] | trim -}} + {%- endif -%} + {%- elif item.get('type') in ['image', 'image_url'] -%} + {{- '<|image|>' -}} + {%- elif item.get('type') in ['audio', 'input_audio'] -%} + {{- '<|audio|>' -}} + {%- elif item.get('type') == 'video' -%} + {{- '<|video|>' -}} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- endset -%} + + {{- captured_content -}} + {%- set has_content = captured_content | trim | length > 0 -%} + + {#- Forward-scan: find next non-tool message role for continuation detection -#} + {%- set next_nt = namespace(role=None, found=false) -%} + {%- for j in range(loop.index0 + 1, loop_messages | length) -%} + {%- if not next_nt.found -%} + {%- if loop_messages[j]['role'] != 'tool' -%} + {%- set next_nt.role = loop_messages[j]['role'] -%} + {%- set next_nt.found = true -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + + {%- set continues_into_next = ( + role == 'model' + and next_nt.role == 'assistant' + and (not message.get('tool_calls') or ns_tr_out.flag) + ) -%} + + {%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%} + {{- '<|tool_response>' -}} + {%- elif continues_into_next -%} + {%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%} + {{- '\n' -}} + {%- endif -%} + + {#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#} + {%- set ns.prev_non_tool_role = message['role'] -%} + {%- endif -%} +{%- endfor -%} + +{%- if add_generation_prompt -%} + {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%} + {{- '<|turn>model\n' -}} + {%- if not enable_thinking -%} + {{- '<|channel>thought\n' -}} + {%- endif -%} + {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%} + {{- '<|channel>thought\n' -}} + {%- endif -%} +{%- endif -%} diff --git a/tests/legacy/chatdiff.cpp b/tests/legacy/chatdiff.cpp index c86fda88..6b820bc2 100644 --- a/tests/legacy/chatdiff.cpp +++ b/tests/legacy/chatdiff.cpp @@ -65,6 +65,11 @@ int Bench::load(const Model& m, const std::string& jinja, std::string* why) { *why = "the template did not compile"; return RAD_E_FORMAT; } + if (m.declared) { + const int st = chat_format_from_abi(m.declared, &fmt_, why); + if (st < 0) return st; + return ReplyFormat::compile(fmt_, &rf_, why); + } std::string refused; int st = chat_format_from_template(jinja, m.bos, m.eos, &fmt_, &refused, why); if (st < 0) return st; diff --git a/tests/legacy/chatdiff.h b/tests/legacy/chatdiff.h index 8a146d91..39654d4a 100644 --- a/tests/legacy/chatdiff.h +++ b/tests/legacy/chatdiff.h @@ -13,6 +13,8 @@ #include "text/chatparse.h" #include "toolparse_legacy.h" +struct RadChatFormat; + #include #include @@ -31,6 +33,9 @@ struct Model { std::string dir; /* under the fixture root */ std::string bos, eos; std::vector terminators; /* its end-of-generation spellings */ + /* The architecture plugin's reply format, when it declares one; null derives the format from + * the template, as the engine does. */ + const RadChatFormat* declared = nullptr; }; const std::vector& models();