radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+522
View File
@@ -0,0 +1,522 @@
#include "chatdiff.h"
#include "text/tokenizer.h"
#include <cstdio>
#include <random>
namespace rad {
namespace chatdiff {
const std::vector<Model>& models() {
static const std::vector<Model> m = {
{ "qwen3.8", "qwen3.8", "", "<|im_end|>", { "<|im_end|>", "<|endoftext|>" } },
{ "qwen3.6", "qwen3.6", "", "<|im_end|>", { "<|im_end|>", "<|endoftext|>" } },
{ "minicpm5", "minicpm5", "<s>", "</s>", { "</s>", "<|im_end|>" } },
};
return m;
}
std::string describe(const ChatRequest& r) {
std::string s = r.tools ? "tools" : "no-tools";
if (!r.parallel) s += ",single";
if (!r.thinking) s += ",no-think";
if (!r.reasoning) s += ",reasoning-none";
if (!r.schema.empty()) s += ",response-format";
return s;
}
const ojson& agent_tools() {
static const ojson t = ojson::parse(R"([
{"type":"function","function":{"name":"bash","description":"Run a shell command.",
"parameters":{"type":"object","properties":{"command":{"type":"string"},
"timeout":{"type":"integer"},"description":{"type":"string"}},"required":["command"]}}},
{"type":"function","function":{"name":"read","description":"Read a file.",
"parameters":{"type":"object","properties":{"path":{"type":"string"},
"offset":{"type":"integer"},"limit":{"type":"integer"}},"required":["path"]}}},
{"type":"function","function":{"name":"write","description":"Write a file.",
"parameters":{"type":"object","properties":{"path":{"type":"string"},
"content":{"type":"string"}},"required":["path","content"]}}},
{"type":"function","function":{"name":"edit","description":"Apply edits to a file.",
"parameters":{"type":"object","properties":{"path":{"type":"string"},
"edits":{"type":"array","items":{"type":"object","properties":{
"oldText":{"type":"string"},"newText":{"type":"string"}},
"required":["oldText","newText"]}}},"required":["path","edits"]}}},
{"type":"function","function":{"name":"todo_write","description":"Update the todo list.",
"parameters":{"type":"object","properties":{"todos":{"type":"array","items":{
"type":"object","properties":{"content":{"type":"string"},
"status":{"type":"string","enum":["pending","in_progress","completed"]}},
"required":["content","status"]}}},"required":["todos"]}}},
{"type":"function","function":{"name":"configure","description":"Set options.",
"parameters":{"type":"object","properties":{"verbose":{"type":"boolean"},
"level":{"type":"number"},"mode":{"enum":["fast","slow"]},"extra":{"type":"object"},
"label":{"type":["string","null"]},"tags":{"type":"array","items":{"type":"string"}},
"nothing":{"type":"null"}}}}},
{"type":"function","function":{"name":"ping","description":"Takes no arguments.",
"parameters":{"type":"object","properties":{}}}}
])");
return t;
}
int Bench::load(const Model& m, const std::string& jinja, std::string* why) {
model_ = m;
jinja_ = jinja;
tmpl_ = std::make_shared<ChatTemplate>();
if (tmpl_->load(jinja, m.bos, m.eos) < 0) {
*why = "the template did not compile";
return RAD_E_FORMAT;
}
std::string refused;
int st = chat_format_from_template(jinja, m.bos, m.eos, &fmt_, &refused, why);
if (st < 0) return st;
if (!refused.empty()) {
*why = "tool calls refused: " + refused;
return RAD_E_UNSUPPORTED;
}
return ReplyFormat::compile(fmt_, &rf_, why);
}
static ChatOptions options_for(const ChatRequest& rq) {
ChatOptions opt;
opt.add_generation_prompt = true;
opt.enable_thinking = rq.thinking;
opt.parallel_tool_calls = rq.parallel;
opt.reasoning_format = rq.reasoning ? "auto" : "none";
opt.json_schema = rq.schema;
return opt;
}
static ojson user_turn() {
return ojson::array({ ojson{ { "role", "user" }, { "content", "Fix the failing test in /work." } } });
}
int Bench::bind(const ChatRequest& rq, const ojson& tools, std::string* why) {
req_ = rq;
tools_ = tools;
prompt_ = ChatPrompt{};
const ChatOptions opt = options_for(rq);
if (tmpl_->apply(user_turn(), rq.tools ? tools_ : ojson(), opt, &prompt_) < 0) {
*why = "render failed: " + prompt_.error;
return RAD_E_INVAL;
}
old_ = std::make_unique<legacy::ToolParser>();
if (old_->init(prompt_, opt.reasoning_format, rq.tools) < 0) {
*why = "the old parser did not load";
return RAD_E_FORMAT;
}
ReplyOptions ro;
ro.generation_prompt = prompt_.generation_prompt;
ro.extract_reasoning = rq.reasoning;
ro.tools = rq.tools ? &tools_ : nullptr;
ro.parallel_tool_calls = rq.parallel;
ro.response_format = !rq.schema.empty();
ro.terminators = model_.terminators;
return ReplyParser::create(rf_, ro, &parser_, why);
}
legacy::Answer Bench::old_parse(const std::string& text, bool partial) const {
return legacy::legacy_parse(*old_, text, partial, req_.tools, model_.terminators);
}
ReplyMessage Bench::new_parse(const std::string& text, bool* strict) const {
return reply_parse(*parser_, text, strict);
}
std::string Bench::render_reply(const ojson& assistant) const {
ChatOptions opt = options_for(req_);
ChatPrompt head, whole;
if (tmpl_->apply(user_turn(), req_.tools ? tools_ : ojson(), opt, &head) < 0) return "";
ojson msgs = user_turn();
msgs.push_back(assistant);
opt.add_generation_prompt = false;
if (tmpl_->apply(msgs, req_.tools ? tools_ : ojson(), opt, &whole) < 0) return "";
if (whole.prompt.size() < head.prompt.size() ||
whole.prompt.compare(0, head.prompt.size(), head.prompt) != 0)
return "";
std::string reply = whole.prompt.substr(head.prompt.size());
while (!reply.empty() && reply.back() == '\n') reply.pop_back();
for (const std::string& t : model_.terminators)
if (reply.size() >= t.size() && reply.compare(reply.size() - t.size(), t.size(), t) == 0) {
reply.erase(reply.size() - t.size());
break;
}
return reply;
}
static std::string q(const std::string& s) {
return nlohmann::json(s).dump(-1, ' ', false, nlohmann::json::error_handler_t::replace);
}
std::string show(const ReplyMessage& m) {
std::string s = "content=" + q(m.content) + " reasoning=" + q(m.reasoning);
for (const ReplyCall& c : m.calls)
s += "\n call " + q(c.name) + " " + q(c.arguments) + (c.closed ? "" : " (open)");
return s;
}
std::string show(const legacy::Answer& a) {
std::string s = "content=" + q(a.content) + " reasoning=" + q(a.reasoning);
if (a.strict_failed) s += " [strict parse failed]";
if (a.lifted) s += " [" + std::to_string(a.lifted) + " lifted]";
for (const legacy::ToolCall& c : a.calls) s += "\n call " + q(c.name) + " " + q(c.arguments);
return s;
}
bool same(const ReplyMessage& a, const ReplyMessage& b) {
if (a.content != b.content || a.reasoning != b.reasoning || a.calls.size() != b.calls.size())
return false;
for (size_t i = 0; i < a.calls.size(); ++i)
if (a.calls[i].name != b.calls[i].name || a.calls[i].arguments != b.calls[i].arguments ||
a.calls[i].closed != b.calls[i].closed)
return false;
return true;
}
Verdict compare(const Bench& b, const std::string& text) {
Verdict v;
const legacy::Answer o = b.old_parse(text);
const ReplyMessage m = b.new_parse(text, &v.strict);
v.old_clean = !o.strict_failed && o.lifted == 0;
v.bare_lift = !o.strict_failed && o.lifted > 0;
const ChatFormat& f = b.format();
if (!f.call_open.empty()) {
size_t a = 0, e = f.call_open.size();
while (a < e && (unsigned char)f.call_open[a] <= ' ') ++a;
while (e > a && (unsigned char)f.call_open[e - 1] <= ' ') --e;
v.old_call_syntax = o.content.find(f.name_prefix) != std::string::npos ||
o.content.find(f.call_open.substr(a, e - a)) != std::string::npos;
}
v.same = o.content == m.content && o.reasoning == m.reasoning && o.calls.size() == m.calls.size();
for (size_t i = 0; v.same && i < o.calls.size(); ++i)
v.same = o.calls[i].name == m.calls[i].name && o.calls[i].arguments == m.calls[i].arguments;
if (!v.same) v.detail = " old: " + show(o) + "\n new: " + show(m);
return v;
}
std::string judge(const Verdict& v) {
if (v.strict) {
if (v.old_clean && !v.same) return "both read the reply within the grammar and disagree";
if (!v.old_clean && !v.bare_lift)
return "the new parser read within the grammar a reply the old grammar rejected";
return std::string();
}
if (v.old_clean && !v.old_call_syntax)
return "the new parser left the grammar on a reply the old grammar accepted";
return std::string();
}
std::string check_stream(const ReplyParser& p, const std::string& text,
const std::vector<size_t>& cuts, const ReplyMessage& expect) {
std::unique_ptr<ReplyStream> s = p.open();
ReplyMessage got;
std::vector<ReplyEvent> ev;
const size_t bound = p.hold_bound();
auto grew = [](const std::string& now, size_t before, const std::string& want) {
return now.size() <= want.size() &&
now.compare(before, std::string::npos, want, before, now.size() - before) == 0;
};
auto take = [&](const char* where) -> std::string {
for (const ReplyEvent& e : ev) {
switch (e.kind) {
case ReplyEvent::Reasoning: {
const size_t b = got.reasoning.size();
got.reasoning += e.text;
if (!grew(got.reasoning, b, expect.reasoning))
return std::string(where) + ": reasoning delta is not a prefix of the answer";
break;
}
case ReplyEvent::Content: {
const size_t b = got.content.size();
got.content += e.text;
if (!grew(got.content, b, expect.content))
return std::string(where) + ": content delta is not a prefix of the answer";
break;
}
case ReplyEvent::CallBegin:
if (e.call != got.calls.size() || e.call >= expect.calls.size() ||
expect.calls[e.call].name != e.text)
return std::string(where) + ": a call began that the answer does not have";
got.calls.push_back({ e.text, std::string(), false });
break;
case ReplyEvent::CallArgs: {
if (e.call >= got.calls.size()) return std::string(where) + ": arguments for no call";
std::string& a = got.calls[e.call].arguments;
const size_t b = a.size();
a += e.text;
if (!grew(a, b, expect.calls[e.call].arguments))
return std::string(where) + ": arguments delta is not a prefix of the answer";
break;
}
case ReplyEvent::CallEnd:
if (e.call >= got.calls.size() || !expect.calls[e.call].closed)
return std::string(where) + ": a call closed that the answer leaves open";
got.calls[e.call].closed = true;
break;
}
}
ev.clear();
return std::string();
};
size_t at = 0;
for (size_t c : cuts) {
if (c <= at || c > text.size()) continue;
s->feed(std::string_view(text).substr(at, c - at), &ev);
at = c;
std::string err = take("after a piece");
if (!err.empty()) return err + " (at byte " + std::to_string(at) + ")";
const ReplyHeld h = s->held();
if (h.delimiter > bound)
return "held " + std::to_string(h.delimiter) + " bytes of text, over the bound of " +
std::to_string(bound) + " (at byte " + std::to_string(at) + ")";
}
if (at < text.size()) s->feed(std::string_view(text).substr(at), &ev);
s->finish(&ev);
std::string err = take("at the end");
if (!err.empty()) return err;
if (!same(got, expect)) return "the deltas add up to\n " + show(got);
if (!same(s->message(), expect)) return "the message is\n " + show(s->message());
return std::string();
}
std::string sanitize(const std::string& s) { return utf8_sanitize(s); }
/* ================================================================== the corpora */
bool is_qwen(const Model& m) { return m.name != "minicpm5"; }
ojson call(const std::string& name, const ojson& args) {
return { { "type", "function" },
{ "function", { { "name", name }, { "arguments", args.dump() } } } };
}
ojson message(const std::string& reasoning, const std::string& content,
const std::vector<ojson>& calls) {
ojson m = { { "role", "assistant" }, { "content", content } };
if (!reasoning.empty()) m["reasoning_content"] = reasoning;
if (!calls.empty()) {
m["tool_calls"] = ojson::array();
for (size_t i = 0; i < calls.size(); ++i) {
ojson c = calls[i];
c["id"] = "call_" + std::to_string(i);
m["tool_calls"].push_back(c);
}
}
return m;
}
static const std::string kFile =
"def add(a, b):\n\n\t# sum\n return a + b \n\nclass X:\n s = \"<b>&amp;</b>\"\n";
std::vector<ojson> rendered_corpus() {
std::vector<ojson> v;
v.push_back(message("", "The tests pass now.", {}));
v.push_back(message("The user wants a summary.\nIt is short.", "It prints one.", {}));
v.push_back(message("I should look first.", "",
{ call("bash", { { "command", "ls -la /work" }, { "timeout", 30 } }) }));
v.push_back(message("", "Let me check the directory.",
{ call("bash", { { "command", "ls" } }) }));
v.push_back(message("Two things.", "", { call("read", { { "path", "/work/a.py" } }),
call("read", { { "path", "/work/b.py" },
{ "offset", 10 },
{ "limit", 40 } }) }));
{
std::vector<ojson> five;
for (int i = 0; i < 5; ++i)
five.push_back(call("bash", { { "command", "echo " + std::to_string(i) } }));
v.push_back(message("Five commands.", "Running them all.", five));
}
v.push_back(message("", "", { call("write", { { "path", "/work/a.py" }, { "content", kFile } }) }));
v.push_back(message("Editing.", "", { call("edit", { { "path", "/work/a.py" },
{ "edits", ojson::array({ { { "oldText", " return a + b" },
{ "newText", " return a + b + 1" } } }) } }) }));
v.push_back(message("", "", { call("todo_write", { { "todos", ojson::array({
{ { "content", "write the test" }, { "status", "completed" } },
{ { "content", "fix it" }, { "status", "in_progress" } } }) } }) }));
v.push_back(message("", "", { call("configure", { { "level", 1.5 },
{ "extra", { { "a", ojson::array({ 1, 2 }) },
{ "b", { { "c", nullptr } } } } },
{ "tags", ojson::array({ "x", "y" }) },
{ "mode", "fast" },
{ "label", "l" } }) }));
v.push_back(message("Unicode.", "Größe, 大小, 🚀.",
{ call("write", { { "path", "/work/中文.txt" },
{ "content", "こんにちは 🌍\nÀ la carte — «ok»\n" } }) }));
v.push_back(message("", "", { call("write", { { "path", "/work/x.xml" },
{ "content", "<param name=\"k\">v</param>\n</param\n</parameter\n</function>x" } }) }));
v.push_back(message("", "", { call("write", { { "path", "" }, { "content", "" } }) }));
v.push_back(message("", "", { call("ping", ojson::object()) }));
return v;
}
std::string qcall(const std::string& name,
const std::vector<std::pair<std::string, std::string>>& args) {
std::string s = "<tool_call>\n<function=" + name + ">\n";
for (const auto& a : args) s += "<parameter=" + a.first + ">\n" + a.second + "\n</parameter>\n";
return s + "</function>\n</tool_call>";
}
std::string mcall(const std::string& name,
const std::vector<std::pair<std::string, std::string>>& args) {
std::string s = "<function name=\"" + name + "\">";
for (const auto& a : args) s += "<param name=\"" + a.first + "\">" + a.second + "</param>";
return s + "</function>";
}
std::string C(const Model& m, const std::string& name,
const std::vector<std::pair<std::string, std::string>>& args) {
return is_qwen(m) ? qcall(name, args) : mcall(name, args);
}
std::vector<Adversarial> adversarial(const Model& m) {
const std::string T = "Thinking it over.\n</think>\n\n";
std::vector<Adversarial> v;
auto add = [&](const std::string& n, const std::string& t) { v.push_back({ n, t }); };
add("reasoning only, never closed", "Thinking and thinking");
add("reasoning only, closed", "Thinking.\n</think>\n\n");
add("content only", T + "The answer is 42.");
add("reasoning then a call", T + C(m, "bash", { { "command", "ls" } }));
add("content then a call", T + "Checking.\n" + C(m, "bash", { { "command", "ls" } }));
add("calls then trailing text", T + C(m, "bash", { { "command", "ls" } }) + "\nDone now.");
add("two calls", T + C(m, "bash", { { "command", "ls" } }) + "\n" +
C(m, "read", { { "path", "/a" } }));
add("two calls with a sentence between", T + C(m, "bash", { { "command", "ls" } }) +
"\nNow the file.\n" + C(m, "read", { { "path", "/a" } }));
{
std::string five = T;
for (int i = 0; i < 5; ++i) five += C(m, "bash", { { "command", "echo " + std::to_string(i) } }) + "\n";
add("five calls", five);
}
add("an integer", T + C(m, "read", { { "path", "/a" }, { "limit", "40" } }));
add("a number", T + C(m, "configure", { { "level", "-1.5e3" } }));
add("a boolean", T + C(m, "configure", { { "verbose", "true" } }));
add("a null", T + C(m, "configure", { { "nothing", "null" } }));
add("an object", T + C(m, "configure", { { "extra", "{\"a\": {\"b\": [1, {\"c\": \"d\"}]}}" } }));
add("an array", T + C(m, "configure", { { "tags", "[\"x\", \"y\"]" } }));
add("a Python-quoted array", T + C(m, "edit", { { "path", "/a" },
{ "edits", "[{'oldText': 'a', 'newText': 'b\\'s'}]" } }));
add("an integer with units", T + C(m, "bash", { { "command", "sleep" }, { "timeout", "30 seconds" } }));
add("JSON then a stray character", T + C(m, "configure", { { "extra", "{\"a\": 1}x" } }));
add("an unterminated JSON string", T + C(m, "configure", { { "extra", "\"abc" } }));
add("a number that is not one", T + C(m, "read", { { "path", "/a" }, { "limit", "01" } }));
add("unicode", T + "Größe 大小 🚀 " + C(m, "write", { { "path", "/中.txt" }, { "content", "こんにちは 🌍" } }));
add("CDATA with brackets and tags", T + C(m, "write", { { "path", "/a" },
{ "content", "<![CDATA[if (a[b[0]]) { x = \"]]\"; }\n <tag>\n indented\n]]>" } }));
add("CDATA holding almost a closer", T + C(m, "write", { { "path", "/a" }, { "content", "<![CDATA[a]]b]] >]]>" } }));
add("a value holding part of its closer", T + C(m, "write", { { "path", "/a" },
{ "content", "x </param y </parameter z </para" } }));
add("empty values", T + C(m, "write", { { "path", "" }, { "content", "" } }));
add("an undeclared argument", T + C(m, "read", { { "path", "/a" }, { "mode", "fast" } }));
add("only an undeclared argument", T + C(m, "read", { { "action", "read" } }));
add("arguments out of order", T + C(m, "write", { { "content", "x" }, { "path", "/a" } }));
add("a required argument missing", T + C(m, "write", { { "path", "/a" } }));
add("no arguments for a tool that needs one", T + C(m, "bash", {}));
add("an argument for a tool that takes none", T + C(m, "ping", { { "x", "1" } }));
add("a function that is not a tool", T + C(m, "which gcc cc clang make", {}));
add("unclosed think before a call", "I will list it.\n" + C(m, "bash", { { "command", "ls" } }));
add("a truncated reply inside a call", T + "Writing.\n" + C(m, "write", { { "path", "/a" }, { "content", "partial fi" } })
.substr(0, 40));
add("a truncated reply inside an argument name", T + (is_qwen(m) ? "<tool_call>\n<function=read>\n<parameter=pa"
: "<function name=\"read\"><param name=\"pa"));
add("a truncated reply inside a function name", T + (is_qwen(m) ? "<tool_call>\n<function=wri" : "<function name=\"wri"));
add("delimiter-like text in content", T + "Use `</think>`, `<tool_call>`, `<function=f>` and "
"`<function name=\"f\">` to call. </parameter> </param>");
add("a closing tag mentioned in reasoning", "The tag </thin is not </think>\n\nfine");
add("the call opener mentioned in reasoning",
std::string("I could write ") + (is_qwen(m) ? "<tool_call>\n" : "<function name=\"") +
" here.\n</think>\n\nNo.");
add("a second </think>", T + "Answer.\n</think>\nmore");
add("a turn terminator at the end", T + "Answer." + m.terminators[0]);
add("trailing spaces and newlines", T + "Answer. \n \n\n");
add("a call inside a sentence", T + "I will " + C(m, "bash", { { "command", "ls" } }) + " now.");
if (is_qwen(m)) {
add("the template's instructions echoed",
T + "<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\n"
"value_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for "
"the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n"
"</tool_call>");
add("a call without the newline after its opener",
T + "<tool_call><function=bash>\n<parameter=command>\nls\n</parameter>\n</function>\n</tool_call>");
add("a bare function without its wrapper",
T + "<function=bash>\n<parameter=command>\nls\n</parameter>\n</function>");
add("a function name without its newline",
T + "<tool_call>\n<function=bash><parameter=command>\nls\n</parameter>\n</function>\n</tool_call>");
add("a close without its newline",
T + "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</function></tool_call>");
add("two calls in one wrapper",
T + "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</function>\n"
"<function=bash>\n<parameter=command>\npwd\n</parameter>\n</function>\n</tool_call>");
add("a call with no closing wrapper",
T + "<tool_call>\n<function=bash>\n<parameter=command>\nls\n</parameter>\n</function>\n"
"<tool_call>\n<function=read>\n<parameter=path>\n/a\n</parameter>\n</function>\n</tool_call>");
add("an argument with no newline after its name",
T + "<tool_call>\n<function=bash>\n<parameter=command>ls</parameter>\n</function>\n</tool_call>");
} else {
add("the template's instructions echoed",
T + "<function name=\"function-name\"><param name=\"param-name\">param-value</param></function>");
add("the instruction's CDATA example echoed",
T + "<function name=\"write\"><param name=\"param-name\"><![CDATA[...multi-line value...]]></param></function>");
add("a value closed with the wrong tag",
T + "<function name=\"bash\"><param name=\"command\">ls\n</command></function>");
add("junk inside a call", T + "<function name=\"bash\"><param name=\"command\">ls</param>, "
"then<param name=\"timeout\">3</param></function>");
add("JSON arguments inside the tag", T + "<function name=\"bash\">{\"command\": \"ls\"}</function>");
}
return v;
}
std::vector<std::string> fragments(const Model& m) {
std::vector<std::string> f = {
"</think>\n\n", "<think>\n", "ls -la", "30", "-1.5e3", "[1,2]", "{\"a\":true}", "{'a': 1}",
"hello", "\n", " ", "<![CDATA[", "]]>", "]", "<", "</", "\"", "'", "\\", "{", "}", "true",
"null", "30 seconds", "中", "🚀", "x", "<|im_end|>", "</s>", "```json\n", "```",
};
const std::vector<std::string> q = {
"<tool_call>\n", "</tool_call>", "<function=bash>\n", "<function=read>\n",
"<function=ping>\n", "<function=configure>\n", "<function=zzz>\n", "</function>\n",
"<parameter=command>\n", "<parameter=timeout>\n", "<parameter=path>\n",
"<parameter=extra>\n", "<parameter=level>\n", "<parameter=xx>\n", "</parameter>\n",
"</parameter", "<tool_call>", "<function=", ">\n",
};
const std::vector<std::string> mc = {
"<function name=\"bash\">", "<function name=\"read\">", "<function name=\"ping\">",
"<function name=\"configure\">", "<function name=\"zz\">", "</function>",
"<param name=\"command\">", "<param name=\"timeout\">", "<param name=\"path\">",
"<param name=\"extra\">", "<param name=\"xx\">", "</param>", "</param", "<function name=\"",
"\">",
};
for (const std::string& s : is_qwen(m) ? q : mc) f.push_back(s);
return f;
}
std::string mutate(std::mt19937& rng, std::string s, const std::vector<std::string>& frag) {
const int n = 1 + (int)(rng() % 4);
for (int k = 0; k < n; ++k) {
const size_t at = s.empty() ? 0 : rng() % (s.size() + 1);
switch (rng() % 4) {
case 0: s.insert(at, frag[rng() % frag.size()]); break;
case 1: if (at < s.size()) s.erase(at, 1 + rng() % 8); break;
case 2: if (at < s.size()) s[at] = (char)(rng() & 0xFF); break;
default: s.insert(at, 1, (char)(rng() & 0xFF)); break;
}
}
return s;
}
std::string long_reply(const Model& m, size_t target) {
std::string think, file, prose;
while (think.size() < target / 4) think += "Considering the failing assertion in test_add again. ";
while (file.size() < target / 2) file += " x = compute(a, b) # <tag> & \"quoted\" ]] \n";
while (prose.size() < target / 4) prose += "The change keeps the interface and fixes the sum. ";
return think + "\n</think>\n\n" + prose + "\n" +
C(m, "write", { { "path", "/work/big.py" }, { "content", file } });
}
} /* namespace chatdiff */
} /* namespace rad */
+150
View File
@@ -0,0 +1,150 @@
/* chatdiff.h -- the streaming reply parser beside the legacy parser, on the same request.
*
* Shared by tests/chatparse_test.cpp and tools/rad_chatparse.cpp. A Bench holds one model's chat
* template, its reply format and, for one rendered request, both parsers: the legacy path
* (toolparse_legacy.h, the `old` side) and the streaming parser (core/text/chatparse.h, the `new`
* side). compare() says whether they agree on a reply and, when they do not, which side left its
* grammar; check_stream() feeds a reply to the streaming parser in pieces and checks the streaming
* contract on every piece.
*/
#pragma once
#include "text/chat.h"
#include "text/chatfmt.h"
#include "text/chatparse.h"
#include "toolparse_legacy.h"
#include <nlohmann/json.hpp>
#include <memory>
#include <random>
#include <string>
#include <vector>
namespace rad {
namespace chatdiff {
using ojson = nlohmann::ordered_json;
/* A model: where its template is and how its vocabulary spells the tokens a template reads. */
struct Model {
std::string name;
std::string dir; /* under the fixture root */
std::string bos, eos;
std::vector<std::string> terminators; /* its end-of-generation spellings */
};
const std::vector<Model>& models();
/* How a request is rendered. */
struct ChatRequest {
bool tools = true;
bool parallel = true;
bool thinking = true;
bool reasoning = true; /* reasoning_format "auto"; false is "none" */
std::string schema; /* a response format's schema, "" for none */
};
std::string describe(const ChatRequest& r);
/* An agent-shaped tool set, with every argument type the formats distinguish. */
const ojson& agent_tools();
class Bench {
public:
/* RAD_OK, or a status with *why. `jinja` is the template's text. */
int load(const Model& m, const std::string& jinja, std::string* why);
int bind(const ChatRequest& rq, const ojson& tools, std::string* why);
const Model& model() const { return model_; }
const ChatFormat& format() const { return fmt_; }
const ChatPrompt& prompt() const { return prompt_; }
const ReplyParser& parser() const { return *parser_; }
std::shared_ptr<const ReplyParser> parser_ptr() const { return parser_; }
const legacy::ToolParser& old_parser() const { return *old_; }
const ChatRequest& request() const { return req_; }
const ChatTemplate& tmpl() const { return *tmpl_; }
legacy::Answer old_parse(const std::string& text, bool partial = false) const;
ReplyMessage new_parse(const std::string& text, bool* strict = nullptr) const;
/* The reply as the template writes an assistant turn -- which is exactly what the model is
* trained to produce -- without the turn terminator the decoder would not render. "" when the
* template does not render the turn as a continuation of the generation prompt. */
std::string render_reply(const ojson& assistant) const;
private:
Model model_;
std::string jinja_;
std::shared_ptr<ChatTemplate> tmpl_;
ChatFormat fmt_;
std::shared_ptr<const ReplyFormat> rf_;
ChatRequest req_;
ojson tools_;
ChatPrompt prompt_;
std::unique_ptr<legacy::ToolParser> old_;
std::shared_ptr<const ReplyParser> parser_;
};
struct Verdict {
bool same = false; /* the two answers are identical */
bool strict = false; /* the streaming parser read the reply within the grammar */
bool old_clean = false; /* the legacy strict parse matched and nothing was lifted */
bool bare_lift = false; /* the legacy path lifted a call written without the call opener */
/* The legacy answer's content still carries a wrapped format's call syntax -- a call written
* without its wrapper, which the legacy lifter takes only when nothing else in the reply
* parses as a call, and which the streaming parser always reads as one. */
bool old_call_syntax = false;
std::string detail; /* both answers, when they differ */
};
Verdict compare(const Bench& b, const std::string& text);
/* Whether a verdict is one the streaming parser is allowed: identical where both read the reply
* within the grammar, and a documented difference otherwise. "" or the reason it is not. */
std::string judge(const Verdict& v);
/* Feed `text` to a fresh stream cut at `cuts` (ascending offsets), checking on every piece that
* what has been emitted is a prefix of `expect` and that the held bytes stay under the bound, and
* at the end that the concatenated deltas and the message both equal `expect`. "" or the first
* violation. */
std::string check_stream(const ReplyParser& p, const std::string& text,
const std::vector<size_t>& cuts, const ReplyMessage& expect);
std::string show(const ReplyMessage& m);
std::string show(const legacy::Answer& a);
bool same(const ReplyMessage& a, const ReplyMessage& b);
/* Replace every byte that is not part of well-formed UTF-8 with U+FFFD, as the decoder does
* before any reply reaches a parser. */
std::string sanitize(const std::string& s);
/* ================================================================== the corpora */
bool is_qwen(const Model& m);
/* A call, and an assistant message carrying calls, OpenAI-shaped. */
ojson call(const std::string& name, const ojson& args);
ojson message(const std::string& reasoning, const std::string& content,
const std::vector<ojson>& calls);
/* Assistant messages that, rendered through a model's template, are the replies the model is
* trained to write: content only, reasoning, one to five calls, every argument type, unicode, and
* values holding the format's own punctuation. */
std::vector<ojson> rendered_corpus();
/* Replies written by hand in a model's own spelling: the shapes models actually write when they
* leave their format, and the ones a streaming parser is easiest to get wrong. */
struct Adversarial { std::string name, text; };
std::vector<Adversarial> adversarial(const Model& m);
/* One call in a model's spelling. */
std::string C(const Model& m, const std::string& name,
const std::vector<std::pair<std::string, std::string>>& args);
/* The pieces random replies are assembled from, and a random edit of a reply. */
std::vector<std::string> fragments(const Model& m);
std::string mutate(std::mt19937& rng, std::string s, const std::vector<std::string>& frag);
/* About `target` bytes of reasoning, prose and one call writing a file. */
std::string long_reply(const Model& m, size_t target);
} /* namespace chatdiff */
} /* namespace rad */
+377
View File
@@ -0,0 +1,377 @@
#include "toolparse_legacy.h"
#include "text/chat.h"
#include "llama/common/chat.h"
#include "llama/common/peg-parser.h"
#include <algorithm>
#include <atomic>
#include <cstdio>
#include <cstring>
#include <nlohmann/json.hpp>
namespace rad {
namespace legacy {
/* ================================================================== the PEG parser */
struct ToolParser::Impl {
common_chat_parser_params params;
bool ready = false;
};
ToolParser::ToolParser() : impl_(std::make_unique<Impl>()) {}
ToolParser::~ToolParser() = default;
bool ToolParser::ready() const { return impl_ && impl_->ready; }
int ToolParser::init(const ChatPrompt& p, const std::string& reasoning_format,
bool parse_tool_calls) {
impl_->ready = false;
impl_->params = common_chat_parser_params{};
impl_->params.format = (common_chat_format)p.format;
impl_->params.generation_prompt = p.generation_prompt;
impl_->params.parse_tool_calls = parse_tool_calls;
impl_->params.reasoning_format = common_reasoning_format_from_name(reasoning_format);
impl_->params.reasoning_in_content =
impl_->params.reasoning_format == COMMON_REASONING_FORMAT_DEEPSEEK_LEGACY;
if (!p.parser.empty()) {
try {
impl_->params.parser.load(p.parser);
} catch (const std::exception&) {
return RAD_E_FORMAT;
}
}
impl_->ready = true;
return RAD_OK;
}
int ToolParser::parse(const std::string& text, bool is_partial, ParsedReply* out) const {
if (!ready()) return RAD_E_STATE;
if (!out) return RAD_E_INVAL;
out->content.clear();
out->reasoning_content.clear();
out->tool_calls.clear();
common_chat_msg msg;
try {
if (!impl_->params.parser.empty())
msg = common_chat_peg_parse(impl_->params.parser, text, is_partial, impl_->params);
else
msg = common_chat_parse(text, is_partial, impl_->params);
} catch (const std::exception&) {
return RAD_E_FORMAT;
}
out->content = std::move(msg.content);
out->reasoning_content = std::move(msg.reasoning_content);
for (common_chat_tool_call& c : msg.tool_calls)
out->tool_calls.push_back({ std::move(c.name), std::move(c.arguments), std::move(c.id) });
return RAD_OK;
}
/* ================================================================== the by-hand lifter
*
* Two spellings, whatever the model's own format:
*
* attr <function name="N"><param name="K">V</param></function>
* eq <tool_call><function=N><parameter=K>V</parameter></function></tool_call>
*/
namespace {
struct XmlCallSyntax {
const char* wrap_open;
const char* wrap_close;
const char* fn_open;
const char* fn_name_end;
const char* fn_close;
const char* arg_open;
const char* arg_name_end;
const char* arg_close;
bool trim_value;
};
const XmlCallSyntax kAttr = { "", "", "<function name=\"", "\">", "</function>",
"<param name=\"", "\">", "</param>", false };
const XmlCallSyntax kEq = { "<tool_call>", "</tool_call>", "<function=", ">", "</function>",
"<parameter=", ">", "</parameter>", true };
size_t skip_ws(const std::string& s, size_t p) {
while (p < s.size() && (unsigned char)s[p] <= ' ') ++p;
return p;
}
std::string trimmed(const std::string& v) {
size_t a = 0, b = v.size();
while (a < b && (unsigned char)v[a] <= ' ') ++a;
while (b > a && (unsigned char)v[b - 1] <= ' ') --b;
return v.substr(a, b - a);
}
size_t read_call(const std::string& s, size_t f, const XmlCallSyntax& x,
std::string* name, nlohmann::ordered_json* args) {
const std::string fn_open(x.fn_open), fn_name_end(x.fn_name_end), fn_close(x.fn_close);
const std::string arg_open(x.arg_open), arg_name_end(x.arg_name_end), arg_close(x.arg_close);
if (s.compare(f, fn_open.size(), fn_open) != 0) return std::string::npos;
const size_t ns = f + fn_open.size();
const size_t ne = s.find(fn_name_end, ns);
if (ne == std::string::npos) return std::string::npos;
*name = s.substr(ns, ne - ns);
if (name->empty() || name->find('<') != std::string::npos) return std::string::npos;
*args = nlohmann::ordered_json::object();
size_t p = ne + fn_name_end.size();
while (true) {
p = skip_ws(s, p);
if (s.compare(p, fn_close.size(), fn_close) == 0) return p + fn_close.size();
if (s.compare(p, arg_open.size(), arg_open) != 0) return std::string::npos;
const size_t ks = p + arg_open.size();
const size_t ke = s.find(arg_name_end, ks);
if (ke == std::string::npos) return std::string::npos;
const std::string key = s.substr(ks, ke - ks);
if (key.empty() || key.find('<') != std::string::npos) return std::string::npos;
size_t vs = ke + arg_name_end.size();
std::string val;
if (s.compare(vs, 9, "<![CDATA[") == 0) {
const size_t ce = s.find("]]>", vs + 9);
if (ce == std::string::npos) return std::string::npos;
val = s.substr(vs + 9, ce - (vs + 9));
p = ce + 3;
if (s.compare(p, arg_close.size(), arg_close) != 0) return std::string::npos;
p += arg_close.size();
} else {
const size_t bound = std::min(s.find(arg_open, vs), s.find(fn_close, vs));
const size_t ve = s.find(arg_close, vs);
if (ve != std::string::npos && (bound == std::string::npos || ve <= bound)) {
val = s.substr(vs, ve - vs);
p = ve + arg_close.size();
} else if (bound != std::string::npos) {
const size_t lt = bound > vs ? s.rfind("</", bound - 1) : std::string::npos;
if (lt != std::string::npos && lt >= vs) {
const size_t gt = s.find('>', lt);
if (gt == std::string::npos || gt >= bound) return std::string::npos;
val = s.substr(vs, lt - vs);
p = gt + 1;
} else {
val = s.substr(vs, bound - vs);
p = bound;
}
} else {
return std::string::npos;
}
}
(*args)[key] = x.trim_value ? trimmed(val) : val;
}
}
std::string mint_call_id() {
static std::atomic<uint64_t> seq{0};
char buf[40];
std::snprintf(buf, sizeof buf, "call_%023llx",
(unsigned long long)seq.fetch_add(1, std::memory_order_relaxed));
return std::string(buf);
}
} /* namespace */
size_t toolparse_find_call_open(const std::string& s) {
static const char* const kMarks[] = { "<tool_call>", "<function name=\"", "<function=" };
size_t at = std::string::npos;
for (const char* m : kMarks) at = std::min(at, s.find(m));
if (at != std::string::npos) return at;
for (const char* m : kMarks) {
const size_t len = std::strlen(m);
for (size_t k = std::min(len - 1, s.size()); k >= 1; --k) {
if (s.compare(s.size() - k, k, m, k) == 0) {
at = std::min(at, s.size() - k);
break;
}
}
}
return at;
}
size_t toolparse_lift_xml_calls(std::string& s, std::vector<ToolCall>& out) {
std::string kept;
size_t cursor = 0, scan = 0, found = 0;
while (true) {
const size_t rel = toolparse_find_call_open(s.substr(scan));
const size_t at = rel == std::string::npos ? std::string::npos : scan + rel;
if (at == std::string::npos) break;
const XmlCallSyntax* x = nullptr;
size_t f = at, wrap = std::string::npos;
if (s.compare(at, strlen(kEq.wrap_open), kEq.wrap_open) == 0) {
wrap = at;
f = skip_ws(s, at + strlen(kEq.wrap_open));
x = &kEq;
} else if (s.compare(at, strlen(kAttr.fn_open), kAttr.fn_open) == 0) {
x = &kAttr;
} else if (s.compare(at, strlen(kEq.fn_open), kEq.fn_open) == 0) {
x = &kEq;
}
if (!x) { scan = at + 1; continue; }
std::string name;
nlohmann::ordered_json args;
size_t end = read_call(s, f, *x, &name, &args);
if (end == std::string::npos) { scan = at + 1; continue; }
if (wrap != std::string::npos) {
const size_t w = skip_ws(s, end);
if (s.compare(w, strlen(kEq.wrap_close), kEq.wrap_close) != 0) { scan = at + 1; continue; }
end = w + strlen(kEq.wrap_close);
}
const size_t span_start = (wrap != std::string::npos) ? wrap : f;
kept.append(s, cursor, span_start - cursor);
ToolCall tc;
tc.id = mint_call_id();
tc.name = name;
tc.arguments = args.dump();
out.push_back(std::move(tc));
cursor = end;
scan = end;
++found;
}
if (found == 0) return 0;
kept.append(s, cursor, std::string::npos);
while (!kept.empty() && (unsigned char)kept.back() <= ' ') kept.pop_back();
s = std::move(kept);
return found;
}
/* ================================================================== the bridge */
static void strip_terminator(std::string& s, const std::vector<std::string>& terms) {
while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back();
for (const std::string& t : terms) {
if (!t.empty() && s.size() >= t.size() &&
s.compare(s.size() - t.size(), t.size(), t) == 0) {
s.erase(s.size() - t.size());
return;
}
}
}
Answer legacy_parse(const ToolParser& tp, const std::string& text, bool is_partial,
bool want_calls, const std::vector<std::string>& terminators) {
Answer a;
ParsedReply r;
if (tp.parse(text, is_partial, &r) < 0) {
a.strict_failed = true;
a.content = text;
} else {
a.content = std::move(r.content);
a.reasoning = std::move(r.reasoning_content);
a.calls = std::move(r.tool_calls);
}
strip_terminator(a.content, terminators);
if (!want_calls || a.content.empty()) return a;
const size_t at = toolparse_find_call_open(a.content);
if (at == std::string::npos) return a;
if (is_partial) { a.content.resize(at); return a; }
if (!a.calls.empty()) return a;
a.lifted = toolparse_lift_xml_calls(a.content, a.calls);
return a;
}
/* ================================================================== the streaming diff */
namespace {
size_t utf8_cut(const std::string& s) {
size_t n = s.size();
size_t k = n, back = 0;
while (k > 0 && back < 4) {
const unsigned char c = (unsigned char)s[k - 1];
if ((c & 0xC0) == 0x80) { --k; ++back; continue; }
size_t need = 1;
if ((c & 0x80) == 0x00) need = 1;
else if ((c & 0xE0) == 0xC0) need = 2;
else if ((c & 0xF0) == 0xE0) need = 3;
else if ((c & 0xF8) == 0xF0) need = 4;
else return n;
return n - (k - 1) >= need ? n : k - 1;
}
return n;
}
bool extends(const std::string& sent, const std::string& cand) {
return cand.size() >= sent.size() && cand.compare(0, sent.size(), sent) == 0;
}
std::string chunk(const nlohmann::ordered_json& delta) {
nlohmann::ordered_json ch;
ch["index"] = 0;
ch["delta"] = delta;
ch["finish_reason"] = nullptr;
nlohmann::ordered_json o;
o["id"] = "chatcmpl-legacy";
o["object"] = "chat.completion.chunk";
o["created"] = 0;
o["model"] = "legacy";
o["choices"] = nlohmann::ordered_json::array({ ch });
return "data: " + o.dump(-1, ' ', false, nlohmann::ordered_json::error_handler_t::replace) +
"\n\n";
}
} /* namespace */
size_t LegacyDeltaStream::push(const std::string& full_text, bool is_final) {
Answer p = legacy_parse(tp_, full_text, !is_final, want_calls_, terms_);
size_t out = 0;
if (p.reasoning.size() > reasoning_.size() && extends(reasoning_, p.reasoning)) {
const size_t safe = is_final ? p.reasoning.size() : utf8_cut(p.reasoning);
if (safe > reasoning_.size()) {
nlohmann::ordered_json d;
d["reasoning_content"] = p.reasoning.substr(reasoning_.size(), safe - reasoning_.size());
out += chunk(d).size();
reasoning_ = p.reasoning.substr(0, safe);
}
}
if (p.content.size() > content_.size() && extends(content_, p.content)) {
const size_t safe = is_final ? p.content.size() : utf8_cut(p.content);
if (safe > content_.size()) {
nlohmann::ordered_json d;
d["content"] = p.content.substr(content_.size(), safe - content_.size());
out += chunk(d).size();
content_ = p.content.substr(0, safe);
}
}
for (size_t i = 0; i < p.calls.size(); ++i) {
const ToolCall& tc = p.calls[i];
if (tc.name.empty()) continue;
if (names_.size() <= i) {
names_.resize(i + 1);
args_.resize(i + 1);
names_[i] = tc.name;
nlohmann::ordered_json f;
f["name"] = tc.name;
f["arguments"] = "";
nlohmann::ordered_json e;
e["index"] = (int64_t)i;
e["function"] = f;
nlohmann::ordered_json d;
d["tool_calls"] = nlohmann::ordered_json::array({ e });
out += chunk(d).size();
}
if (!extends(args_[i], tc.arguments)) continue;
const size_t safe = is_final ? tc.arguments.size() : utf8_cut(tc.arguments);
if (safe <= args_[i].size()) continue;
nlohmann::ordered_json f;
f["arguments"] = tc.arguments.substr(args_[i].size(), safe - args_[i].size());
nlohmann::ordered_json e;
e["index"] = (int64_t)i;
e["function"] = f;
nlohmann::ordered_json d;
d["tool_calls"] = nlohmann::ordered_json::array({ e });
out += chunk(d).size();
args_[i] = tc.arguments.substr(0, safe);
}
return out;
}
} /* namespace legacy */
} /* namespace rad */
+97
View File
@@ -0,0 +1,97 @@
/* toolparse_legacy.h -- a whole-reply parser built on llama.cpp's PEG auto-parser, kept as the
* ORACLE the differential tests compare the streaming parser (core/text/chatparse.h) against. It
* is test code: it is built into the test binaries and the acceptance tool, never into the engine.
*
* It is the whole legacy path, layer for layer, because its answer is what all of them produce
* together:
*
* * ToolParser -- llama.cpp's PEG parser, generated per request by the vendored auto-parser from
* the chat template (vendor/llama/common/chat-auto-parser*.cpp) and run over the WHOLE reply;
* * legacy_parse -- the bridge's reading of that: a turn terminator trimmed off the content,
* and, when the strict parse produced no call but the content still carries call syntax,
* calls lifted out of the text by hand;
* * LegacyDeltaStream -- a streaming diff that re-parses the accumulated reply on every chunk and
* sends what has grown.
*/
#pragma once
#include "rad_internal.h"
#include <memory>
#include <string>
#include <vector>
namespace rad {
struct ChatPrompt;
namespace legacy {
struct ToolCall {
std::string name;
std::string arguments;
std::string id;
};
struct ParsedReply {
std::string content;
std::string reasoning_content;
std::vector<ToolCall> tool_calls;
};
/* The by-hand lifter: `<function name="N"><param name="K">V</param></function>` and
* `<tool_call><function=N><parameter=K>V</parameter></function></tool_call>` spans read out of
* `text` whatever the model's format, appended to `out` and removed. */
size_t toolparse_lift_xml_calls(std::string& text, std::vector<ToolCall>& out);
/* The earliest byte of `text` that could begin a call in either spelling, or npos. */
size_t toolparse_find_call_open(const std::string& text);
/* The vendored PEG parser for one rendered request. */
class ToolParser {
public:
ToolParser();
~ToolParser();
int init(const ChatPrompt& p, const std::string& reasoning_format = "auto",
bool parse_tool_calls = true);
/* RAD_OK, or RAD_E_FORMAT when the reply does not match the format at all. */
int parse(const std::string& text, bool is_partial, ParsedReply* out) const;
bool ready() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
/* What the legacy path answers for a reply, and which of its layers produced the answer. */
struct Answer {
std::string content, reasoning;
std::vector<ToolCall> calls;
bool strict_failed = false; /* the PEG parse failed; the whole reply became content */
size_t lifted = 0; /* calls the by-hand lifter took out of the content */
};
/* The bridge's reading of a reply: the PEG parse, the terminator trim and, for a request that
* offered tools, the lifter. `is_partial` is the streaming path's question. */
Answer legacy_parse(const ToolParser& tp, const std::string& text, bool is_partial,
bool want_calls, const std::vector<std::string>& terminators);
/* The legacy streaming diff over the accumulated text: returns how many bytes of deltas it sends,
* and fills the concatenation of what it sent. */
class LegacyDeltaStream {
public:
LegacyDeltaStream(const ToolParser& tp, bool want_calls, std::vector<std::string> terminators)
: tp_(tp), want_calls_(want_calls), terms_(std::move(terminators)) {}
size_t push(const std::string& full_text, bool is_final);
const std::string& content() const { return content_; }
const std::string& reasoning() const { return reasoning_; }
const std::vector<std::string>& arguments() const { return args_; }
const std::vector<std::string>& names() const { return names_; }
private:
const ToolParser& tp_;
bool want_calls_;
std::vector<std::string> terms_;
std::string content_, reasoning_;
std::vector<std::string> names_, args_;
};
} /* namespace legacy */
} /* namespace rad */