Commit dd53f70d0 for llama.cpp

commit dd53f70d089f8b57db9d9e4f44f3201a16668637
Author: Aldehir Rojas <hello@alde.dev>
Date:   Mon Nov 23 01:54:42 2026 -0600

    chat : improve inkling parser/grammar (#32833)

diff --git a/common/parsers/inkling.cpp b/common/parsers/inkling.cpp
index 9c30cdb87..082bd86fd 100644
--- a/common/parsers/inkling.cpp
+++ b/common/parsers/inkling.cpp
@@ -100,18 +100,18 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
     auto use_tools           = has_tools && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_NONE;
     auto extract_reasoning   = inputs.reasoning_format != COMMON_REASONING_FORMAT_NONE;

-    data.parser = build_chat_peg_parser([&](common_chat_peg_builder & p) {
-        auto header = p.literal(HEADER);
-        auto end    = p.literal(END);
+    data.parser = build_chat_peg_parser(inputs.specials, [&](common_chat_peg_builder & p) {
+        auto header = p.token(HEADER);
+        auto end    = p.token(END);

-        auto think    = p.literal(THINK);
-        auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(END)) + end :
-                                                               p.atomic(p.content(think)) + p.content(p.until(END) + end));
-        auto text     = p.rule("text", p.literal(TEXT) + p.content(p.until(END)) + end);
+        auto think    = p.token(THINK);
+        auto thinking = p.rule("thinking", extract_reasoning ? think + p.reasoning(p.until(end)) + end :
+                                                               p.atomic(p.content(think)) + p.content(p.until(end) + end));
+        auto text     = p.rule("text", p.token(TEXT) + p.content(p.until(end)) + end);

         if (has_response_format) {
             auto response_format = p.rule("response-format", p.content(p.schema(p.json(), "response-format-schema", inputs.json_schema)));
-            return p.zero_or_more(header + thinking) + header + p.literal(TEXT) + response_format + end;
+            return p.zero_or_more(header + thinking) + header + p.token(TEXT) + response_format + end;
         }

         auto blocks = p.zero_or_more(header + (thinking | text));
@@ -120,45 +120,43 @@ common_chat_params common_chat_params_init_inkling(const common_chat_template &
             return blocks;
         }

-        auto tool_choice = p.choice();
-        foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
-            const auto & function = tool.at("function");
-            std::string  name     = function.at("name");
-
-            auto open = p.tool_name(p.literal(name)) + p.literal(TOOL_JSON) + p.literal("{\"name\":" + json(name).dump() + ",\"args\":");
-            auto args = p.tool_args(p.json());
-
-            tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.tool_open(open) + args + p.tool_close(p.literal("}")) + end));
-        });
-
-        // tool calls are the last blocks of the turn
-        auto calls      = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
-        auto tool_calls = header + p.trigger_rule("tool-calls", calls);
+        // the call takes the name in the JSON
+        auto tool_json = p.token(TOOL_JSON);
+        auto tool_body = [&](const common_peg_parser & json_name) {
+            return p.tool_open(p.literal("{")) << p.json_member("name", p.literal("\"") + p.tool_name(json_name) + p.literal("\"")) << p.literal(",")
+                                               << p.json_member("args", p.tool_args(p.json())) << p.tool_close(p.literal("}")) + end;
+        };

         if (inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_REQUIRED) {
-            return blocks + tool_calls;
+            auto tool_choice = p.choice();
+            foreach_function(inputs.tools, [&](size_t tool_index, const json & tool) {
+                const auto & function = tool.at("function");
+                std::string  name     = function.at("name");
+                std::string  quoted   = json(name).dump();
+
+                // The research model does not generate a tool name before the tool call token
+                auto json_name = p.literal(quoted.substr(1, quoted.size() - 2));
+                tool_choice |= p.rule("tool-" + std::to_string(tool_index), p.tool(p.optional(p.literal(name)) + tool_json + tool_body(json_name)));
+            });
+
+            auto calls = inputs.parallel_tool_calls ? tool_choice + p.zero_or_more(header + tool_choice) : tool_choice;
+            return blocks + header + calls;
         }

-        return blocks + p.optional(tool_calls);
+        auto name  = p.until(tool_json);
+        auto body  = tool_body(p.string_content('"'));
+        auto next  = p.rule("tool-call", header + p.tool(name + tool_json + body));
+        auto more  = inputs.parallel_tool_calls ? p.zero_or_more(next) : p.eps();
+        auto calls = header + name + p.trigger_rule("tool-calls", tool_json, body + more);
+
+        return blocks + p.optional(calls);
     });

     if (has_response_format || use_tools) {
-        data.grammar_lazy = !has_response_format && inputs.tool_choice != COMMON_CHAT_TOOL_CHOICE_REQUIRED;
+        data.grammar_lazy = false;
         data.grammar      = build_grammar([&](const common_grammar_builder & builder) {
-            data.parser.build_grammar(builder, data.grammar_lazy);
+            data.parser.build_grammar(builder, !has_response_format && inputs.tool_choice == COMMON_CHAT_TOOL_CHOICE_AUTO);
         });
-
-        if (data.grammar_lazy) {
-            // a header followed by text and not by a content token is a tool call, the grammar starts at the name
-            data.grammar_triggers = {
-                { COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN, "<\\|message_model\\|>([^<])" },
-            };
-            // Inkling 1: the first header is in the generation prompt, and a lazy grammar does not get the prompt.
-            // an output that starts with no content token is a tool call. not for a continuation, it starts with text
-            if (!inputs.has_continuation()) {
-                data.grammar_triggers.push_back({ COMMON_GRAMMAR_TRIGGER_TYPE_PATTERN_FULL, "[^<]+" });
-            }
-        }
     }

     return data;
diff --git a/tests/test-chat.cpp b/tests/test-chat.cpp
index 341e7aceb..20a3cc6a0 100644
--- a/tests/test-chat.cpp
+++ b/tests/test-chat.cpp
@@ -5653,6 +5653,7 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
     for (const int version : { 1, 2 }) {
         auto tst = peg_tester(version == 1 ? "models/templates/thinkingmachines-Inkling.jinja" :
                                              "models/templates/thinkingmachines-Inkling-2-Small.jinja", detailed_debug);
+        tst.specials({ "<|message_model|>", "<|content_thinking|>", "<|content_text|>", "<|content_invoke_tool_json|>", "<|end_message|>" });

         // Inkling 1 has the first header in the generation prompt, Inkling 2 writes it
         const std::string H = "<|message_model|>";
@@ -5693,7 +5694,8 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
             .expect_tool_calls({
                 { "special_function", R"({"arg1":1})", "" },
             })
-            .expect_rules({ "tool-0" })
+            .expect_rules({ "tool-calls" })
+            .expect_grammar()
             .run();

         // Thinking, content, then a tool call
@@ -5721,20 +5723,41 @@ static void test_template_output_peg_parsers(bool detailed_debug) {
             })
             .run();

-        // The block closer inside a string argument does not end the block
-        tst.test(P + "python<|content_invoke_tool_json|>{\"name\":\"python\",\"args\":{\"code\":\"print('<|end_message|>')\"}}" + E)
-            .tools({ python_tool })
-            .expect_tool_calls({
-                { "python", R"JSON({"code":"print('<|end_message|>')"})JSON", "" },
-            })
-            .run();
-
         // Forced tool call
         tst.test(P + "<|content_thinking|>I should call it" + E + H + CALL)
             .reasoning_format(COMMON_REASONING_FORMAT_AUTO)
             .tool_choice(COMMON_CHAT_TOOL_CHOICE_REQUIRED)
             .tools({ special_function_tool })
             .expect(simple_assist_msg("", "I should call it", "special_function", R"({"arg1":1})", ""))
+            .expect_rules({ "tool-0" })
+            .expect_grammar()
+            .run();
+
+        // The research model does not write the name before the tool token
+        for (const auto tool_choice : { COMMON_CHAT_TOOL_CHOICE_AUTO, COMMON_CHAT_TOOL_CHOICE_REQUIRED }) {
+            tst.test(P + "<|content_invoke_tool_json|>{\"name\":\"special_function\",\"args\":{\"arg1\":1}}" + E)
+                .tool_choice(tool_choice)
+                .tools({ special_function_tool })
+                .expect_tool_calls({
+                    { "special_function", R"({"arg1":1})", "" },
+                })
+                .run();
+        }
+
+        // A tool that is not in the list, with spaces in the JSON
+        tst.test(P + "unknown_tool<|content_invoke_tool_json|>{\"name\": \"unknown_tool\", \"args\": {\"arg1\": 1}}" + E)
+            .tools({ special_function_tool })
+            .expect_tool_calls({
+                { "unknown_tool", R"({"arg1": 1})", "" },
+            })
+            .run();
+
+        // The call takes the name in the JSON, not the one before the tool token
+        tst.test(P + "special<|content_invoke_tool_json|>{\"name\":\"special_function\",\"args\":{\"arg1\":1}}" + E)
+            .tools({ special_function_tool })
+            .expect_tool_calls({
+                { "special_function", R"({"arg1":1})", "" },
+            })
             .run();

         // Response format