From dbd4e164b3b78404253f1a4ac329303b92f47548 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Sat, 10 Oct 2026 12:41:05 +0000 Subject: [PATCH] chat: a call written as its name and one object; reasoning that opens again later The reply format described one call syntax, the tagged one: each argument in its own tags, typed by the tool's schema. A call written as its name followed by ONE object holding the arguments could not be described -- Gemma 4's `<|tool_call>call:NAME{key:<|"|>text<|"|>}` is one, and its tool requests were refused; JSON behind a name tag (`[TOOL_CALLS]NAME[ARGS]{...}`) or inside a function tag is the same shape. RadChatFormat grows at its end (no ABI bump; an older plugin reads the new fields as zero): - args_form RAD_CHAT_ARGS_OBJECT: the arguments are one object after the name. name_suffix may be empty, and the name then ends at the object's `{`; call_end may be empty, and the object's own `}` ends the call. The arg_* fields are unused and must be empty. - object_string_open / object_string_close: a string delimiter of the object's dialect besides JSON's `"`, between which the text is verbatim (Gemma 4: <|"|> twice). - object_bare_keys: the dialect writes keys bare, `key:value`. - reasoning_anywhere: a reasoning block may open again later in the reply (after the answer, between calls) and is read as reasoning there too; a close with no block open is dropped. The streaming parser reads the object as it arrives and writes it as JSON as it reads: brackets and separators as they come, a key once its `:` shows it is one, a string's bytes as they arrive (the dialect's verbatim, JSON's with its escapes checked: an unknown escape is text, a lone surrogate is U+FFFD), and a bare value as the tagged family writes a typed one -- held while it could be a number or literal, else a string. Trailing and missing separators, a bracket of the wrong kind, a key without value and an object cut off by the call's close are repaired locally and reported as leaving the grammar; a closed call's arguments are JSON whatever was written. The streaming contract holds: deltas are never revised, holds stay bounded. The lazy grammar writes the object in its dialect (strings between the delimiters, bare keys, JSON numbers and literals) and leaves the values to the model, as llama.cpp's own Gemma 4 grammar does: the schema converter speaks JSON, and the dialect is not JSON. chat_format_check refuses what the parser could not read unambiguously, by name: tagged fields in an object format, a dialect string opener that begins like a bare word, a call close that holds object punctuation or cannot be told apart from the string opener, a reasoning marker that overlaps a call opener in content. chatparse_test: JSON behind a name tag and behind a function tag (strict, lenient, streamed every way, grammar admits and refuses), reasoning_anywhere on and off, and the refusals. --- abi/rad_builder.h | 34 +++ core/text/chatfmt.cpp | 229 +++++++++++++--- core/text/chatfmt.h | 44 ++- core/text/chatparse.cpp | 566 +++++++++++++++++++++++++++++++++++++-- spec.md | 6 + tests/chatparse_test.cpp | 181 +++++++++++++ 6 files changed, 1007 insertions(+), 53 deletions(-) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index a0540103..89f5275d 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -679,6 +679,18 @@ int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); * UTF-8; NULL reads as "". The engine copies what it needs while loading, so static storage in * the plugin is enough. * + * The other family is a call written as a name and ONE object holding its arguments + * (args_form = RAD_CHAT_ARGS_OBJECT): + * + * [call_open] name_prefix NAME name_suffix { key: value, ... } [call_end] [call_close] + * + * The object is JSON, or a dialect of it: strings between object_string_open and + * object_string_close, their text verbatim, and keys written bare (object_bare_keys). Gemma 4 is + * "<|tool_call>" / "", "call:" / "" / "", strings "<|\"|>" / "<|\"|>", bare keys -- + * `<|tool_call>call:get_weather{city:<|"|>Paris<|"|>}` -- and the reply's JSON + * arguments are that object respelled as JSON. The arg_* fields describe tagged arguments only + * and are empty in this family. + * * THE STRUCT GROWS AT ITS END AND NEVER CHANGES IN THE MIDDLE. `struct_size` is * sizeof(RadChatFormat) as the plugin was compiled; the engine reads only the fields that size * covers and treats the rest as zero, so a plugin built against an older header keeps loading @@ -700,6 +712,11 @@ enum { RAD_CHAT_THINK_NEVER = 2 /* the model opens its own block, if any */ }; +enum { + RAD_CHAT_ARGS_TAGGED = 0, /* each argument in its own tags: arg_prefix .. arg_value_suffix */ + RAD_CHAT_ARGS_OBJECT = 1 /* one object after the name, in JSON or the object_* dialect */ +}; + typedef struct RadChatFormat { uint32_t struct_size; const char* name; /* for the startup log; NULL is the plugin's name */ @@ -739,6 +756,23 @@ typedef struct RadChatFormat { * reply is read unconstrained. */ const char* const* triggers; uint32_t n_triggers; + + /* RAD_CHAT_ARGS_*: how a call's arguments are written. Zero is the tagged family above. With + * RAD_CHAT_ARGS_OBJECT, name_suffix may be empty -- the name then ends where the object + * begins -- and so may call_end, when the object's own closing brace ends the call. */ + uint32_t args_form; + /* RAD_CHAT_ARGS_OBJECT: a string delimiter of the object's dialect besides JSON's `"`. What + * stands between the two is the string, verbatim -- the dialect has no escapes. NULL: the + * object writes JSON strings only. */ + const char* object_string_open; + const char* object_string_close; + /* RAD_CHAT_ARGS_OBJECT: non-zero when the dialect writes a key bare, `key:value`. */ + uint32_t object_bare_keys; + + /* Non-zero: a reasoning block may open again LATER in the reply -- after its answer, between + * calls -- and is read as reasoning there as well, and a reasoning_close with no block open + * is not part of the answer. Zero: only a block the reply starts with is reasoning. */ + uint32_t reasoning_anywhere; } RadChatFormat; /* Return the format, or NULL for "derive it from the chat template". Called once at startup. */ diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index 528c59c4..c6297dcb 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -45,6 +46,75 @@ bool starts_with(const std::string& s, const std::string& p) { std::string show(const std::string& s) { return nlohmann::json(s).dump(); } +int refuse(std::string* why, const std::string& s) { + if (why) *why = s; + return RAD_E_UNSUPPORTED; +} + +/* A byte that begins a bare word or a JSON value, or is the object's own punctuation. */ +bool object_byte(unsigned char c) { + return c == 0 || std::isalnum(c) || is_ws(c) || std::strchr("-+._'\"{}[],:", (int)c) != nullptr; +} + +/* An argument object, as the streaming parser reads it (chatparse.cpp). Where a key or a value + * may begin, it tells three literals apart by their first bytes: a dialect string's opener, and + * the call's close and end, which a reply that leaves its object unclosed writes there. None may + * begin another. A bare word ends at the object's punctuation or at the call's close; one + * automaton finds both in the order they start only when the close holds none of it. */ +int object_check(const ChatFormat& f, std::string* why) { + const std::string& so = f.object_string_open; + const std::string& sc = f.object_string_close; + if (so.empty() != sc.empty()) + return refuse(why, "object_string_open and object_string_close are set together or not " + "at all"); + if (!so.empty()) { + if (trim_ws(so) != so || trim_ws(sc) != sc) + return refuse(why, "an object string delimiter may not begin or end with " + "whitespace"); + if (object_byte((unsigned char)so[0])) + return refuse(why, "object_string_open " + show(so) + " begins with a byte that also " + "begins a bare word, a JSON value or the object's punctuation"); + } + std::vector lits; + if (!so.empty()) lits.push_back(so); + const std::string cc = trim_ws(f.call_close), ce = trim_ws(f.call_end); + for (const std::string* s : { &cc, &ce }) { + if (s->empty()) continue; + for (char c : *s) + if (std::strchr(",:{}[]\"", c)) + return refuse(why, "the call's close " + show(*s) + " holds " + + show(std::string(1, c)) + ", which is the argument object's " + "punctuation"); + if (std::find(lits.begin(), lits.end(), *s) == lits.end()) lits.push_back(*s); + else if (!so.empty() && *s == so) + return refuse(why, show(*s) + " both opens an object string and closes the call"); + } + for (size_t i = 0; i < lits.size(); ++i) + for (size_t j = 0; j < lits.size(); ++j) + if (i != j && (starts_with(lits[i], lits[j]) || occurs_inside(lits[j], lits[i]))) + return refuse(why, show(lits[j]) + " and " + show(lits[i]) + " cannot be told " + "apart inside an argument object"); + return RAD_OK; +} + +/* Content is scanned for a later reasoning block's opener and for a stray close beside the call + * openers, in one automaton, which reports them in the order they start only when none occurs + * inside another or begins it. */ +int reasoning_anywhere_check(const ChatFormat& f, std::string* why) { + if (!f.reasoning_anywhere) return RAD_OK; + std::vector d = { trim_ws(f.reasoning_open), trim_ws(f.reasoning_close) }; + if (f.has_tools()) { + if (!f.call_open.empty()) d.push_back(trim_ws(f.call_open)); + d.push_back(f.name_prefix); + } + for (size_t i = 0; i < d.size(); ++i) + for (size_t j = 0; j < d.size(); ++j) + if (i != j && (starts_with(d[i], d[j]) || occurs_inside(d[j], d[i]))) + return refuse(why, show(d[j]) + " and " + show(d[i]) + " cannot be told apart in " + "content, which a reasoning block may open anywhere in"); + return RAD_OK; +} + } /* namespace */ /* ================================================================== validity */ @@ -61,16 +131,24 @@ int chat_format_check(const ChatFormat& f, std::string* why) { return no("reasoning_close is only whitespace"); if ((uint32_t)f.reasoning_in_prompt > (uint32_t)ChatThink::Never) return no("reasoning_in_prompt is not a RAD_CHAT_THINK_* value"); + if ((uint32_t)f.args_form > (uint32_t)ChatArgs::Object) + return no("args_form is not a RAD_CHAT_ARGS_* value"); + /* A block that opens later in the reply is found by its opener, in content. */ + if (f.reasoning_anywhere && (!f.has_reasoning() || trim_ws(f.reasoning_open).empty())) + return no("reasoning_anywhere needs a reasoning block with an opener"); if (!f.has_tools()) { for (const std::string* s : { &f.section_open, &f.section_close, &f.call_separator, &f.call_open, &f.call_close, &f.name_suffix, &f.call_end, &f.arg_prefix, &f.arg_name_suffix, &f.arg_value_prefix, - &f.arg_value_suffix }) + &f.arg_value_suffix, &f.object_string_open, + &f.object_string_close }) if (!s->empty()) return no("tool-call delimiters are set but name_prefix is empty"); + if (f.object_args() || f.object_bare_keys) + return no("an argument object is described but name_prefix is empty"); if (!f.reasoning_breaks.empty()) return no("reasoning_breaks without tool calls"); if (!f.triggers.empty()) return no("grammar triggers without tool calls"); - return RAD_OK; + return reasoning_anywhere_check(f, why); } if (!f.section_open.empty() || !f.section_close.empty()) @@ -81,22 +159,43 @@ int chat_format_check(const ChatFormat& f, std::string* why) { ") is not read by the streaming parser; tagged calls separate on whitespace"); if (f.call_open.empty() && !f.call_close.empty()) return no("call_close without call_open"); - if (f.name_suffix.empty() || 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"); - if (f.call_end.empty()) return no("call_end is empty: a call must close with its own tag"); - if (f.arg_prefix.empty()) return no("arg_prefix is empty"); - if (f.arg_value_suffix.empty()) return no("arg_value_suffix is empty"); - 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.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) - return no("other_value is not a RAD_CHAT_VALUE_* value"); + 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()) + 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"); + } + if (!object) { + if (f.call_end.empty()) return no("call_end is empty: a call must close with its own tag"); + if (f.arg_prefix.empty()) return no("arg_prefix is empty"); + if (f.arg_value_suffix.empty()) return no("arg_value_suffix is empty"); + 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.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) + return no("other_value is not a RAD_CHAT_VALUE_* value"); + if (!f.object_string_open.empty() || !f.object_string_close.empty() || + f.object_bare_keys) + return no("the object_* fields describe an argument object, and args_form is " + "RAD_CHAT_ARGS_TAGGED"); + } else { + for (const std::string* s : { &f.arg_prefix, &f.arg_name_suffix, &f.arg_value_prefix, + &f.arg_value_suffix }) + if (!s->empty()) + return no("the arg_* fields describe tagged arguments, and args_form is " + "RAD_CHAT_ARGS_OBJECT"); + if (!f.call_end.empty() && trim_ws(f.call_end).empty()) + return no("call_end is only whitespace"); + const int st = object_check(f, why); + if (st < 0) return st; + } /* A wrapped format's content is scanned for the wrapper's core and for name_prefix alone, * which opens a call written without its wrapper; the two must not be confusable. */ @@ -127,16 +226,19 @@ int chat_format_check(const ChatFormat& f, std::string* why) { return no("reasoning break " + show(b) + " overlaps reasoning_close " + show(close)); } - /* Inside a call the next tag is an argument or the close, and the close is recognised by its - * core as well: the whitespace around it is optional when a reply leaves the format. */ - const std::string end = trim_ws(f.call_end); - if (end.empty()) return no("call_end is only whitespace"); - for (const std::string* e : { &f.call_end, &end }) - if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) || - occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix)) - return no("arg_prefix " + show(f.arg_prefix) + " and call_end " + show(f.call_end) + - " cannot be told apart"); - return RAD_OK; + if (!object) { + /* Inside a call the next tag is an argument or the close, and the close is recognised by + * its core as well: the whitespace around it is optional when a reply leaves the + * format. */ + const std::string end = trim_ws(f.call_end); + if (end.empty()) return no("call_end is only whitespace"); + for (const std::string* e : { &f.call_end, &end }) + if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) || + occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix)) + return no("arg_prefix " + show(f.arg_prefix) + " and call_end " + + show(f.call_end) + " cannot be told apart"); + } + return reasoning_anywhere_check(f, why); } /* ================================================================== the plugin's declaration */ @@ -183,6 +285,11 @@ int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* f.other_value = (ChatValue)c.other_value; f.value_newlines = c.value_newlines != 0; list(c.triggers, c.n_triggers, &f.triggers); + f.args_form = (ChatArgs)c.args_form; + f.object_string_open = s(c.object_string_open); + f.object_string_close = s(c.object_string_close); + f.object_bare_keys = c.object_bare_keys != 0; + f.reasoning_anywhere = c.reasoning_anywhere != 0; *out = std::move(f); return RAD_OK; } @@ -286,13 +393,23 @@ int chat_format_from_template(const std::string& jinja, const std::string& bos, std::string chat_format_describe(const ChatFormat& f) { std::string s = f.name + ":"; if (f.has_reasoning()) - s += " reasoning " + show(f.reasoning_open) + ".." + show(f.reasoning_close); + s += " reasoning " + show(f.reasoning_open) + ".." + show(f.reasoning_close) + + (f.reasoning_anywhere ? " anywhere" : ""); else s += " no reasoning"; - if (f.has_tools()) { + if (f.has_tools() && f.object_args()) { + s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) + + " {OBJECT"; + if (!f.object_string_open.empty()) + s += ", strings " + show(f.object_string_open) + ".." + show(f.object_string_close); + if (f.object_bare_keys) s += ", bare keys"; + s += "} " + show(f.call_end) + show(f.call_close); + } else if (f.has_tools()) { s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) + " " + show(f.arg_prefix) + "ARG" + show(f.arg_name_suffix) + show(f.arg_value_prefix) + "VALUE" + show(f.arg_value_suffix) + " " + show(f.call_end) + show(f.call_close); + } + if (f.has_tools()) { if (!f.triggers.empty()) { s += "; grammar on"; for (const std::string& t : f.triggers) s += " " + show(t); @@ -310,7 +427,8 @@ std::vector chat_format_markers(const ChatFormat& f) { for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.section_open, &f.section_close, &f.call_open, &f.call_close, &f.name_prefix, &f.name_suffix, &f.call_end, &f.arg_prefix, &f.arg_name_suffix, - &f.arg_value_prefix, &f.arg_value_suffix }) { + &f.arg_value_prefix, &f.arg_value_suffix, + &f.object_string_open, &f.object_string_close }) { const std::string t = trim_ws(*s); if (!t.empty() && std::find(out.begin(), out.end(), t) == out.end()) out.push_back(t); } @@ -538,6 +656,40 @@ void add_json_rules(const common_grammar_builder& b) { "json-null"); } +/* THE ARGUMENT OBJECT of the object family, in its dialect: JSON, or strings between the + * declared delimiters and keys written bare. As llama.cpp's own Gemma 4 grammar does, it fixes + * the syntax and leaves the values to the model: a tool's schema says what JSON a value must be, + * and the dialect is not JSON, so the schema converter has nothing to say about it. Whitespace + * goes where the dialect's writers put it -- after a separator and inside the brackets -- and + * nowhere else. */ +void add_object_rules(const common_grammar_builder& b, const ChatFormat& f) { + const std::string& so = f.object_string_open; + if (!so.empty()) + b.add_rule("obj-string", gbnf_format_literal(so) + " " + + until_pattern({ f.object_string_close }) + " " + + gbnf_format_literal(f.object_string_close)); + else + b.add_rule("obj-string", "\"\\\"\" ( [^\"\\\\] | \"\\\\\" ( [\"\\\\/ bfnrt] | \"u\" " + "[0-9a-fA-F]{4} ) )* \"\\\"\""); + b.add_rule("obj-number", "\"-\"? (\"0\" | [1-9] [0-9]*) (\".\" [0-9]+)? ([eE] [+-]? [0-9]+)?"); + b.add_rule("obj-value", "obj-object | obj-array | obj-string | obj-number | \"true\" | " + "\"false\" | \"null\""); + b.add_rule("obj-array", "\"[\" space (\"]\" | obj-value (\",\" space obj-value)* space " + "\"]\")"); + if (f.object_bare_keys) { + /* A bare key: no whitespace, no punctuation, and not the string opener's first byte. */ + std::string cls = "[^ \\t\\n\\r:,{}\\[\\]\""; + if (!so.empty()) cls += class_char((unsigned char)so[0]); + cls += "]+"; + b.add_rule("obj-key", cls + " | obj-string"); + } else { + b.add_rule("obj-key", "obj-string"); + } + b.add_rule("obj-member", "obj-key \":\" space obj-value"); + b.add_rule("obj-object", "\"{\" space (\"}\" | obj-member (\",\" space obj-member)* space " + "\"}\")"); +} + G optspace(const std::string& tag) { size_t a = 0, b = tag.size(); while (a < b && is_ws((unsigned char)tag[a])) ++a; @@ -644,6 +796,18 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat const auto& fn = tool.at("function"); const std::string name = fn.at("name"); if (!req.only_tool.empty() && name != req.only_tool) continue; + if (f.object_args()) { + /* The name, then the object; the object's own closing brace may be all + * that ends the call. */ + G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), lit(f.name_suffix) })); + G func = f.call_end.empty() + ? seq({ open, rule_ref("obj-object") }) + : seq({ open, rule_ref("obj-object"), space(), + wrap(lit(f.call_end)) }); + b.add_rule(rule_name("tool-" + name), render(func)); + choices.push_back(rule_ref(rule_name("tool-" + name))); + continue; + } auto params = fn.contains("parameters") ? fn.at("parameters") : ojson::object(); const auto properties = params.contains("properties") ? params.at("properties") : ojson::object(); @@ -704,7 +868,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat if (choices.empty() && !req.only_tool.empty()) throw std::invalid_argument("no tool named \"" + req.only_tool + "\" to call"); if (typed) add_json_rules(b); - if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix })); + if (!choices.empty() && f.object_args()) add_object_rules(b, f); + else if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix })); G choice = alt(choices); G calls; diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h index 9bfe7fa0..b81ab275 100644 --- a/core/text/chatfmt.h +++ b/core/text/chatfmt.h @@ -32,10 +32,21 @@ * the raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as * JSON is taken raw -- a model writing into an XML tag writes Python as often as JSON. * - * The analyser also recognises formats outside this family (a JSON object per call, JSON - * arguments inside a tag, call ids). For those chat_format_from_template keeps the reasoning split - * and names why tool calls are refused, and a model that needs one gets it by adding the shape to - * the parser, not by a fallback. */ + * THE OBJECT FAMILY writes a call as its name and one object holding the arguments + * (ChatArgs::Object): + * + * Gemma 4 <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3} + * + * The object is JSON or a dialect of it -- strings between two declared delimiters with their + * text verbatim, keys written bare -- and the arguments a client receives are that object in + * JSON. Here the values carry their own types, so no schema is consulted to read them; a bare + * word that is no JSON literal or number is read as a string, as a typed argument that is not + * JSON is in the tagged family. + * + * The analyser also recognises formats outside these families (a JSON object per call with its + * name inside it, call ids). For those chat_format_from_template keeps the reasoning split and + * names why tool calls are refused, and a model that needs one gets it by adding the shape to the + * parser, not by a fallback. */ #pragma once #include "rad_internal.h" @@ -68,6 +79,12 @@ enum class ChatThink : uint32_t { Never = 2, /* the model opens its own block, if any */ }; +/* How a call's arguments are written. The numbering is the ABI's (RAD_CHAT_ARGS_*). */ +enum class ChatArgs : uint32_t { + Tagged = 0, /* each argument in its own tags: arg_prefix NAME .. VALUE arg_value_suffix */ + Object = 1, /* one object after the name: `{` key `:` value, ... `}` */ +}; + struct ChatFormat { std::string name; /* for logs: "plugin:" or "template" */ @@ -83,6 +100,10 @@ struct ChatFormat { * Must name the call opener (`call_open`) when non-empty. */ std::vector reasoning_breaks; ChatThink reasoning_in_prompt = ChatThink::FromPrompt; + /* A block may also open later in the reply -- after the answer, between calls -- and is read + * as reasoning there; a close with no block open is dropped. Gemma 4 writes an empty block + * after its answer now and then, and a lone close. Needs `reasoning_open`. */ + bool reasoning_anywhere = false; /* ------------------------------------------------------------------ tool calls * `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the @@ -94,8 +115,18 @@ struct ChatFormat { /* Around EACH call: "\n", "". When set, a call written without it -- * name_prefix alone -- is still read as a call, leniently (chatparse.h). */ std::string call_open, call_close; - std::string name_prefix, name_suffix; /* "\n" */ - std::string call_end; /* "\n" */ + /* "\n". In the object family name_suffix may be empty: the name then ends + * where the object begins, at its `{`. */ + std::string name_prefix, name_suffix; + std::string call_end; /* "\n"; may be empty for an object */ + + /* How the arguments are written. Object: the arg_* fields below are empty, and these three + * describe the object's dialect -- a string delimiter besides JSON's `"`, between which the + * text is verbatim ("<|\"|>" twice for Gemma 4; empty for JSON strings only), and whether a + * key may be written bare. */ + ChatArgs args_form = ChatArgs::Tagged; + std::string object_string_open, object_string_close; + bool object_bare_keys = false; std::string arg_prefix; /* "\n" (MiniCPM: empty, the value prefix ends it) */ @@ -115,6 +146,7 @@ struct ChatFormat { bool has_reasoning() const { return !reasoning_close.empty(); } bool has_tools() const { return !name_prefix.empty(); } + bool object_args() const { return args_form == ChatArgs::Object; } }; /* Can the streaming parser run this format? RAD_OK, or RAD_E_UNSUPPORTED with *why naming the diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index ae2f9803..d81057ad 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -744,6 +744,25 @@ struct ReplyFormat::Impl { std::string cc_core; Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose; size_t longest = 0; /* the longest delimiter */ + + /* THE OBJECT FAMILY. `object`: a call's arguments are one object; `ns_object`: the object's + * own `{` is what ends the name (name_suffix empty), and ns_core is "{". */ + bool object = false, ns_object = false; + /* Where a key or a value may begin, besides the object's punctuation: the dialect string's + * opener, and the call's close and end -- a reply that leaves its object unclosed writes them + * there. Read anchored, by their first bytes (chat_format_check keeps them apart). */ + enum : uint8_t { LitString, LitClose, LitEnd }; + std::vector obj_lits; + std::vector obj_lit_kind; + /* A dialect string runs to its close. A bare value ends at `,` `}` `]` and a bare key at `:` + * `,` `}` -- patterns 0..2 -- or at the call's close or end, which follow at the indices + * below (-1: none). */ + Dfa obj_str, obj_bare, obj_key; + int bare_cc = -1, bare_ce = -1, key_cc = -1, key_ce = -1; + + /* REASONING ANYWHERE: content is scanned for a later block's opener and a stray close too, + * after the call openers (text_think) or alone when the request has no calls (think_only). */ + Dfa text_think, think_only; }; ReplyFormat::ReplyFormat() : impl_(std::make_unique()) {} @@ -773,6 +792,12 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr 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.object = f.has_tools() && f.object_args(); + if (m.object && f.name_suffix.empty()) { + m.ns_object = true; + m.ns_core = "{"; + m.ns_trail.clear(); + } if (f.has_reasoning()) { m.think.build({ m.close_core }); @@ -780,7 +805,39 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr for (const std::string& s : f.reasoning_breaks) b.push_back(s); m.think_breaks.build(b); } - if (f.has_tools()) { + if (f.reasoning_anywhere && f.has_reasoning()) { + std::vector t; + if (f.has_tools()) t = m.openers; + t.push_back(m.open_core); + t.push_back(m.close_core); + m.text_think.build(t); + m.think_only.build({ m.open_core, m.close_core }); + } + if (m.object) { + m.text.build(m.openers); + std::string trail; + split_ws(f.call_close, &m.cc_core, &trail); + std::vector bare{ ",", "}", "]" }, key{ ":", ",", "}" }; + if (!f.object_string_open.empty()) { + m.obj_lits.push_back(f.object_string_open); + m.obj_lit_kind.push_back(Impl::LitString); + m.obj_str.build({ f.object_string_close }); + } + if (!m.cc_core.empty()) { + m.obj_lits.push_back(m.cc_core); + m.obj_lit_kind.push_back(Impl::LitClose); + m.bare_cc = (int)bare.size(); bare.push_back(m.cc_core); + m.key_cc = (int)key.size(); key.push_back(m.cc_core); + } + if (!m.end_core.empty() && m.end_core != m.cc_core) { + m.obj_lits.push_back(m.end_core); + m.obj_lit_kind.push_back(Impl::LitEnd); + m.bare_ce = (int)bare.size(); bare.push_back(m.end_core); + m.key_ce = (int)key.size(); key.push_back(m.end_core); + } + m.obj_bare.build(bare); + m.obj_key.build(key); + } else if (f.has_tools()) { m.text.build(m.openers); m.arg_name.build({ m.name_end }); m.value.build({ f.arg_value_suffix }); @@ -800,7 +857,8 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open, &f.call_close, &f.name_prefix, &f.name_suffix, &f.call_end, &f.arg_prefix, &m.name_end, - &f.arg_value_suffix }; + &f.arg_value_suffix, &f.object_string_open, + &f.object_string_close }; for (const std::string* s : delims) m.longest = std::max(m.longest, s->size()); for (const std::string& s : f.reasoning_breaks) m.longest = std::max(m.longest, s.size()); *out = std::move(r); @@ -831,6 +889,9 @@ struct ReplyParser::Impl { bool calls = false; /* the request sent tools and the format has calls */ bool breaks = false; /* an unclosed reasoning block ends at a call */ bool pure = false; /* no reasoning, calls or document: every byte is content */ + /* A reasoning block may open later in the reply too (ChatFormat::reasoning_anywhere), and + * this request extracts reasoning. */ + bool anywhere = false; std::vector tools; std::unordered_map by_name; std::vector terminators; @@ -897,9 +958,10 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse optional.push_back(pname); } /* A name the argument's own delimiter could end early would be read as a - * different name. */ + * different name. An object's keys are delimited by its own punctuation, and + * one that holds it is written as a string. */ const std::string probe = pname + F.name_end; - if (probe.find(F.name_end) != pname.size()) { + if (!F.object && probe.find(F.name_end) != pname.size()) { *why = "parameter '" + pname + "' of tool '" + t.name + "' contains '" + F.name_end + "', which this model's tool-call format uses to end an " "argument name"; @@ -909,7 +971,8 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse } t.arms.insert(t.arms.end(), optional.begin(), optional.end()); if (t.name.find(F.ns_core) != std::string::npos || - (t.name + F.f.name_suffix).find(F.f.name_suffix) != t.name.size()) { + (!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 + "', which this model's tool-call format uses to end a function name"; return RAD_E_INVAL; @@ -949,6 +1012,8 @@ int ReplyParser::create(std::shared_ptr fmt, const ReplyOptio P.calls = want_calls && !opt.response_format; P.breaks = want_calls && F.f.has_reasoning() && !F.f.reasoning_breaks.empty(); P.pure = !F.f.has_reasoning() && !want_calls && !opt.response_format; + P.anywhere = F.f.reasoning_anywhere && F.f.has_reasoning() && opt.extract_reasoning && + !opt.response_format; if (F.f.has_reasoning()) { switch (F.f.reasoning_in_prompt) { @@ -1004,6 +1069,17 @@ enum class St : uint8_t { RfClose, /* "```" */ RfEnd, /* after the closing fence */ RfRaw, /* a reply that is not the document it was asked for: content */ + ObjStart, /* after a name_suffix: whitespace, then the argument object's `{` */ + ObjKey, /* where a key may begin, or the object's `}` */ + ObjKeyBare, /* a bare key, to its `:` */ + ObjColon, /* after a quoted key: whitespace, then `:` */ + ObjValue, /* where a value may begin, or an empty array's `]` */ + ObjLit, /* the dialect's string opener, or the call's close or end, being matched */ + ObjStr, /* a dialect string, to its close */ + ObjJStr, /* a JSON string, to its quote */ + ObjBare, /* a bare value: a number, a literal, or a word read as a string */ + ObjAfter, /* after a value: whitespace, then `,` or a closing bracket */ + ObjEnd, /* after the object: whitespace, then call_end */ }; /* A function name the grammar does not know is still read as a call, up to this long. */ @@ -1018,8 +1094,20 @@ struct ReplyStream::Impl { explicit Impl(const ReplyParser::Impl& p) : P(p), F(p.fmt->impl()) { content.init(P.terminators.empty() ? nullptr : &P.terms, &P.terminators); st = P.pure ? St::Text : St::LeadWs; + if (P.anywhere) { + text_dfa = P.calls ? &F.text_think : &F.think_only; + n_open = P.calls ? F.openers.size() : 0; + } else if (P.calls) { + text_dfa = &F.text; + n_open = F.openers.size(); + } } + /* What content is scanned with: the call openers when calls are on, then -- reasoning + * anywhere -- a later block's opener and a stray close. Null: content is every byte. */ + const Dfa* text_dfa = nullptr; + size_t n_open = 0; + ReplyMessage msg; ContentOut content; bool think_text = false; /* the reasoning has had a non-blank byte */ @@ -1062,6 +1150,19 @@ struct ReplyStream::Impl { size_t vs_pos = 0; bool fenced = false; + /* THE ARGUMENT OBJECT being read: its open brackets, whether a key (rather than a value) is + * being read, a separator read but not yet written -- it is written only once the next + * member shows the object goes on, so a trailing one never reaches the JSON -- whether the + * container was just opened, and whether a key's `:` went out with no value yet. */ + std::vector ostack; + bool okey = false, ocomma = false, ofirst = false, vpending = false; + /* A bare value's first bytes, to tell at its end whether it was a JSON number or literal -- + * which the grammar admits -- or a word read as a string, which it does not. */ + std::string bare_txt; + /* A JSON string's escape being read -- the backslash, and a "u" escape's four hex digits, + * in vheld -- and a high surrogate's escape, held until the low one shows it is a pair. */ + std::string jhi; + /* published offsets, for the deltas */ size_t sent_r = 0, sent_c = 0, sent_a = 0; int cur = -1; /* the channel last published: 0 r, 1 c, 2 args */ @@ -1202,7 +1303,7 @@ struct ReplyStream::Impl { bool declared_prefix(std::string_view n) const { for (const Tool& t : P.tools) { - const std::string full = t.name + F.f.name_suffix; + const std::string full = t.name + (F.ns_object ? F.ns_core : F.f.name_suffix); if (full.size() >= n.size() && full.compare(0, n.size(), n) == 0) return true; } return false; @@ -1283,14 +1384,180 @@ struct ReplyStream::Impl { cur = -1; event(ReplyEvent::CallBegin, (uint32_t)msg.calls.size() - 1, msg.calls.back().name); depth = 0; in_str = false; esc = false; - args_out("{"); argc = 0; ++calls; att.clear(); post_call = false; + if (F.object) { + /* The arguments are the object's, and its `{` is written now: a reply that ends + * here is a call with no arguments yet, as in the tagged family. */ + obj_out("{"); + ostack.assign(1, '{'); + okey = ocomma = vpending = false; + ofirst = true; + jhi.clear(); + st = F.ns_object ? St::ObjKey : St::ObjStart; + return; + } + args_out("{"); st = St::Body; } + /* ------------------------------------------------------------ the argument object + * + * The object of the object family, read as it streams and written as JSON as it is read: + * brackets and separators as they come, a key as soon as its `:` shows it is one, a string + * as its bytes arrive, and a bare value as the tagged family writes a typed one (ValueOut, + * Raw): held while it could still be a literal or a number, else a string. What the dialect + * spells otherwise -- its string delimiters, its bare keys -- is respelled; what leaves it + * -- a missing separator, a trailing one, a bracket of the wrong kind, an object the call's + * close cuts off -- is repaired locally and said so (strict). The arguments a closed call + * reports are JSON whatever was written. */ + + void obj_out(std::string_view s) { + if (s.empty()) return; + touch(2); + msg.calls.back().arguments.append(s.data(), s.size()); + } + void obj_flush() { if (!scratch.empty()) { obj_out(scratch); scratch.clear(); } } + + /* A member or an element begins: the separator before it, if one was read, goes out now. */ + void obj_sep() { + if (ocomma) { obj_out(","); ocomma = false; } + ofirst = false; + } + + /* The outermost bracket closed: what follows the object. */ + void obj_done() { + if (!F.end_core.empty()) { lpos = 0; lhold.clear(); st = St::ObjEnd; } + else end_call(); + } + + /* A closing bracket where a key, a value or a separator may stand. A separator before it is + * dropped, and a bracket of the other kind closes the open container all the same. */ + void obj_close_bracket(char c) { + if (ocomma) { lenient(); ocomma = false; } + const char top = ostack.back(); + if ((top == '{') != (c == '}')) lenient(); + if (vpending) { lenient(); obj_out("null"); vpending = false; } + ostack.pop_back(); + ofirst = false; + obj_out(top == '{' ? "}" : "]"); + if (ostack.empty()) obj_done(); + else st = St::ObjAfter; + } + + /* The punctuation after a value. */ + void obj_struct(char c) { + if (c != ',') { obj_close_bracket(c); return; } + if (ocomma) lenient(); /* `,,`: one separator */ + ocomma = true; + ofirst = false; + okey = ostack.back() == '{'; + st = okey ? St::ObjKey : St::ObjValue; + } + + bool obj_lit_start(unsigned char c) const { + for (const std::string& l : F.obj_lits) + if ((unsigned char)l[0] == c) return true; + return false; + } + + /* Bytes that open no string and close no call: a bare key or a bare value. */ + void obj_bare_begin() { + ds = 0; + hold.clear(); + if (okey) { + if (!F.f.object_bare_keys) lenient(); + name.clear(); + st = St::ObjKeyBare; + return; + } + obj_sep(); + vpending = false; + bare_txt.clear(); + val.begin(ValueOut::Raw, /*cdata=*/false, /*lead=*/false, /*trail=*/false, scratch); + obj_flush(); + st = St::ObjBare; + } + + static constexpr size_t kBareKeep = 64; /* longer than any number a model writes */ + + /* A bare value ended: one that is no JSON number or literal was read by the recovery rule. */ + void bare_done() { + std::string_view v(bare_txt); + while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1); + const bool json = bare_txt.size() < kBareKeep && !v.empty() && + (v == "true" || v == "false" || v == "null" || + ((v[0] == '-' || (v[0] >= '0' && v[0] <= '9')) && + nlohmann::json::accept(v))); + if (!json) lenient(); + } + + /* A JSON string, which is the dialect's own only when it declares no string delimiters. */ + void json_string_begin() { + if (!F.f.object_string_open.empty()) lenient(); + obj_out("\""); + vheld.clear(); + st = St::ObjJStr; + } + + /* One of the anchored literals matched where a key or a value may begin. */ + void obj_lit_done(uint8_t kind) { + if (kind == ReplyFormat::Impl::LitString) { + obj_sep(); + if (!okey) vpending = false; + obj_out("\""); + ds = 0; + hold.clear(); + st = St::ObjStr; + return; + } + /* The call's close or end where the object wanted more: the reply left the object + * unclosed, and the call ends here with it closed. */ + lenient(); + ocomma = false; + if (kind == ReplyFormat::Impl::LitClose) end_call_at_close(); + else end_core_done(); + } + + /* A JSON string's text goes out as it is, its escapes checked: one JSON has not is the + * backslash and the letter as text, a raw control character is escaped, and a surrogate + * escape that is not half of a pair is U+FFFD -- a client's JSON parser refuses all three. */ + void jstr_char(const char* q, size_t n) { + if (n == 0) return; + if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); } + touch(2); + json_escape_into(msg.calls.back().arguments, q, n); + } + + void jstr_escape_done(const std::string& e) { + /* e: a complete two-character escape, or a "u" escape with its four digits. */ + if (e.size() == 6) { + const unsigned long cp = std::strtoul(e.c_str() + 2, nullptr, 16); + if (cp >= 0xD800 && cp <= 0xDBFF) { + if (!jhi.empty()) { lenient(); obj_out("\\ufffd"); } + jhi = e; + return; + } + if (cp >= 0xDC00 && cp <= 0xDFFF) { + if (jhi.empty()) { lenient(); obj_out("\\ufffd"); return; } + obj_out(jhi + e); + jhi.clear(); + return; + } + } + if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); } + obj_out(e); + } + + /* A string or a key closed. */ + void obj_string_done() { + if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); } + obj_out("\""); + st = okey ? St::ObjColon : St::ObjAfter; + } + /* The core of call_end has matched. The whitespace the format writes after it is part of the * tag, so the call closes when that has arrived too -- a reply that ends in between leaves the * call open, as the grammar does -- and a reply that goes straight on without it has closed @@ -1306,8 +1573,18 @@ struct ReplyStream::Impl { * match, so no quote is ever pending here; a raw value that left a string open is passed * through as the model wrote it. */ void end_call() { - std::string close((size_t)std::max(depth, 0), '}'); - args_out(close); + if (F.object) { + /* What the object left open is closed, so the arguments are JSON: a key whose value + * never came is null, and each bracket gets its partner. */ + std::string close = vpending ? "null" : ""; + vpending = false; + for (auto it = ostack.rbegin(); it != ostack.rend(); ++it) close += *it == '{' ? '}' : ']'; + ostack.clear(); + obj_out(close); + } else { + std::string close((size_t)std::max(depth, 0), '}'); + args_out(close); + } publish(2, true); msg.calls.back().closed = true; event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {}); @@ -1499,14 +1776,22 @@ struct ReplyStream::Impl { return p; case St::Text: - if (!P.calls) { + if (!text_dfa) { text_out(p, (size_t)(e - p)); return e; } - p = scan(F.text, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); - if (hit >= 0) { + p = scan(*text_dfa, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); + if (hit < 0) return p; + if ((size_t)hit < n_open) { att_at = here(p) - F.openers[(size_t)hit].size(); begin_text_attempt(hit); + } else if ((size_t)hit == n_open) { + /* A reasoning block opens again, later in the reply. */ + trail = 0; + st = St::ThinkOpenWs; + } else { + /* Its close with no block open: not part of the answer. */ + lenient(); } return p; @@ -1558,12 +1843,18 @@ struct ReplyStream::Impl { lpos = 0; lhold.clear(); tag_end = att.size(); - if (loose) st = St::OpenPeek; + if (loose && F.object) { + /* A call written without its wrapper, in the object family: a declared + * tool's name and the object's opening are what make it one. */ + if (tool < 0) { fail_attempt(); return p + 1; } + begin_call(false); + } else if (loose) st = St::OpenPeek; else if (F.ns_trail.empty()) begin_call(true); else st = St::OpenTail; return p + 1; } - if (name.size() > kMaxLooseName || (c == '<' && !declared_prefix(name))) { + if (name.size() > kMaxLooseName || (c == '<' && !declared_prefix(name)) || + (loose && F.object && !declared_prefix(name))) { fail_attempt(); return p + 1; } @@ -1775,6 +2066,245 @@ struct ReplyStream::Impl { if (p < e) { post_call = true; ds = 0; hold.clear(); st = St::Text; } return p; + case St::ObjStart: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + if (*p == '{') { ofirst = true; okey = true; st = St::ObjKey; return p + 1; } + /* No object after the name: the call takes none, and what stands there instead is + * read as what follows a call. */ + lenient(); + obj_done(); + return p; + + case St::ObjKey: { + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + const char c = *p; + okey = true; + if (c == '}' || c == ']') { obj_close_bracket(c); return p + 1; } + if (c == ',') { lenient(); return p + 1; } /* an empty member */ + if (c == '"') { + obj_sep(); + json_string_begin(); + return p + 1; + } + if (obj_lit_start((unsigned char)c)) { lhold.clear(); st = St::ObjLit; return p; } + obj_bare_begin(); + return p; + } + + case St::ObjKeyBare: + p = scan(F.obj_key, p, e, &hit, [this](const char* q, size_t n) { name.append(q, n); }); + if (hit < 0) return p; + if (hit <= 2) { + std::string_view k(name); + while (!k.empty() && is_ws((unsigned char)k.back())) k.remove_suffix(1); + if (k.empty()) lenient(); + obj_sep(); + std::string out = json_quote(k); + name.clear(); + if (hit == 0) { + obj_out(out + ":"); + vpending = true; + okey = false; + st = St::ObjValue; + return p; + } + /* A key with no value: it is null. */ + lenient(); + obj_out(out + ":null"); + obj_struct(hit == 1 ? ',' : '}'); + return p; + } + /* The call's close or end inside a key: the key had no value, and goes. */ + name.clear(); + lenient(); + ocomma = false; + if (hit == F.key_cc) end_call_at_close(); + else end_core_done(); + return p; + + case St::ObjColon: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + vpending = true; + okey = false; + st = St::ObjValue; + if (*p == ':') { obj_out(":"); return p + 1; } + lenient(); + obj_out(":"); + return p; + + case St::ObjValue: { + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + const char c = *p; + const bool in_array = ostack.back() == '['; + okey = false; + if (c == '{' || c == '[') { + obj_sep(); + vpending = false; + obj_out(c == '{' ? "{" : "["); + ostack.push_back(c); + ofirst = true; + okey = c == '{'; + st = c == '{' ? St::ObjKey : St::ObjValue; + return p + 1; + } + if (c == ']' && in_array && ofirst) { obj_close_bracket(c); return p + 1; } + if (c == '}' || c == ']' || c == ',') { + /* No value where one was due: a member's is null, and an array's gap is no + * element. */ + lenient(); + if (!in_array) { + obj_out("null"); + vpending = false; + st = St::ObjAfter; + return p; + } + if (c == ',') return p + 1; + obj_close_bracket(c); + return p + 1; + } + if (c == '"') { + obj_sep(); + vpending = false; + json_string_begin(); + return p + 1; + } + if (obj_lit_start((unsigned char)c)) { lhold.clear(); st = St::ObjLit; return p; } + obj_bare_begin(); + return p; + } + + case St::ObjLit: { + const char c = *p; + lhold.push_back(c); + bool part = false; + for (size_t i = 0; i < F.obj_lits.size(); ++i) { + const std::string& l = F.obj_lits[i]; + if (lhold.size() > l.size() || l.compare(0, lhold.size(), lhold) != 0) continue; + if (lhold.size() < l.size()) { part = true; continue; } + lhold.clear(); + obj_lit_done(F.obj_lit_kind[i]); + return p + 1; + } + if (part) return p + 1; + /* None of them: the bytes begin a bare key or value. */ + std::string again; + again.swap(lhold); + obj_bare_begin(); + read_again(again); + return p + 1; + } + + case St::ObjStr: + p = scan(F.obj_str, p, e, &hit, [this](const char* q, size_t n) { + touch(2); + json_escape_into(msg.calls.back().arguments, q, n); + }); + if (hit >= 0) obj_string_done(); + return p; + + case St::ObjJStr: { + const char* run = p; + while (p < e) { + const unsigned char c = (unsigned char)*p; + if (vheld.size() == 1) { /* after the backslash */ + if (c && std::strchr("\"\\/bfnrt", (int)c)) { + vheld.push_back((char)c); + jstr_escape_done(vheld); + vheld.clear(); + run = ++p; + continue; + } + if (c == 'u') { vheld.push_back('u'); run = ++p; continue; } + /* No JSON escape: the backslash is text, and what follows it is read as + * the string's next byte. */ + lenient(); + vheld.clear(); + jstr_char("\\", 1); + run = p; + continue; + } + if (!vheld.empty()) { /* a "u" escape's digits */ + if (std::isxdigit(c)) { + vheld.push_back((char)c); + if (vheld.size() == 6) { jstr_escape_done(vheld); vheld.clear(); } + run = ++p; + continue; + } + lenient(); + const std::string text = vheld; + vheld.clear(); + jstr_char(text.data(), text.size()); + run = p; + continue; + } + if (c != '"' && c != '\\') { ++p; continue; } + jstr_char(run, (size_t)(p - run)); + ++p; + if (c == '"') { obj_string_done(); return p; } + vheld.assign(1, '\\'); + run = p; + } + jstr_char(run, (size_t)(p - run)); + return p; + } + + case St::ObjBare: + p = scan(F.obj_bare, p, e, &hit, [this](const char* q, size_t n) { + if (bare_txt.size() < kBareKeep) + bare_txt.append(q, std::min(n, kBareKeep - bare_txt.size())); + val.add(q, n, scratch); + obj_flush(); + }); + if (hit < 0) return p; + val.finish(false, scratch); + obj_flush(); + bare_done(); + if (hit <= 2) { obj_struct(",}]"[hit]); return p; } + lenient(); + if (hit == F.bare_cc) end_call_at_close(); + else end_core_done(); + return p; + + case St::ObjAfter: { + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + const char c = *p; + if (c == ',' || c == '}' || c == ']') { obj_struct(c); return p + 1; } + /* A key or a value with no separator before it: one is supplied. */ + lenient(); + ocomma = true; + ofirst = false; + okey = ostack.back() == '{'; + st = okey ? St::ObjKey : St::ObjValue; + return p; + } + + case St::ObjEnd: { + if (lpos == 0) { + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + } + const char c = *p; + if (c == F.end_core[lpos]) { + lhold.push_back(c); + if (++lpos == F.end_core.size()) { lhold.clear(); lpos = 0; end_core_done(); } + return p + 1; + } + /* The object is not followed by the call's end: the call ends with it all the same, + * and what stands there is read as what follows a call. */ + lenient(); + std::string again; + again.swap(lhold); + lpos = 0; + end_call(); + read_again(again); + return p; + } + case St::RfWs: while (p < e && is_ws((unsigned char)*p)) ++p; if (p < e) { @@ -1998,6 +2528,11 @@ struct ReplyStream::Impl { case St::ValJsonEnd: json_value_done(std::string_view(vheld).substr(0, vheld.size() - vs_pos)); break; + case St::ObjBare: + /* A bare value the reply was cut off inside: as it arrived. The call is open. */ + val.finish(true, scratch); + obj_flush(); + break; default: break; } @@ -2066,7 +2601,8 @@ ReplyHeld ReplyStream::held() const { (m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) + (m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a); h.space = m.content.held_space() + m.think_pend.size(); - h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container(); + h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container() + + m.jhi.size(); return h; } diff --git a/spec.md b/spec.md index 38bfaee8..7815552a 100644 --- a/spec.md +++ b/spec.md @@ -1472,6 +1472,12 @@ how a value is encoded — is plain data (`core/text/chatfmt.h`), and everything spelling is derived from it: the parser that reads the reply back, the lazy tool-call grammar and the literal words that trigger it, and the control tokens the decoder must render as text. +Two families of call syntax are described. In the tagged one each argument has its own tags +(Qwen's ``, MiniCPM's ``) and is typed by the tool's schema. In +the object one a call is its name and ONE object holding the arguments — JSON, or a dialect of +it with strings between declared delimiters and bare keys, as Gemma 4 writes +`call:NAME{path:<|"|>/a<|"|>,limit:3}` — and the values carry their own types. + There are two producers, in order of precedence. An architecture plugin may declare the format through the optional `rad_arch_chat_format` export (`abi/rad_builder.h`) — a new model whose template the analysis cannot read is supported by stating its format once. Otherwise the format diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index 33a8d075..6ebaa30a 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -1492,6 +1492,187 @@ TEST(a_template_whose_calls_cannot_be_described_refuses_tools_and_still_chats) { CHECK(!why.empty()); } +/* ================================================================== the object family + * + * A call written as its name and ONE object holding the arguments (ChatArgs::Object): JSON behind + * a name tag with neither an end nor a wrapper -- Mistral's `[TOOL_CALLS]NAME[ARGS]{...}` -- and + * behind a function tag that has its own close. The dialect fields (Gemma 4's strings and bare + * keys) are held in chatparse_gemma4_test, against the model's own template and llama.cpp's + * parser for it. */ + +static std::shared_ptr object_format(bool tagged_end, ChatFormat* out = nullptr) { + static const char* const kT1[] = { "[TOOL_CALLS]" }; + static const char* const kT2[] = { "" }; + RadChatFormat c{}; + c.struct_size = sizeof(RadChatFormat); + c.args_form = RAD_CHAT_ARGS_OBJECT; + if (!tagged_end) { + c.name = "test:name-tag"; + c.name_prefix = "[TOOL_CALLS]"; + c.name_suffix = "[ARGS]"; + c.triggers = kT1; + } else { + c.name = "test:function-tag"; + c.call_open = "\n"; + c.call_close = ""; + c.name_prefix = " rf; + std::shared_ptr p; + if (chat_format_from_abi(&c, &f, &why) < 0 || ReplyFormat::compile(f, &rf, &why) < 0) { + ::radtest::fail(__FILE__, __LINE__, why); + return nullptr; + } + if (out) *out = f; + ReplyOptions ro; + ro.tools = &agent_tools(); + if (ReplyParser::create(rf, ro, &p, &why) < 0) ::radtest::fail(__FILE__, __LINE__, why); + return p; +} + +static int object_admits(const std::string& gbnf, const std::string& text) { + static const SimpleVocab vocab = [] { + SimpleVocab v; + for (int c = 32; c < 127; ++c) v.add(std::string(1, (char)c)); + v.add("\n"); + return v; + }(); + std::unique_ptr gr; + std::string err; + if (GbnfGrammar::create(gbnf, "root", &vocab, false, {}, {}, &gr, &err) < 0) return -1; + if (gr->accept_str(text) < 0) return 0; + return gr->complete() ? 1 : 0; +} + +TEST(json_arguments_behind_a_name_tag_read_as_one_object) { + std::shared_ptr p = object_format(false); + REQUIRE(p != nullptr); + bool strict = false; + const std::string reply = "Sure.[TOOL_CALLS]bash[ARGS]{\"command\": \"ls -la\", \"timeout\": 30}" + "[TOOL_CALLS]read[ARGS]{\"path\": \"/a\", \"limit\": [1, {\"x\": null}]}"; + const ReplyMessage m = reply_parse(*p, reply, &strict); + CHECK(strict); + CHECK_EQ(m.content, std::string("Sure.")); + REQUIRE(m.calls.size() == 2); + CHECK_EQ(m.calls[0].arguments, std::string("{\"command\":\"ls -la\",\"timeout\":30}")); + CHECK_EQ(m.calls[1].arguments, std::string("{\"path\":\"/a\",\"limit\":[1,{\"x\":null}]}")); + const std::string err = stream_all(*p, reply); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + /* A bare key is outside JSON: read, and said so. */ + const ReplyMessage b = reply_parse(*p, "[TOOL_CALLS]read[ARGS]{path: \"/a\"}", &strict); + CHECK(!strict); + REQUIRE(b.calls.size() == 1); + CHECK_EQ(b.calls[0].arguments, std::string("{\"path\":\"/a\"}")); + /* No object after the tag: a call with none, and what stood there is content. */ + const ReplyMessage n = reply_parse(*p, "[TOOL_CALLS]ping[ARGS] and then", &strict); + CHECK(!strict); + REQUIRE(n.calls.size() == 1); + CHECK_EQ(n.calls[0].arguments, std::string("{}")); + CHECK_EQ(n.content, std::string("and then")); +} + +TEST(json_arguments_behind_a_function_tag_end_at_its_close) { + ChatFormat f; + std::shared_ptr p = object_format(true, &f); + REQUIRE(p != nullptr); + bool strict = false; + const std::string reply = "\n{\"command\": \"ls\"}\n" + "\n{\"path\": \"/a\"}\n\n"; + const ReplyMessage m = reply_parse(*p, reply, &strict); + CHECK(strict); + REQUIRE(m.calls.size() == 2); + CHECK_EQ(m.calls[0].arguments, std::string("{\"command\":\"ls\"}")); + CHECK_EQ(m.calls[1].arguments, std::string("{\"path\":\"/a\"}")); + const std::string err = stream_all(*p, reply); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + /* The function's close where the object was still open closes it. */ + const ReplyMessage c = reply_parse( + *p, "\n{\"path\": \"/a\"\n", &strict); + CHECK(!strict); + REQUIRE(c.calls.size() == 1); + CHECK(c.calls[0].closed); + CHECK_EQ(c.calls[0].arguments, std::string("{\"path\":\"/a\"}")); + + /* The grammar: a JSON object between the tags, and the tags as written. */ + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + ChatGrammar g; + std::string why; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + CHECK(g.lazy); + log_set_level(Log::Error); + CHECK_EQ(object_admits(g.text, "\n{\"command\": \"ls\", \"n\": [1, {\"a\": null}]}" + "\n"), 1); + CHECK_EQ(object_admits(g.text, "\n{command: \"ls\"}\n"), 0); + CHECK_EQ(object_admits(g.text, "\n{}\n"), 0); + log_set_level(Log::Warn); +} + +/* reasoning_anywhere: a block that opens after the answer is reasoning there too, and a close + * with no block open is not part of the answer. Without it, both are content. */ +TEST(a_reasoning_block_may_open_again_later_when_the_format_says_so) { + for (bool anywhere : { false, true }) { + RadChatFormat c = qwen_abi(); + c.reasoning_anywhere = anywhere ? 1 : 0; + ChatFormat f; + std::string why; + std::shared_ptr rf; + std::shared_ptr p; + CHECK_OK(chat_format_from_abi(&c, &f, &why)); + CHECK_OK(ReplyFormat::compile(f, &rf, &why)); + ReplyOptions ro; + ro.generation_prompt = "<|im_start|>assistant\n\n"; + ro.tools = &agent_tools(); + CHECK_OK(ReplyParser::create(rf, ro, &p, &why)); + const std::string reply = "Plan.\n\n\nAnswer.\nmore\n\n\nTail."; + bool strict = false; + const ReplyMessage m = reply_parse(*p, reply, &strict); + if (anywhere) { + CHECK_EQ(m.reasoning, std::string("Plan.\nmore\n")); + CHECK_EQ(m.content, std::string("Answer.Tail.")); + CHECK(!strict); /* the last closed nothing */ + } else { + CHECK_EQ(m.reasoning, std::string("Plan.\n")); + CHECK_EQ(m.content, std::string("Answer.\nmore\n\n\nTail.")); + } + const std::string err = stream_all(*p, reply); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + } +} + +TEST(an_object_format_the_parser_cannot_read_is_refused) { + auto refused = [](void (*edit)(RadChatFormat&), const char* word) { + static const char* const kT[] = { "[TOOL_CALLS]" }; + RadChatFormat c{}; + c.struct_size = sizeof(RadChatFormat); + c.args_form = RAD_CHAT_ARGS_OBJECT; + c.name_prefix = "[TOOL_CALLS]"; + c.name_suffix = "[ARGS]"; + c.triggers = kT; + c.n_triggers = 1; + edit(c); + ChatFormat f; + std::string why; + if (chat_format_from_abi(&c, &f, &why) < 0) return false; + return chat_format_check(f, &why) == RAD_E_UNSUPPORTED && why.find(word) != std::string::npos; + }; + CHECK(refused([](RadChatFormat&) {}, "") == false); /* the base is a format */ + CHECK(refused([](RadChatFormat& c) { c.arg_value_suffix = ""; }, "arg_*")); + CHECK(refused([](RadChatFormat& c) { c.object_string_open = ""; }, "together")); + CHECK(refused([](RadChatFormat& c) { c.object_string_open = c.object_string_close = "'"; }, + "bare word")); + CHECK(refused([](RadChatFormat& c) { c.call_end = "<,>"; }, "punctuation")); + CHECK(refused([](RadChatFormat& c) { c.call_end = " \n"; }, "only whitespace")); + CHECK(refused([](RadChatFormat& c) { c.name_prefix = ""; c.triggers = nullptr; c.n_triggers = 0; }, + "name_prefix is empty")); +} + /* ================================================================== cost * * The legacy path re-parses the whole reply on every chunk, so a reply of n bytes costs O(n^2). The