Archived
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<|"|>}<tool_call|>`
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.
215 lines
12 KiB
C++
215 lines
12 KiB
C++
/* chatfmt.h -- how a model spells a turn: reasoning, tool calls, arguments. As DATA.
|
|
*
|
|
* Everything the engine knows about a model's reply syntax is in one plain struct, ChatFormat,
|
|
* and everything that depends on that syntax is DERIVED from it: the streaming reply parser
|
|
* (chatparse.h), the lazy tool-call grammar and the literal words that trigger it (below), and the
|
|
* tokens the decoder must render as text so the parser can see the structure. A new model is
|
|
* supported by stating its format once.
|
|
*
|
|
* TWO PRODUCERS, IN ORDER OF PRECEDENCE.
|
|
*
|
|
* 1. The architecture plugin, through the optional `rad_arch_chat_format` export
|
|
* (abi/rad_builder.h). A plugin that knows its model's syntax says so and nothing is guessed.
|
|
* 2. Analysis of the chat template. llama.cpp's differential analyser renders the template with
|
|
* and without a reasoning block, a call and its arguments, and diffs the renders to find the
|
|
* delimiters (vendor/llama/common/chat-diff-analyzer.cpp). Its derived MARKERS are read here;
|
|
* its PEG parser is not used.
|
|
*
|
|
* If neither yields a format the parser can run, the model still chats -- the reply is content --
|
|
* but a request that sends tools is refused, naming why. There is no second parser to fall back
|
|
* to: a reply format the engine cannot describe is a reply it cannot read, and saying so at
|
|
* admission is better than returning a call as prose.
|
|
*
|
|
* THE FAMILY THIS DESCRIBES is the tagged one, which covers every model this engine serves:
|
|
*
|
|
* Qwen3.6 / Qwen3.8 <tool_call>\n<function=NAME>\n<parameter=ARG>\nVALUE\n</parameter>\n
|
|
* </function>\n</tool_call>
|
|
* MiniCPM5 <function name="NAME"><param name="ARG">VALUE</param></function>
|
|
*
|
|
* A call's name is written between a prefix and a suffix and it ends with its own close; each
|
|
* argument is a name between a prefix and a suffix and a value ending at its own suffix; calls may
|
|
* be wrapped one by one. Arguments are typed by the tool's JSON schema: a string-typed argument is
|
|
* 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 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}<tool_call|>
|
|
*
|
|
* 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"
|
|
|
|
#include <nlohmann/json_fwd.hpp>
|
|
|
|
#include <cstdint>
|
|
#include <memory>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
struct RadChatFormat;
|
|
|
|
namespace rad {
|
|
|
|
/* How a value is written between its delimiters. The numbering is the ABI's (RAD_CHAT_VALUE_*). */
|
|
enum class ChatValue : uint32_t {
|
|
Raw = 0, /* the text, verbatim */
|
|
Cdata = 1, /* the text, unless wrapped in <![CDATA[ ]]>, which is punctuation and removed */
|
|
Json = 2, /* a JSON value; text that does not parse as one is taken raw */
|
|
};
|
|
|
|
/* Whether the reply starts inside a reasoning block. The numbering is the ABI's. */
|
|
enum class ChatThink : uint32_t {
|
|
/* Search the rendered generation prompt for `reasoning_open`: whatever follows its first
|
|
* occurrence is the start of the reply's own text. A template that opens the block for the
|
|
* model (Qwen writes "<think>\n" at the end of the prompt) and one that closes it again when
|
|
* thinking is off ("<think>\n\n</think>\n\n") are both read correctly this way. */
|
|
FromPrompt = 0,
|
|
Always = 1, /* the reply is inside a reasoning block from its first byte */
|
|
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:<arch>" or "template" */
|
|
|
|
/* ------------------------------------------------------------------ reasoning
|
|
* A block runs from `reasoning_open` to `reasoning_close`. Whitespace at either end of either
|
|
* tag is optional when matching, so "<think>\n" also matches "<think>". An empty close means
|
|
* the format has no reasoning block. An empty open with a close means the reply starts in one
|
|
* and the close ends it. */
|
|
std::string reasoning_open;
|
|
std::string reasoning_close;
|
|
/* Literals that end an UNCLOSED block when a call starts there. A model that forgets to close
|
|
* its reasoning and goes straight to a call must not have the call swallowed as reasoning.
|
|
* Must name the call opener (`call_open`) when non-empty. */
|
|
std::vector<std::string> 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
|
|
* format has no tool calls. */
|
|
std::string section_open, section_close; /* around ALL calls; not read yet, must be empty */
|
|
/* Between two calls beyond whitespace. Tagged calls are self-delimiting, so this is empty;
|
|
* a JSON-array format would say ", ". Not read yet, must be empty. */
|
|
std::string call_separator;
|
|
/* Around EACH call: "<tool_call>\n", "</tool_call>". 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;
|
|
/* "<function=", ">\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; /* "</function>\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; /* "<parameter=" */
|
|
std::string arg_name_suffix; /* ">\n" (MiniCPM: empty, the value prefix ends it) */
|
|
std::string arg_value_prefix; /* "" (MiniCPM: "\">") */
|
|
std::string arg_value_suffix; /* "</parameter>\n" */
|
|
|
|
ChatValue string_value = ChatValue::Cdata; /* a string-typed argument: Raw or Cdata */
|
|
ChatValue other_value = ChatValue::Json; /* any other type: Json */
|
|
/* One newline at each end of a value is punctuation: the template writes the value on its own
|
|
* lines, and exactly the first and last newline belong to the tags. A tag that ends with its
|
|
* newline (Qwen's `>\n`) has written the first one already, and the value starts after it. */
|
|
bool value_newlines = true;
|
|
|
|
/* The literal words that start constrained decoding of a call. Empty means no lazy grammar:
|
|
* the reply is unconstrained and the parser reads whatever arrives. */
|
|
std::vector<std::string> triggers;
|
|
|
|
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
|
|
* field. A format with no tool calls is valid (reasoning split only); a format with tool calls
|
|
* must describe them completely enough that every delimiter is unambiguous. */
|
|
int chat_format_check(const ChatFormat& f, std::string* why);
|
|
|
|
/* The plugin's declaration, copied out of the ABI struct. Fields past the plugin's
|
|
* `struct_size` read as their zero. Returns RAD_E_INVAL with *why when the struct is unusable. */
|
|
int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* why);
|
|
|
|
/* Derive the format from a chat template by the vendored differential analysis.
|
|
*
|
|
* RAD_OK with *out filled. A template whose tool calls the analysis found but this family cannot
|
|
* express still yields its reasoning split, with the tool fields empty and *tools_refused saying
|
|
* why -- the model chats, and a request with tools is refused with that sentence. RAD_E_UNSUPPORTED
|
|
* with *why when the template routes to one of llama.cpp's hand-written handlers, whose formats
|
|
* the analysis does not describe at all; RAD_E_FORMAT when the template does not compile. An
|
|
* empty source is the ChatML fallback, which has neither reasoning nor calls. */
|
|
int chat_format_from_template(const std::string& jinja, const std::string& bos,
|
|
const std::string& eos, ChatFormat* out,
|
|
std::string* tools_refused, std::string* why);
|
|
|
|
/* Human-readable one-liner for the startup log. */
|
|
std::string chat_format_describe(const ChatFormat& f);
|
|
|
|
/* ================================================================== grammar
|
|
*
|
|
* The GBNF that constrains a reply to the format, generated from the description. For a tool
|
|
* request it is LAZY: the reply is free until one of `triggers` appears, and from there the
|
|
* grammar admits the call syntax with each argument constrained by its schema. For a response
|
|
* format, and for a request that requires a call, it is the whole reply. Rule names and structure
|
|
* follow the vendored generator so the two produce the same grammar for a template-analysed
|
|
* format. */
|
|
struct ChatGrammarRequest {
|
|
const nlohmann::ordered_json* tools = nullptr; /* the request's tools, or null */
|
|
const nlohmann::ordered_json* json_schema = nullptr; /* a response format's schema, or null */
|
|
std::string generation_prompt;
|
|
bool parallel_tool_calls = true;
|
|
bool extract_reasoning = true; /* reasoning_format != "none" */
|
|
/* tool_choice "required" or a named function: the grammar is the whole reply rather than lazy,
|
|
* the reasoning block and then the calls with nothing after them, and `only_tool` (when set)
|
|
* narrows the calls to that one function. */
|
|
bool require_call = false;
|
|
std::string only_tool;
|
|
};
|
|
|
|
struct ChatGrammar {
|
|
std::string text; /* empty when the request is unconstrained */
|
|
bool lazy = false;
|
|
std::vector<std::string> trigger_words;
|
|
};
|
|
|
|
/* RAD_OK, or RAD_E_INVAL with *why when a tool or schema cannot be expressed. */
|
|
int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, ChatGrammar* out,
|
|
std::string* why);
|
|
|
|
/* The markers the decoder must render as text for the parser to see them: a format built from
|
|
* control tokens reaches the parser with its structure gone otherwise, because the decoder
|
|
* suppresses control tokens. Every non-empty delimiter, whitespace-trimmed, deduplicated, in the
|
|
* order the vendored analyser lists them -- a marker that is not a single token is harmless, the
|
|
* decoder only compares it with the spellings of control tokens. */
|
|
std::vector<std::string> chat_format_markers(const ChatFormat& f);
|
|
|
|
} /* namespace rad */
|