radiance 2.0.0

Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an
int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block
FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such
weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5,
Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0
serves all of them.

Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new
Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill
reworked, and a reworked adaptive draft window.

Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its
configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool
in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server,
each accelerator's memory by model, model states over time.

Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by
AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests
keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410);
eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d
large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi
(#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon
(#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and
multi-model serving as asked for in #367 and #109.

Plugin ABI 39: out-of-tree plugins need to be rebuilt.

Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
Deadcode committed 2026-11-14 22:32:28 +01:00
1 parent b4c04b6042
commit ddcb9c69bb
696 files changed
+120770 -56596

No files matched your search

+3 -3
View File
@@ -5,13 +5,13 @@
#include "common.h"
#include "json-schema-to-grammar.h"
#include "log.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include "peg-parser.h"
#include <stdexcept>
#include <string>
using json = nlohmann::ordered_json;
using json = rad::Json;
// Helper to iterate over tools/functions
static void foreach_function(const json & tools, const std::function<void(const json &)> & fn) {
@@ -44,7 +44,7 @@ common_chat_params peg_generator::generate_parser(const common_chat_template &
// Create the result structure
common_chat_params data;
data.prompt = common_chat_template_direct_apply(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_with_rendered(tmpl, inputs, data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.preserved_tokens = autoparser.preserved_tokens;
+2 -2
View File
@@ -4,13 +4,13 @@
#include "chat-peg-parser.h"
#include "chat.h"
#include "log.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include "peg-parser.h"
#include <cctype>
#include <numeric>
using json = nlohmann::ordered_json;
using json = rad::Json;
std::string trim_whitespace(const std::string & str) {
size_t start = 0;
+2 -2
View File
@@ -4,7 +4,7 @@
#include "common.h"
#include "jinja/caps.h"
#include "peg-parser.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include <chrono>
#include <optional>
@@ -12,7 +12,7 @@
#include <utility>
#include <vector>
using json = nlohmann::ordered_json;
using json = rad::Json;
class common_chat_peg_builder;
+4 -3
View File
@@ -4,11 +4,12 @@
#include "chat.h"
#include "common.h"
#include "log.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include "peg-parser.h"
#include <algorithm>
#include <cctype>
#include <numeric>
#include <ostream>
#include <sstream>
@@ -17,7 +18,7 @@
#define ANSI_ORANGE "\033[1m\x1b[38;5;214m"
#define ANSI_RED "\033[1m\x1b[38;5;196m"
using json = nlohmann::ordered_json;
using json = rad::Json;
namespace autoparser {
@@ -896,7 +897,7 @@ void analyze_tools::analyze_tool_call_format_json_native(const std::string & cle
int json_end = clean_haystack.find_last_of('}');
std::string cut = clean_haystack.substr(json_start, json_end - json_start + 1);
json call_struct = json::parse(cut);
auto register_field = [&](const std::string & prefix, const nlohmann::detail::iteration_proxy_value<json::iterator> & subel) {
auto register_field = [&](const std::string & prefix, const auto & subel) {
if (subel.value().is_string() && std::string(subel.value()).find("call0000") != std::string::npos) {
format.id_field = !prefix.empty() ? prefix + "." + subel.key() : subel.key();
} else if (subel.value().is_string() && std::string(subel.value()) == fun_name_needle) {
+2 -2
View File
@@ -4,9 +4,9 @@
#include "ggml.h"
#include "peg-parser.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
using ordered_json = nlohmann::ordered_json;
using ordered_json = rad::Json;
static std::string_view trim_trailing_space(std::string_view sv, int max = -1) {
int count = 0;
+6 -6
View File
@@ -111,7 +111,7 @@ class common_chat_peg_builder : public common_peg_parser_builder {
// parameters_order: order in which JSON fields should be parsed
common_peg_parser standard_json_tools(const std::string & section_start,
const std::string & section_end,
const nlohmann::ordered_json & tools,
const rad::Json & tools,
bool parallel_tool_calls,
bool force_tool_calls,
const std::string & name_key = "",
@@ -125,30 +125,30 @@ class common_chat_peg_builder : public common_peg_parser_builder {
// Legacy-compatible helper for building XML/tagged style tool calls
// Used by tests and manual parsers
common_peg_parser standard_constructed_tools(const std::map<std::string, std::string> & markers,
const nlohmann::ordered_json & tools,
const rad::Json & tools,
bool parallel_tool_calls,
bool force_tool_calls);
// Helper for Python-style function call format: name(arg1="value1", arg2=123)
// Used by LFM2 and similar templates
common_peg_parser python_style_tool_calls(const nlohmann::ordered_json & tools,
common_peg_parser python_style_tool_calls(const rad::Json & tools,
bool parallel_tool_calls);
private:
// Implementation helpers for standard_json_tools — one per JSON tool call layout mode
common_peg_parser build_json_tools_function_is_key(const nlohmann::ordered_json & tools,
common_peg_parser build_json_tools_function_is_key(const rad::Json & tools,
const std::string & args_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key);
common_peg_parser build_json_tools_nested_keys(const nlohmann::ordered_json & tools,
common_peg_parser build_json_tools_nested_keys(const rad::Json & tools,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
const std::string & gen_call_id_key);
common_peg_parser build_json_tools_flat_keys(const nlohmann::ordered_json & tools,
common_peg_parser build_json_tools_flat_keys(const rad::Json & tools,
const std::string & effective_name_key,
const std::string & effective_args_key,
const std::string & call_id_key,
+209 -85
View File
@@ -13,15 +13,18 @@
#include "jinja/caps.h"
#include "peg-parser.h"
#include "nlohmann/json.hpp"
#include "util/json.h"
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <exception>
#include <functional>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <optional>
#include <sstream>
@@ -30,7 +33,20 @@
#include <utility>
#include <vector>
using json = nlohmann::ordered_json;
using json = rad::Json;
bool common_chat_tool_call::operator==(const common_chat_tool_call & other) const {
if (name != other.name || id != other.id) {
return false;
}
if (arguments_json || other.arguments_json) {
// Compare on the parsed form; dumping here is a diff/error path, not a render path.
const std::string a = arguments_json ? arguments_json->dump() : arguments;
const std::string b = other.arguments_json ? other.arguments_json->dump() : other.arguments;
return a == b;
}
return arguments == other.arguments;
}
static std::string format_time(const std::chrono::system_clock::time_point & now, const std::string & format) {
auto time = std::chrono::system_clock::to_time_t(now);
@@ -164,7 +180,7 @@ json common_chat_msg::to_json_oaicompat(bool concat_typed_text) const {
text += part.text;
}
jmsg["content"] = text;
jmsg["content"] = std::move(text);
} else {
auto & parts = jmsg["content"] = json::array();
for (const auto & part : content_parts) {
@@ -194,7 +210,8 @@ json common_chat_msg::to_json_oaicompat(bool concat_typed_text) const {
{"type", "function"},
{"function", {
{"name", tool_call.name},
{"arguments", json(tool_call.arguments)},
{"arguments", tool_call.arguments_json ? *tool_call.arguments_json
: json(tool_call.arguments)},
}},
};
if (!tool_call.id.empty()) {
@@ -204,7 +221,7 @@ json common_chat_msg::to_json_oaicompat(bool concat_typed_text) const {
// We only generate a random id for the ones that don't generate one by themselves
// (they also won't get to see it as their template likely doesn't use it, so it's all for the client)
// {"id", tc.id.empty() ? gen_tool_call_id() : tc.id},
jtool_calls.push_back(tc);
jtool_calls.push_back(std::move(tc));
}
}
@@ -379,7 +396,7 @@ std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const json & messa
common_chat_msg_content_part msg_part;
msg_part.type = type;
msg_part.text = part.at("text");
msg.content_parts.push_back(msg_part);
msg.content_parts.push_back(std::move(msg_part));
}
} else if (!content.is_null()) {
throw std::invalid_argument("Invalid 'content' type: expected string or array, got " +
@@ -408,13 +425,15 @@ std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const json & messa
const auto & args = fc.at("arguments");
if (args.is_string()) {
tc.arguments = args;
} else if (args.is_object() || args.is_array()) {
tc.arguments_json = std::make_shared<const json>(args);
} else {
tc.arguments = args.dump();
}
if (tool_call.contains("id")) {
tc.id = tool_call.at("id");
}
msg.tool_calls.push_back(tc);
msg.tool_calls.push_back(std::move(tc));
}
}
if (!has_content && !has_tool_calls) {
@@ -432,7 +451,7 @@ std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const json & messa
msg.tool_call_id = message.at("tool_call_id");
}
msgs.push_back(msg);
msgs.push_back(std::move(msg));
}
} catch (const std::exception & e) {
// @ngxson : disable otherwise it's bloating the API response
@@ -455,21 +474,22 @@ static json render_message_to_json(const std::vector<common_chat_msg> & msgs, co
for (const auto & msg : msgs) {
if (only_string_accepted) {
json jmsg = msg.to_json_oaicompat(/* concat_typed_text= */ true);
messages.push_back(jmsg);
messages.push_back(std::move(jmsg));
} else if (only_typed_accepted) {
json jmsg = msg.to_json_oaicompat(/* concat_typed_text= */ false);
if (jmsg.at("content").is_string()) {
std::string text = std::move(jmsg.at("content").get_ref<std::string &>());
jmsg["content"] = json::array({
json{
{"type", "text"},
{"text", jmsg.at("content").get<std::string>()},
{"text", std::move(text)},
}
});
}
messages.push_back(jmsg);
messages.push_back(std::move(jmsg));
} else {
json jmsg = msg.to_json_oaicompat(/* concat_typed_text= */ false);
messages.push_back(jmsg);
messages.push_back(std::move(jmsg));
}
}
return messages;
@@ -537,7 +557,7 @@ std::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const json & too
return result;
}
common_chat_continuation common_chat_continuation_parse(const nlohmann::ordered_json & value) {
common_chat_continuation common_chat_continuation_parse(const rad::Json & value) {
if (value.is_boolean() && value.get<bool>()) {
return COMMON_CHAT_CONTINUATION_AUTO;
}
@@ -863,39 +883,41 @@ static std::string common_chat_template_direct_apply_impl(
const std::optional<json> & additional_context = std::nullopt) {
jinja::context ctx(tmpl.source());
nlohmann::ordered_json inp = nlohmann::ordered_json{
{"messages", messages_override.has_value() ? *messages_override : inputs.messages},
{"bos_token", tmpl.bos_token()},
{"eos_token", tmpl.eos_token()},
{"enable_thinking", inputs.enable_thinking},
// Set the globals straight from the JSON values already held, in the same order (and so
// with the same overwrites) as the intermediate object this used to build first: copying
// the messages and tools DOMs into that object just to convert them back out was a deep
// copy of the whole conversation per render.
auto set_json = [&](const std::string & k, const json & v) {
jinja::global_set_from_json(ctx, k, v, inputs.mark_input);
};
set_json("messages", messages_override.has_value() ? *messages_override : inputs.messages);
set_json("bos_token", json(tmpl.bos_token()));
set_json("eos_token", json(tmpl.eos_token()));
set_json("enable_thinking", json(inputs.enable_thinking));
if (tools_override.has_value() || !inputs.tools.empty()) {
inp["tools"] = tools_override.has_value() ? *tools_override : inputs.tools;
set_json("tools", tools_override.has_value() ? *tools_override : inputs.tools);
}
if (inputs.extra_context.is_object()) {
// TODO: do we need to merge, or replacing is fine?
for (const auto & [k, v] : inputs.extra_context.items()) {
inp[k] = v;
set_json(k, v);
}
}
if (additional_context.has_value()) {
// TODO: merge properly instead of overwriting (matching old behavior)
for (const auto & [k, v] : additional_context->items()) {
inp[k] = v;
set_json(k, v);
}
}
if (inputs.add_generation_prompt) {
inp["add_generation_prompt"] = true;
set_json("add_generation_prompt", json(true));
}
jinja::global_from_json(ctx, inp, inputs.mark_input);
// render
jinja::runtime runtime(ctx);
const jinja::value results = runtime.execute(tmpl.prog);
auto parts = jinja::runtime::gather_string_parts(results);
std::string result = parts->as_string().str();
std::string result = jinja::runtime::gather_string(results);
// TODO: improve this later
if (inputs.add_bos && string_starts_with(result, tmpl.bos_token())) {
@@ -913,36 +935,65 @@ std::string common_chat_template_direct_apply(
return common_chat_template_direct_apply_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt);
}
static std::string common_chat_template_generation_prompt_impl(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs,
const std::optional<json> & messages_override = std::nullopt,
const std::optional<json> & tools_override = std::nullopt,
const std::optional<json> & additional_context = std::nullopt) {
auto adjusted_messages = messages_override ? *messages_override : inputs.messages;
autoparser::generation_params params = inputs;
params.add_generation_prompt = false;
params.continue_final_message = COMMON_CHAT_CONTINUATION_NONE;
std::string no_gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
params.add_generation_prompt = true;
std::string gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
static std::string gen_prompt_diff(const std::string & no_gen_prompt, const std::string & gen_prompt) {
size_t prefix_len = 0;
size_t min_size = std::min(no_gen_prompt.size(), gen_prompt.size());
const size_t min_size = std::min(no_gen_prompt.size(), gen_prompt.size());
while (prefix_len < min_size && no_gen_prompt[prefix_len] == gen_prompt[prefix_len]) {
prefix_len++;
}
return gen_prompt.substr(prefix_len);
}
static std::string common_chat_template_generation_prompt_impl(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs,
const std::optional<json> & messages_override = std::nullopt,
const std::optional<json> & tools_override = std::nullopt,
const std::optional<json> & additional_context = std::nullopt,
// The caller's own direct_apply of these inputs and overrides, when it has one.
const std::string * rendered_prompt = nullptr) {
auto adjusted_messages = messages_override ? *messages_override : inputs.messages;
autoparser::generation_params params = inputs;
params.continue_final_message = COMMON_CHAT_CONTINUATION_NONE;
std::string no_gen_prompt;
std::string gen_prompt;
// A rendered prompt is one of the two renders below -- the with-generation-prompt one when
// inputs asks for it, the without one when it does not (direct_apply does not read
// continue_final_message, the only other toggled field) -- so render only the other one. A
// chat request otherwise renders its whole conversation three times.
if (rendered_prompt && inputs.add_generation_prompt) {
gen_prompt = *rendered_prompt;
params.add_generation_prompt = false;
no_gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
} else if (rendered_prompt) {
no_gen_prompt = *rendered_prompt;
params.add_generation_prompt = true;
gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
} else {
params.add_generation_prompt = false;
no_gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
params.add_generation_prompt = true;
gen_prompt = common_chat_template_direct_apply_impl(tmpl, params, adjusted_messages, tools_override, additional_context);
}
return gen_prompt_diff(no_gen_prompt, gen_prompt);
}
std::string common_chat_template_generation_prompt(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs) {
return common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt);
}
std::string common_chat_template_generation_prompt_with_rendered(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs,
const std::string & rendered_prompt) {
return common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &rendered_prompt);
}
static common_chat_params common_chat_params_init_ministral_3(const common_chat_template & tmpl,
const autoparser::generation_params & inputs) {
common_chat_params data;
@@ -981,9 +1032,9 @@ static common_chat_params common_chat_params_init_ministral_3(const common_chat_
}
auto adjusted = msg;
adjusted["content"] = content;
adjusted["content"] = std::move(content);
adjusted.erase("reasoning_content");
adjusted_messages.push_back(adjusted);
adjusted_messages.push_back(std::move(adjusted));
}
auto has_tools = inputs.tools.is_array() && !inputs.tools.empty();
@@ -995,7 +1046,7 @@ static common_chat_params common_chat_params_init_ministral_3(const common_chat_
data.thinking_start_tag = "[THINK]";
data.thinking_end_tag = "[/THINK]";
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs, /* messages_override = */ adjusted_messages);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override = */ adjusted_messages);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override = */ adjusted_messages, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.preserved_tokens = {
"[THINK]",
@@ -1085,12 +1136,15 @@ static common_chat_params common_chat_params_init_gpt_oss(const common_chat_temp
auto adjusted_messages = json::array();
for (auto msg : inputs.messages) {
if (msg.contains("reasoning_content") && msg.at("reasoning_content").is_string()) {
msg["thinking"] = msg.at("reasoning_content");
/* By value first: inserting "thinking" can reallocate msg's member vector,
* which at() reads through. */
const json reasoning = msg.at("reasoning_content");
msg["thinking"] = reasoning;
if (msg.contains("tool_calls") && msg.at("tool_calls").is_array() && !msg.at("tool_calls").empty()) {
msg.erase("content");
}
}
adjusted_messages.push_back(msg);
adjusted_messages.push_back(std::move(msg));
}
auto prompt = common_chat_template_direct_apply_impl(tmpl, inputs, /* messages_override= */ adjusted_messages);
@@ -1108,13 +1162,6 @@ static common_chat_params common_chat_params_init_gpt_oss(const common_chat_temp
data.prompt = prompt;
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, /* messages_override= */ adjusted_messages);
data.message_spans = common_chat_split_by_role(prompt, {
{ "assistant", "<|start|>assistant" },
{ "user", "<|start|>user" },
{ "system", "<|start|>developer" },
{ "system", "<|start|>system" },
{ "tool", "<|start|>functions" },
});
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
@@ -1245,7 +1292,7 @@ static common_chat_params common_chat_params_init_gemma4(const common_chat_templ
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
if (inputs.add_generation_prompt && string_ends_with(data.prompt, "<turn|>\n")) {
// This may happen if the model generates content + tool_call, the
@@ -1255,11 +1302,6 @@ static common_chat_params common_chat_params_init_gemma4(const common_chat_templ
data.prompt += data.generation_prompt;
}
data.message_spans = common_chat_split_by_role(data.prompt, {
{ "user", "<|turn>user\n" },
{ "assistant", "<|turn>model\n" },
});
data.format = COMMON_CHAT_FORMAT_PEG_GEMMA4;
data.supports_thinking = true;
data.thinking_start_tag = "<|channel>thought";
@@ -1409,7 +1451,7 @@ static common_chat_params common_chat_params_init_functionary_v3_2(const common_
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.preserved_tokens = {
">>>all",
@@ -1510,7 +1552,7 @@ static common_chat_params common_chat_params_init_kimi_k2(const common_chat_temp
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
data.preserved_tokens = {
@@ -1646,7 +1688,7 @@ static common_chat_params common_chat_params_init_lfm2(const common_chat_templat
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
data.preserved_tokens = {
@@ -1738,7 +1780,7 @@ static common_chat_params common_chat_params_init_lfm2_5(const common_chat_templ
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
data.preserved_tokens = {
@@ -1822,7 +1864,7 @@ static common_chat_params common_chat_params_init_gigachat_v3(
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = false;
data.preserved_tokens = {
@@ -1900,7 +1942,7 @@ static common_chat_params common_chat_params_init_deepseek_v3_2(const common_cha
common_chat_params data;
data.prompt = common_chat_template_direct_apply_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs);
data.generation_prompt = common_chat_template_generation_prompt_impl(tmpl, inputs, std::nullopt, std::nullopt, std::nullopt, &data.prompt);
data.format = COMMON_CHAT_FORMAT_PEG_NATIVE;
data.supports_thinking = true;
data.thinking_start_tag = "<think>";
@@ -2263,16 +2305,81 @@ static void convert_tool_responses_gemma4(json & messages) {
messages = result;
}
/* Parsed tool-call arguments by their JSON text. An agent re-sends its whole history every
* turn, so the same arguments strings are parsed again on every request; copying the parsed
* DOM back out is several times cheaper than lexing it again. Bounded by key bytes and
* cleared whole when full -- a cache of convenience, never correctness. */
struct ArgsParseCache {
std::mutex mu;
std::unordered_map<std::string, std::shared_ptr<const json>> by_text;
size_t bytes = 0;
};
static ArgsParseCache & args_parse_cache() {
static ArgsParseCache cache;
return cache;
}
// Tool-call arguments a request sent as an object or array reach the template as that value
// (common_chat_tool_call::arguments_json). A template that does not take object arguments
// reads them as a string, so it gets their compact JSON text, as a request sending the string
// would have given it.
static void func_args_string(json & messages) {
GGML_ASSERT(messages.is_array());
for (auto & message : messages) {
if (!message.is_object() || !message.contains("tool_calls") || !message["tool_calls"].is_array()) {
continue;
}
for (auto & tool_call : message["tool_calls"]) {
if (!tool_call.is_object() || !tool_call.contains("function")) {
continue;
}
auto & fn = tool_call["function"];
if (fn.is_object() && fn.contains("arguments")) {
auto & args = fn["arguments"];
if (args.is_object() || args.is_array()) {
args = json(args.dump());
}
}
}
}
}
static void func_args_not_string(json & messages) {
GGML_ASSERT(messages.is_array());
ArgsParseCache & cache = args_parse_cache();
for (auto & message : messages) {
if (message.contains("tool_calls")) {
for (auto & tool_call : message["tool_calls"]) {
if (tool_call.contains("function") && tool_call["function"].contains("arguments")) {
auto & args = tool_call["function"]["arguments"];
if (args.is_string()) {
const std::string & text = args.get_ref<const std::string &>();
std::shared_ptr<const json> hit;
{
std::lock_guard<std::mutex> lock(cache.mu);
auto it = cache.by_text.find(text);
if (it != cache.by_text.end()) {
hit = it->second;
}
}
if (hit) {
args = *hit;
continue;
}
try {
args = json::parse(args.get<std::string>());
json parsed = json::parse(text);
{
std::lock_guard<std::mutex> lock(cache.mu);
if (cache.bytes + text.size() > 8 * 1024 * 1024 ||
cache.by_text.size() >= 4096) {
cache.by_text.clear();
cache.bytes = 0;
}
cache.bytes += text.size();
cache.by_text[text] = std::make_shared<const json>(parsed);
}
args = std::move(parsed);
} catch (const std::exception & e) {
throw std::runtime_error("Failed to parse tool call arguments as JSON: " + std::string(e.what()));
}
@@ -2446,11 +2553,28 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
if (tmpl.original_caps().supports_object_arguments) {
workaround::func_args_not_string(params.messages);
} else {
workaround::func_args_string(params.messages);
}
params.extra_context = common_chat_extra_context();
for (auto el : inputs.chat_template_kwargs) {
params.extra_context[el.first] = json::parse(el.second);
{
// The base context's members in place (a kwarg of the same name replacing one), then
// the other kwargs in order. Appended, not assigned by key: an object lookup is a scan,
// and a request may send many kwargs.
const json base = common_chat_extra_context();
json::object_t ctx;
ctx.reserve(base.size() + inputs.chat_template_kwargs.size());
for (auto it = base.begin(); it != base.end(); ++it) {
auto kw = inputs.chat_template_kwargs.find(it.key());
ctx.emplace_back(it.key(), kw != inputs.chat_template_kwargs.end() ? json::parse(kw->second)
: it.value());
}
for (const auto & el : inputs.chat_template_kwargs) {
if (!base.contains(el.first)) {
ctx.emplace_back(el.first, json::parse(el.second));
}
}
params.extra_context = json(std::move(ctx));
}
if (!inputs.json_schema.empty()) {
@@ -2496,26 +2620,19 @@ static common_chat_params common_chat_templates_apply_jinja(const struct common_
const autoparser::autoparser & autoparser = *analysis;
auto auto_params = autoparser::peg_generator::generate_parser(tmpl, params, autoparser);
std::vector<common_chat_msg_delimiter> delimiters;
if (!autoparser.assistant_start.empty()) {
delimiters.push_back({ "assistant", autoparser.assistant_start });
}
if (!autoparser.user_start.empty()) {
delimiters.push_back({ "user", autoparser.user_start });
}
if (!delimiters.empty()) {
auto_params.message_spans = common_chat_split_by_role(auto_params.prompt, delimiters);
}
// No message_spans: nothing in this tree reads them, and splitting the rendered
// prompt by role is a full extra scan of every conversation.
auto_params.supports_thinking = autoparser.reasoning.mode != autoparser::reasoning_mode::NONE;
if (auto_params.supports_thinking) {
auto_params.thinking_start_tag = trim_whitespace(autoparser.reasoning.start);
auto_params.thinking_end_tag = trim_whitespace(autoparser.reasoning.end);
}
common_peg_arena arena;
arena.load(auto_params.parser);
LOG_DBG("%s: generated parser:\n%s\n\nparser generation prompt: %s\n", __func__, arena.dump(arena.root()).c_str(), auto_params.generation_prompt.c_str());
if (::rad_vendor_log::verbose()) {
common_peg_arena arena;
arena.load(auto_params.parser);
LOG_DBG("%s: generated parser:\n%s\n\nparser generation prompt: %s\n", __func__, arena.dump(arena.root()).c_str(), auto_params.generation_prompt.c_str());
}
return auto_params;
} catch (const std::exception & e) {
throw std::invalid_argument(std::string("Unable to generate parser for this template. Automatic parser generation failed: ") + e.what());
@@ -2679,3 +2796,10 @@ std::map<std::string, bool> common_chat_templates_get_caps(const common_chat_tem
GGML_ASSERT(chat_templates->template_default != nullptr);
return chat_templates->template_default->caps.to_map();
}
// RADIANCE: jinja::caps::probe_error of the default template.
std::string common_chat_templates_get_probe_error(const common_chat_templates * chat_templates) {
GGML_ASSERT(chat_templates != nullptr);
GGML_ASSERT(chat_templates->template_default != nullptr);
return chat_templates->template_default->caps.probe_error;
}
+24 -11
View File
@@ -8,16 +8,17 @@
#include "jinja/runtime.h"
#include "jinja/caps.h"
#include "nlohmann/json_fwd.hpp"
#include "util/json.h"
#include <chrono>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <vector>
using chat_template_caps = jinja::caps;
using json = nlohmann::ordered_json;
using json = rad::Json;
struct common_chat_templates;
@@ -29,10 +30,13 @@ struct common_chat_tool_call {
std::string name;
std::string arguments;
std::string id;
/* Arguments that arrived already parsed (an object in the request), carried as JSON so
* the render path neither dumps them to a string here nor parses that string back when a
* template reads them as a mapping. When set, `arguments` stays empty and this is the
* value common_chat_msgs_to_json_oaicompat emits. */
std::shared_ptr<const rad::Json> arguments_json;
bool operator==(const common_chat_tool_call & other) const {
return name == other.name && arguments == other.arguments && id == other.id;
}
bool operator==(const common_chat_tool_call & other) const;
};
struct common_chat_msg_content_part {
@@ -87,7 +91,7 @@ struct common_chat_msg {
std::string tool_name;
std::string tool_call_id;
nlohmann::ordered_json to_json_oaicompat(bool concat_typed_text = false) const;
rad::Json to_json_oaicompat(bool concat_typed_text = false) const;
std::string render_content(const std::string & delimiter = "\n\n") const;
@@ -289,19 +293,20 @@ common_chat_tool_choice common_chat_tool_choice_parse_oaicompat(const std::strin
bool common_chat_templates_support_enable_thinking(const common_chat_templates * chat_templates);
// Parses a JSON array of messages in OpenAI's chat completion API format.
std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const nlohmann::ordered_json & messages);
std::vector<common_chat_msg> common_chat_msgs_parse_oaicompat(const rad::Json & messages);
std::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const nlohmann::ordered_json & tools);
std::vector<common_chat_tool> common_chat_tools_parse_oaicompat(const rad::Json & tools);
common_chat_continuation common_chat_continuation_parse(const nlohmann::ordered_json & value);
common_chat_continuation common_chat_continuation_parse(const rad::Json & value);
// DEPRECATED: only used in tests
nlohmann::ordered_json common_chat_msgs_to_json_oaicompat(const std::vector<common_chat_msg> & msgs, bool concat_typed_text = false);
rad::Json common_chat_msgs_to_json_oaicompat(const std::vector<common_chat_msg> & msgs, bool concat_typed_text = false);
nlohmann::ordered_json common_chat_tools_to_json_oaicompat(const std::vector<common_chat_tool> & tools);
rad::Json common_chat_tools_to_json_oaicompat(const std::vector<common_chat_tool> & tools);
// get template caps, useful for reporting to server /props endpoint
std::map<std::string, bool> common_chat_templates_get_caps(const common_chat_templates * chat_templates);
std::string common_chat_templates_get_probe_error(const common_chat_templates * chat_templates);
std::string common_chat_template_direct_apply(
const common_chat_template & tmpl,
@@ -311,6 +316,14 @@ std::string common_chat_template_generation_prompt(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs);
// As above, with the caller's own direct_apply of `inputs` in hand: it is one of the two
// renders the generation prompt is diffed from, so the other is the only one still needed
// (and a repeat request whose generation prompt proved message-independent needs neither).
std::string common_chat_template_generation_prompt_with_rendered(
const common_chat_template & tmpl,
const autoparser::generation_params & inputs,
const std::string & rendered_prompt);
std::optional<common_chat_params> common_chat_try_specialized_template(
const common_chat_template & tmpl,
const std::string & src,
+1 -1
View File
@@ -7,7 +7,7 @@ The implementation can be found in the `common/jinja` directory.
## Key Features
- Input marking: security against special token injection
- Decoupled from `nlohmann::json`: this dependency is only used for JSON-to-internal type translation and is completely optional
- Decoupled from `Json`: this dependency is only used for JSON-to-internal type translation and is completely optional
- Minimal primitive types: int, float, bool, string, array, object, none, undefined
- Detailed logging: allow source tracing on error
- Clean architecture: workarounds are applied to input data before entering the runtime (see `common/chat.cpp`)
+12 -2
View File
@@ -4,20 +4,24 @@
// note: the json dependency is only for defining input in a convenient way
// we can remove it in the future when we figure out a better way to define inputs using jinja::value
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <functional>
#include <sstream>
#define FILENAME "jinja-caps"
using json = nlohmann::ordered_json;
using json = rad::Json;
namespace jinja {
using caps_json_fn = std::function<json()>;
using caps_analyze_fn = std::function<void(bool, value &, value &)>;
// RADIANCE: where caps_get collects the first exception of a probe that carried tools
// (caps::probe_error).
static thread_local std::string * caps_probe_error = nullptr;
static void caps_try_execute(jinja::program & prog,
const caps_json_fn & messages_fn,
const caps_json_fn & tools_fn,
@@ -45,6 +49,10 @@ static void caps_try_execute(jinja::program & prog,
success = true;
} catch (const std::exception & e) {
JJ_DEBUG("Exception during execution: %s", e.what());
if (caps_probe_error && caps_probe_error->empty() && is_val<value_array>(tools) &&
!tools->as_array().empty()) {
*caps_probe_error = e.what();
}
result = "";
// ignore exceptions during capability analysis
}
@@ -90,6 +98,7 @@ std::string caps::to_string() const {
caps caps_get(jinja::program & prog) {
caps result;
caps_probe_error = &result.probe_error;
static const auto has_op = [](value & v, const std::string & op_name) {
return v->stats.ops.find(op_name) != v->stats.ops.end();
@@ -475,6 +484,7 @@ caps caps_get(jinja::program & prog) {
JJ_DEBUG("%s\n", result.to_string().c_str());
caps_probe_error = nullptr;
return result;
}
+5
View File
@@ -20,6 +20,11 @@ struct caps {
bool supports_object_arguments = false;
// RADIANCE: what the first probe render that threw said, empty when none did. The probes
// ignore exceptions, so a template calling something this engine lacks and a template
// without tool support both come back supports_tools = false; this tells them apart.
std::string probe_error;
// for reporting on server
std::map<std::string, bool> to_map() const;
+104 -69
View File
@@ -18,16 +18,27 @@ void enable_debug(bool enable) {
g_jinja_debug = enable;
}
/* A block's statement results as one string value. A lone string result already is that
* value -- regathering it would copy (or move) its parts into a fresh string for nothing,
* and blocks with a single output statement are the common shape inside a message loop. */
static value_string gather_array_result(const value_array & result) {
if (result->val_arr.size() == 1) {
if (auto s = std::dynamic_pointer_cast<value_string_t>(result->val_arr[0])) {
return s;
}
}
value_string str = mk_val<value_string>();
gather_string_parts_recursive(result, str);
return str;
}
static value_string exec_statements(const statements & stmts, context & ctx) {
auto result = mk_val<value_array>();
for (const auto & stmt : stmts) {
JJ_DEBUG("Executing statement of type %s", stmt->type().c_str());
result->push_back(stmt->execute(ctx));
}
// convert to string parts
value_string str = mk_val<value_string>();
gather_string_parts_recursive(result, str);
return str;
return gather_array_result(result);
}
static std::string get_line_col(const std::string & source, size_t pos) {
@@ -82,14 +93,17 @@ value statement::execute(context & ctx) {
value identifier::execute_impl(context & ctx) {
auto it = ctx.get_val(val);
auto builtins = global_builtins();
if (!it->is_undefined()) {
if (ctx.is_get_stats) {
value_t::stats_t::mark_used(it);
}
JJ_DEBUG("Identifier '%s' found, type = %s", val.c_str(), it->type().c_str());
return it;
} else if (builtins.find(val) != builtins.end()) {
}
// By reference, and only on the miss path: this used to copy the whole builtins map
// (every std::function in it) for every identifier evaluated.
const auto & builtins = global_builtins();
if (builtins.find(val) != builtins.end()) {
JJ_DEBUG("Identifier '%s' found in builtins", val.c_str());
return mk_val<value_func>(val, builtins.at(val));
} else {
@@ -139,8 +153,8 @@ value binary_expression::execute_impl(context & ctx) {
JJ_DEBUG("%s", "Workaround: treating null/undefined as empty string for string concatenation");
string left_str = is_left_null ? string() : left_val->as_string();
string right_str = is_right_null ? string() : right_val->as_string();
auto output = left_str.append(right_str);
res = mk_val<value_string>(std::move(output));
left_str.append(right_str);
res = mk_val<value_string>(std::move(left_str));
return true;
}
return false;
@@ -245,7 +259,8 @@ value binary_expression::execute_impl(context & ctx) {
if ((is_val<value_string>(left_val) || is_val<value_string>(right_val)) &&
(op.value == "~" || op.value == "+")) {
JJ_DEBUG("String concatenation with %s operator", op.value.c_str());
auto output = left_val->as_string().append(right_val->as_string());
string output = left_val->as_string();
output.append(right_val->as_string());
auto res = mk_val<value_string>();
res->val_str = std::move(output);
return res;
@@ -263,7 +278,7 @@ value binary_expression::execute_impl(context & ctx) {
return res;
}
for (int64_t i = 0; i < repeat; ++i) {
res->val_str = res->val_str.append(str);
res->val_str.append(str);
}
return res;
}
@@ -299,7 +314,7 @@ static value try_builtin_func(context & ctx, const std::string & name, value & i
value_t::stats_t::mark_used(input);
input->stats.ops.insert(name);
}
auto builtins = input->get_builtins();
const auto & builtins = input->get_builtins();
auto it = builtins.find(name);
if (it != builtins.end()) {
JJ_DEBUG("Binding built-in '%s'", name.c_str());
@@ -441,7 +456,7 @@ value unary_expression::execute_impl(context & ctx) {
value if_statement::execute_impl(context & ctx) {
value test_val = test->execute(ctx);
auto out = mk_val<value_array>();
auto out = mk_val<value_stmt_results>();
if (test_val->as_bool()) {
for (auto & stmt : body) {
JJ_DEBUG("IF --> Executing THEN body, current block: %s", stmt->type().c_str());
@@ -453,10 +468,7 @@ value if_statement::execute_impl(context & ctx) {
out->push_back(stmt->execute(ctx));
}
}
// convert to string parts
value_string str = mk_val<value_string>();
gather_string_parts_recursive(out, str);
return str;
return out;
}
value for_statement::execute_impl(context & ctx) {
@@ -517,31 +529,36 @@ value for_statement::execute_impl(context & ctx) {
}
}
std::vector<std::function<void(context &)>> scope_update_fns;
std::vector<value> filtered_items;
for (size_t i = 0; i < items.size(); ++i) {
context loop_scope(scope);
value current = items[i];
std::function<void(context&)> scope_update_fn = [](context &) { /* no-op */};
// Bind the loop variable(s) for items[i] in a context. One lambda for the whole loop:
// this used to build a std::function per item (and a copied scope to test it on, selected
// or not), which made filtering cost more than the iterations it sets up.
auto apply_loop_var = [&](context & c, size_t i) {
if (is_stmt<identifier>(loopvar)) {
auto id = cast_stmt<identifier>(loopvar)->val;
if (is_val<value_object>(iterable_val)) {
// case example: {% for key in dict %}
current = items[i]->as_array()[0];
scope_update_fn = [id, &items, i](context & ctx) {
ctx.set_val(id, items[i]->as_array()[0]);
};
} else {
// case example: {% for item in list %}
scope_update_fn = [id, &items, i](context & ctx) {
ctx.set_val(id, items[i]);
};
// {% for key in dict %} binds the key, {% for item in list %} the item.
c.set_val(id, is_val<value_object>(iterable_val) ? items[i]->as_array()[0] : items[i]);
} else {
auto tuple = cast_stmt<tuple_literal>(loopvar);
auto & c_arr = items[i]->as_array();
for (size_t j = 0; j < tuple->val.size(); ++j) {
if (!is_stmt<identifier>(tuple->val[j])) {
throw std::runtime_error("Cannot unpack non-identifier type: " + tuple->val[j]->type());
}
auto id = cast_stmt<identifier>(tuple->val[j])->val;
c.set_val(id, c_arr[j]);
}
}
};
std::vector<value> filtered_items;
std::vector<size_t> filtered_idx;
for (size_t i = 0; i < items.size(); ++i) {
value current = items[i];
if (is_stmt<identifier>(loopvar)) {
if (is_val<value_object>(iterable_val)) {
current = items[i]->as_array()[0];
}
} else if (is_stmt<tuple_literal>(loopvar)) {
// case example: {% for key, value in dict %}
auto tuple = cast_stmt<tuple_literal>(loopvar);
@@ -552,23 +569,13 @@ value for_statement::execute_impl(context & ctx) {
if (tuple->val.size() != c_arr.size()) {
throw std::runtime_error(std::string("Too ") + (tuple->val.size() > c_arr.size() ? "few" : "many") + " items to unpack");
}
scope_update_fn = [tuple, &items, i](context & ctx) {
auto & c_arr = items[i]->as_array();
for (size_t j = 0; j < tuple->val.size(); ++j) {
if (!is_stmt<identifier>(tuple->val[j])) {
throw std::runtime_error("Cannot unpack non-identifier type: " + tuple->val[j]->type());
}
auto id = cast_stmt<identifier>(tuple->val[j])->val;
ctx.set_val(id, c_arr[j]);
}
};
} else {
throw std::runtime_error("Invalid loop variable(s): " + loopvar->type());
}
if (select_expr && test_expr) {
scope_update_fn(loop_scope);
context loop_scope(scope);
apply_loop_var(loop_scope, i);
value test_val = test_expr->execute(loop_scope);
if (!test_val->as_bool()) {
continue;
@@ -576,28 +583,45 @@ value for_statement::execute_impl(context & ctx) {
}
JJ_DEBUG("For loop: adding item type %s at index %zu", current->type().c_str(), i);
filtered_items.push_back(current);
scope_update_fns.push_back(scope_update_fn);
filtered_idx.push_back(i);
}
JJ_DEBUG("For loop: %zu items after filtering", filtered_items.size());
auto result = mk_val<value_array>();
auto result = mk_val<value_stmt_results>();
// One loop object for the whole loop, its fields replaced per iteration (as in Jinja2,
// where `loop` is one context object whose counters move): a fresh object per iteration
// was nine hash nodes and a bucket array allocated to describe a counter.
value_object loop_obj;
if (!filtered_items.empty()) {
loop_obj = mk_val<value_object>();
loop_obj->has_builtins = false; // loop object has no builtins
loop_obj->insert_new("index", mk_val<value_int>(1));
loop_obj->insert_new("index0", mk_val<value_int>(0));
loop_obj->insert_new("revindex", mk_val<value_int>(filtered_items.size()));
loop_obj->insert_new("revindex0", mk_val<value_int>(filtered_items.size() - 1));
loop_obj->insert_new("first", mk_val<value_bool>(true));
loop_obj->insert_new("last", mk_val<value_bool>(filtered_items.size() == 1));
loop_obj->insert_new("length", mk_val<value_int>(filtered_items.size()));
loop_obj->insert_new("previtem", mk_val<value_undefined>("previtem"));
loop_obj->insert_new("nextitem", filtered_items.size() > 1 ? filtered_items[1] : mk_val<value_undefined>("nextitem"));
}
bool noIteration = true;
for (size_t i = 0; i < filtered_items.size(); i++) {
JJ_DEBUG("For loop iteration %zu/%zu", i + 1, filtered_items.size());
value_object loop_obj = mk_val<value_object>();
loop_obj->has_builtins = false; // loop object has no builtins
loop_obj->insert("index", mk_val<value_int>(i + 1));
loop_obj->insert("index0", mk_val<value_int>(i));
loop_obj->insert("revindex", mk_val<value_int>(filtered_items.size() - i));
loop_obj->insert("revindex0", mk_val<value_int>(filtered_items.size() - i - 1));
loop_obj->insert("first", mk_val<value_bool>(i == 0));
loop_obj->insert("last", mk_val<value_bool>(i == filtered_items.size() - 1));
loop_obj->insert("length", mk_val<value_int>(filtered_items.size()));
loop_obj->insert("previtem", i > 0 ? filtered_items[i - 1] : mk_val<value_undefined>("previtem"));
loop_obj->insert("nextitem", i < filtered_items.size() - 1 ? filtered_items[i + 1] : mk_val<value_undefined>("nextitem"));
if (i > 0) {
loop_obj->at("index") = mk_val<value_int>(i + 1);
loop_obj->at("index0") = mk_val<value_int>(i);
loop_obj->at("revindex") = mk_val<value_int>(filtered_items.size() - i);
loop_obj->at("revindex0") = mk_val<value_int>(filtered_items.size() - i - 1);
loop_obj->at("first") = mk_val<value_bool>(false);
loop_obj->at("last") = mk_val<value_bool>(i == filtered_items.size() - 1);
loop_obj->at("previtem") = filtered_items[i - 1];
loop_obj->at("nextitem") = i < filtered_items.size() - 1 ? filtered_items[i + 1] : mk_val<value_undefined>("nextitem");
}
scope.set_val("loop", loop_obj);
scope_update_fns[i](scope);
apply_loop_var(scope, filtered_idx[i]);
try {
for (auto & stmt : body) {
value val = stmt->execute(scope);
@@ -619,10 +643,7 @@ value for_statement::execute_impl(context & ctx) {
}
}
// convert to string parts
value_string str = mk_val<value_string>();
gather_string_parts_recursive(result, str);
return str;
return result;
}
value set_statement::execute_impl(context & ctx) {
@@ -790,8 +811,7 @@ value member_expression::execute_impl(context & ctx) {
if (!is_stmt<identifier>(this->property)) {
throw std::runtime_error("Static member property must be an identifier");
}
property = mk_val<value_string>(cast_stmt<identifier>(this->property)->val);
std::string prop = property->as_string().str();
const std::string & prop = cast_stmt<identifier>(this->property)->val;
JJ_DEBUG("Member expression, object type %s, static property '%s'", object->type().c_str(), prop.c_str());
// behavior of jinja2: obj having prop as a built-in function AND 'prop', as an object key,
@@ -803,6 +823,21 @@ value member_expression::execute_impl(context & ctx) {
if (!is_val<value_undefined>(val)) {
return val;
}
if (is_val<value_object>(object)) {
// The common case (a message field): look the name up directly instead of
// allocating a key value and hashing it, then trying the builtins a second time.
value out = mk_val<value_undefined>("object_property");
out = object->at(prop, out);
if (ctx.is_get_stats && out && object) {
value prop_val = mk_val<value_string>(prop);
value_t::stats_t::mark_used(out);
value_t::stats_t::mark_used(object);
value_t::stats_t::mark_used(prop_val);
object->stats.ops.insert("object_access");
}
return out;
}
property = mk_val<value_string>(prop);
// else, fallthrough to normal property access below
}
+103 -27
View File
@@ -69,18 +69,17 @@ struct context {
context(const context & parent) : context() {
// inherit variables (for example, when entering a new scope)
auto & pvar = parent.env->as_ordered_object();
for (const auto & pair : pvar) {
set_val(pair.first, pair.second);
}
env->copy_entries_from(*parent.env);
current_time = parent.current_time;
is_get_stats = parent.is_get_stats;
src = parent.src;
}
value get_val(const std::string & name) {
value default_val = mk_val<value_undefined>(name);
return env->at(name, default_val);
if (value * v = env->find_string_key(name)) {
return *v;
}
return mk_val<value_undefined>(name);
}
void set_val(const std::string & name, const value & val) {
@@ -316,30 +315,37 @@ struct identifier : public expression {
// Literals
/* A literal's value made once, at parse time: literals sit inside the loops a template runs
* per message, and allocating a fresh value (and copying the text) for every evaluation was
* thousands of allocations per render for values nothing ever mutates -- every operation on
* a string works on an as_string() copy, and numbers are only read. */
struct integer_literal : public expression {
int64_t val;
explicit integer_literal(int64_t val) : val(val) {}
value cached;
explicit integer_literal(int64_t val) : val(val), cached(mk_val<value_int>(val)) {}
std::string type() const override { return "IntegerLiteral"; }
value execute_impl(context &) override {
return mk_val<value_int>(val);
return cached;
}
};
struct float_literal : public expression {
double val;
explicit float_literal(double val) : val(val) {}
value cached;
explicit float_literal(double val) : val(val), cached(mk_val<value_float>(val)) {}
std::string type() const override { return "FloatLiteral"; }
value execute_impl(context &) override {
return mk_val<value_float>(val);
return cached;
}
};
struct string_literal : public expression {
std::string val;
explicit string_literal(const std::string & val) : val(val) {}
value cached;
explicit string_literal(const std::string & val) : val(val), cached(mk_val<value_string>(val)) {}
std::string type() const override { return "StringLiteral"; }
value execute_impl(context &) override {
return mk_val<value_string>(val);
return cached;
}
};
@@ -598,19 +604,35 @@ struct rethrown_exception : public std::exception {
static void gather_string_parts_recursive(const value & val, value_string & parts) {
// TODO: probably allow print value_none as "None" string? currently this breaks some templates
if (is_val<value_string>(val)) {
const auto & str_val = cast_val<value_string>(val)->val_str;
parts->val_str.append(str_val);
// A uniquely owned string is a statement result being consumed by this gather; move its
// parts instead of copying every byte again at each nesting level. A shared one is an
// input value the context still holds, and is copied as before.
if (val.use_count() == 1) {
auto & src = const_cast<value_string_t *>(cast_val<value_string>(val))->val_str.parts;
auto & dst = parts->val_str.parts;
dst.reserve(dst.size() + src.size());
for (auto & part : src) {
dst.push_back(std::move(part));
}
src.clear();
} else {
const auto & str_val = cast_val<value_string>(val)->val_str;
parts->val_str.append(str_val);
}
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
std::string str_val = val->as_string().str();
parts->val_str.append(str_val);
} else if (is_val<value_array>(val)) {
auto items = cast_val<value_array>(val)->as_array();
const auto & items = cast_val<value_array>(val)->as_array();
for (const auto & item : items) {
/* RADIANCE: `val` is a block's statement results, and every block statement returns
* a string, so a list or a dict among them is the value of an expression the template
* prints. jinja2 prints its repr; flattening it ran its strings together and printed
* nothing for a dict. */
if (is_val<value_array>(item) || is_val<value_object>(item)) {
* nothing for a dict. A statement-results carrier is the one array that is not a
* value: flattening it is its whole purpose. */
if (is_val<value_stmt_results>(item)) {
gather_string_parts_recursive(item, parts);
} else if (is_val<value_array>(item) || is_val<value_object>(item)) {
parts->val_str.append(item->as_string().str());
} else {
gather_string_parts_recursive(item, parts);
@@ -620,11 +642,54 @@ static void gather_string_parts_recursive(const value & val, value_string & part
}
static std::string render_string_parts(const value_string & parts) {
std::ostringstream oss;
std::string out;
out.reserve(parts->val_str.length());
for (const auto & part : parts->val_str.parts) {
oss << part.val;
out += part.val;
}
return out;
}
// The flat text of a statement-result tree, gathered without building a parts list: the parts
// (and their is_input flags) matter to the capability probe, but a caller that only wants the
// rendered string otherwise pays to copy every byte into parts, join them, and copy them out.
static size_t gather_string_length_recursive(const value & val) {
if (is_val<value_string>(val)) {
return cast_val<value_string>(val)->val_str.length();
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
return val->as_string().str().size();
} else if (is_val<value_array>(val)) {
size_t len = 0;
for (const auto & item : cast_val<value_array>(val)->as_array()) {
if (!is_val<value_stmt_results>(item) &&
(is_val<value_array>(item) || is_val<value_object>(item))) {
len += item->as_string().str().size();
} else {
len += gather_string_length_recursive(item);
}
}
return len;
}
return 0;
}
static void gather_string_recursive(const value & val, std::string & out) {
if (is_val<value_string>(val)) {
for (const auto & part : cast_val<value_string>(val)->val_str.parts) {
out += part.val;
}
} else if (is_val<value_int>(val) || is_val<value_float>(val) || is_val<value_bool>(val)) {
out += val->as_string().str();
} else if (is_val<value_array>(val)) {
for (const auto & item : cast_val<value_array>(val)->as_array()) {
if (!is_val<value_stmt_results>(item) &&
(is_val<value_array>(item) || is_val<value_object>(item))) {
out += item->as_string().str();
} else {
gather_string_recursive(item, out);
}
}
}
return oss.str();
}
struct runtime {
@@ -643,18 +708,29 @@ struct runtime {
static value_string gather_string_parts(const value & val) {
value_string parts = mk_val<value_string>();
gather_string_parts_recursive(val, parts);
// join consecutive parts with the same type
// Join consecutive parts with the same type, in one compaction pass: erasing each
// merged part from the middle shifts the rest of the vector every time.
auto & p = parts->val_str.parts;
for (size_t i = 1; i < p.size(); ) {
if (p[i].is_input == p[i - 1].is_input) {
p[i - 1].val += p[i].val;
p.erase(p.begin() + i);
} else {
i++;
if (!p.empty()) {
size_t w = 0;
for (size_t r = 1; r < p.size(); ++r) {
if (p[r].is_input == p[w].is_input) {
p[w].val += p[r].val;
} else {
p[++w] = std::move(p[r]);
}
}
p.resize(w + 1);
}
return parts;
}
static std::string gather_string(const value & val) {
std::string out;
out.reserve(gather_string_length_recursive(val));
gather_string_recursive(val, out);
return out;
}
};
} // namespace jinja
+41 -12
View File
@@ -2,6 +2,7 @@
#include "jinja/value.h"
#include <algorithm>
#include <cstring>
#include <functional>
#include <optional>
#include <sstream>
@@ -46,11 +47,38 @@ std::string string::str() const {
if (parts.size() == 1) {
return parts[0].val;
}
std::ostringstream oss;
std::string out;
out.reserve(length());
for (const auto & part : parts) {
oss << part.val;
out += part.val;
}
return oss.str();
return out;
}
bool string::equals(const string & other) const {
if (parts.size() == 1 && other.parts.size() == 1) {
return parts[0].val == other.parts[0].val;
}
if (length() != other.length()) {
return false;
}
size_t i = 0, j = 0; // part cursors
size_t a = 0, b = 0; // byte offsets within the cursors' parts
while (i < parts.size() && j < other.parts.size()) {
const std::string & pa = parts[i].val;
const std::string & pb = other.parts[j].val;
const size_t n = std::min(pa.size() - a, pb.size() - b);
if (n > 0 && std::memcmp(pa.data() + a, pb.data() + b, n) != 0) {
return false;
}
a += n;
b += n;
if (a == pa.size()) { ++i; a = 0; }
if (b == pb.size()) { ++j; b = 0; }
}
// The lengths are equal and every byte compared equal; what is left on either side is
// empty parts.
return true;
}
size_t string::length() const {
@@ -103,7 +131,8 @@ void string::mark_input_based_on(const string & other) {
}
}
string string::append(const string & other) {
string & string::append(const string & other) {
parts.reserve(parts.size() + other.parts.size());
for (const auto & part : other.parts) {
parts.push_back(part);
}
@@ -113,29 +142,29 @@ string string::append(const string & other) {
// in-place transformation
using transform_fn = std::function<std::string(const std::string&)>;
static string apply_transform(string & self, const transform_fn & fn) {
static string apply_transform(string && self, const transform_fn & fn) {
for (auto & part : self.parts) {
part.val = fn(part.val);
}
return self;
return std::move(self);
}
string string::uppercase() {
return apply_transform(*this, [](const std::string & s) {
return apply_transform(std::move(*this), [](const std::string & s) {
std::string res = s;
std::transform(res.begin(), res.end(), res.begin(), ::toupper);
return res;
});
}
string string::lowercase() {
return apply_transform(*this, [](const std::string & s) {
return apply_transform(std::move(*this), [](const std::string & s) {
std::string res = s;
std::transform(res.begin(), res.end(), res.begin(), ::tolower);
return res;
});
}
string string::capitalize() {
return apply_transform(*this, [](const std::string & s) {
return apply_transform(std::move(*this), [](const std::string & s) {
if (s.empty()) return s;
std::string res = s;
res[0] = ::toupper(static_cast<unsigned char>(res[0]));
@@ -144,7 +173,7 @@ string string::capitalize() {
});
}
string string::titlecase() {
return apply_transform(*this, [](const std::string & s) {
return apply_transform(std::move(*this), [](const std::string & s) {
std::string res = s;
bool capitalize_next = true;
for (char &c : res) {
@@ -180,7 +209,7 @@ string string::strip(bool left, bool right, std::optional<const std::string_view
return s.substr(start, end - start);
};
if (parts.empty()) {
return *this;
return std::move(*this);
}
if (left) {
for (size_t i = 0; i < parts.size(); ++i) {
@@ -207,7 +236,7 @@ string string::strip(bool left, bool right, std::optional<const std::string_view
}
}
}
return *this;
return std::move(*this);
}
} // namespace jinja
+7 -1
View File
@@ -27,6 +27,9 @@ struct string {
string(const std::string & v, bool user_input = false) {
parts.push_back({user_input, v});
}
string(std::string && v, bool user_input = false) {
parts.push_back({user_input, std::move(v)});
}
string(int v) {
parts.push_back({false, std::to_string(v)});
}
@@ -38,6 +41,8 @@ struct string {
void mark_input();
std::string str() const;
// Flattened equality without flattening: walk both part lists segment by segment.
bool equals(const string & other) const;
size_t length() const;
void hash_update(hasher & hash) const noexcept;
bool all_parts_are_input() const;
@@ -47,7 +52,8 @@ struct string {
// mark this string as input if other has ALL parts as input
void mark_input_based_on(const string & other);
string append(const string & other);
// In place: the parts are appended to this string. Returns *this so callers can move it on.
string & append(const string & other);
// in-place transformations
+65 -9
View File
@@ -3,7 +3,7 @@
#include "value.h"
// for converting from JSON to jinja values
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <sstream>
#include <string>
@@ -299,6 +299,58 @@ static value minmax_fn(const func_args & args) {
return best;
}
/* jinja2's unique() over a sequence: the first occurrence of each item, in order, compared by
* `attribute` where one is given. Strings compare lowercased unless `case_sensitive` is true
* (jinja2's default is false). A tuple stays a tuple. */
static value unique_fn(const func_args & args) {
args.ensure_count(1, 3);
if (!is_val<value_array>(args.get_pos(0))) {
throw raised_exception("unique: first argument must be an array");
}
value val = args.get_pos(0);
value cs = args.get_kwarg_or_pos("case_sensitive", 1);
value attribute = args.get_kwarg_or_pos("attribute", 2);
const bool case_sensitive = !cs->is_undefined() && cs->as_bool();
const bool attr_is_int = is_val<value_int>(attribute);
const int64_t attr_int = attr_is_int ? attribute->as_int() : 0;
const std::vector<value> & arr = val->as_array();
auto key = [&](const value & v) -> value {
value k = v;
if (!attribute->is_undefined()) {
if (attr_is_int && is_val<value_array>(v)) {
k = v->at(attr_int);
} else if (!attr_is_int && is_val<value_object>(v)) {
k = v->at(attribute);
} else {
throw raised_exception("unique: unsupported object attribute comparison on " + v->type());
}
}
if (!case_sensitive && is_val<value_string>(k)) {
jinja::string low = k->as_string().lowercase();
return mk_val<value_string>(low);
}
return k;
};
std::vector<value> keys, out;
for (const auto & item : arr) {
value k = key(item);
bool seen = false;
for (const auto & have : keys) {
/* value_compare reads a number against a string as text; jinja2 keeps 1 and "1" apart */
if (is_val<value_string>(k) == is_val<value_string>(have) &&
value_compare(k, have, value_compare_op::eq)) {
seen = true;
break;
}
}
if (!seen) {
keys.push_back(std::move(k));
out.push_back(item);
}
}
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(out)) : mk_val<value_array>(std::move(out));
}
template<bool is_reject>
static value selectattr(const func_args & args) {
args.ensure_count(2, 4);
@@ -924,10 +976,6 @@ const func_builtins & value_bool_t::get_builtins() const {
return builtins;
}
[[noreturn]] static value array_unique_not_implemented(const func_args &) {
throw not_implemented_exception("Array unique builtin not implemented");
}
const func_builtins & value_array_t::get_builtins() const {
static const func_builtins builtins = {
{"default", default_value},
@@ -1133,7 +1181,10 @@ const func_builtins & value_array_t::get_builtins() const {
std::reverse(arr.begin(), arr.end());
return is_val<value_tuple>(val) ? mk_val<value_tuple>(std::move(arr)) : mk_val<value_array>(std::move(arr));
}},
{"unique", array_unique_not_implemented},
/* RADIANCE: upstream leaves `unique` a stub that throws, with the same result as a
* missing min or max above: GLM-5.3-Flash's template checks its tool-call ids with it,
* and the model was reported as having no tool support. */
{"unique", unique_fn},
};
return builtins;
}
@@ -1297,7 +1348,7 @@ const func_builtins & value_undefined_t::get_builtins() const {
//////////////////////////////////
static value from_json(const nlohmann::ordered_json & j, bool mark_input) {
static value from_json(const rad::Json & j, bool mark_input) {
if (j.is_null()) {
return mk_val<value_none>();
} else if (j.is_boolean()) {
@@ -1307,7 +1358,7 @@ static value from_json(const nlohmann::ordered_json & j, bool mark_input) {
} else if (j.is_number_float()) {
return mk_val<value_float>(j.get<double>());
} else if (j.is_string()) {
auto str = mk_val<value_string>(j.get<std::string>());
auto str = mk_val<value_string>(j.get_ref<const std::string &>());
if (mark_input) {
str->mark_input();
}
@@ -1394,7 +1445,7 @@ bool value_compare(const value & a, const value & b, value_compare_op op) {
}
template<>
void global_from_json(context & ctx, const nlohmann::ordered_json & json_obj, bool mark_input) {
void global_from_json(context & ctx, const rad::Json & json_obj, bool mark_input) {
// printf("global_from_json: %s\n" , json_obj.dump(2).c_str());
if (json_obj.is_null() || !json_obj.is_object()) {
throw std::runtime_error("global_from_json: input JSON value must be an object");
@@ -1405,6 +1456,11 @@ void global_from_json(context & ctx, const nlohmann::ordered_json & json_obj, bo
}
}
void global_set_from_json(context & ctx, const std::string & key,
const rad::Json & j, bool mark_input) {
ctx.set_val(key, from_json(j, mark_input));
}
// recursively convert value to JSON string
// TODO: avoid circular references
static void value_to_json_internal(std::ostringstream & oss, const value & val, int curr_lvl, int indent, const std::string_view item_sep, const std::string_view key_sep) {
+170 -28
View File
@@ -3,6 +3,8 @@
#include "string.h"
#include "utils.h"
#include "util/json.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
@@ -86,10 +88,16 @@ struct context; // forward declaration
// marking input can be useful for tracking data provenance
// and preventing template injection attacks
//
// Note: T_JSON can be nlohmann::ordered_json
// Note: T_JSON can be rad::Json
template<typename T_JSON>
void global_from_json(context & ctx, const T_JSON & json_obj, bool mark_input);
/* One global from a JSON value, converted in place: a caller assembling several globals from
* JSON values it already holds (a chat render's messages and tools) need not first copy them
* into an intermediate JSON object for global_from_json to convert back out. */
void global_set_from_json(context & ctx, const std::string & key,
const rad::Json & j, bool mark_input);
//
// base value type
//
@@ -290,7 +298,9 @@ using value_float = std::shared_ptr<value_float_t>;
struct value_string_t : public value_t {
value_string_t() { val_str = string(); }
value_string_t(const std::string & v) { val_str = string(v); }
value_string_t(std::string && v) { val_str = string(std::move(v)); }
value_string_t(const string & v) { val_str = v; }
value_string_t(string && v) { val_str = std::move(v); }
virtual std::string type() const override { return "String"; }
virtual string as_string() const override { return val_str; }
virtual std::string as_repr() const override {
@@ -317,7 +327,7 @@ struct value_string_t : public value_t {
}
protected:
virtual bool equivalent(const value_t & other) const override {
return typeid(*this) == typeid(other) && val_str.str() == other.val_str.str();
return typeid(*this) == typeid(other) && val_str.equals(other.val_str);
}
};
using value_string = std::shared_ptr<value_string_t>;
@@ -459,6 +469,15 @@ protected:
};
using value_array = std::shared_ptr<value_array_t>;
/* A block statement's results, carried up to the gather that actually needs text. If and for
* statements used to gather their bodies into a fresh string at every nesting level, copying
* every shared part's bytes each time; as a carrier, the parts are only flattened once -- by
* the top-level render, or by exec_statements where a real string value is required (a set
* block, a macro body). It is an array for storage only: the gathers recurse into it where a
* plain array value would print its repr, and it never reaches template expressions. */
struct value_stmt_results_t : public value_array_t {};
using value_stmt_results = std::shared_ptr<value_stmt_results_t>;
struct value_tuple_t : public value_array_t {
value_tuple_t(value & v) {
@@ -482,13 +501,40 @@ using value_tuple = std::shared_ptr<value_tuple_t>;
struct value_object_t : public value_t {
std::unordered_map<value, value, value_hasher, value_equivalence> unordered;
/* The hash index over val_obj, built only once an object outgrows a linear scan. The
* objects a chat render builds by the thousand -- messages, calls, scopes -- hold a
* handful of keys each, and for those the map's bucket array and per-key nodes cost more
* than every lookup they would ever serve. val_obj stays the ordered authority either way. */
bool unordered_built_ = false;
static constexpr size_t kHashIndexThreshold = 32;
void build_unordered() {
if (unordered_built_) {
return;
}
unordered.reserve(val_obj.size() * 2);
for (const auto & pair : val_obj) {
unordered.emplace(pair.first, pair.second);
}
unordered_built_ = true;
}
void maybe_build_unordered() {
if (val_obj.size() > kHashIndexThreshold) {
build_unordered();
}
}
value * find_key_linear(const value & key) {
for (auto & pair : val_obj) {
if (*(pair.first) == *key) {
return &pair.second;
}
}
return nullptr;
}
bool has_builtins = true; // context and loop objects do not have builtins
value_object_t() = default;
value_object_t(value & v) {
val_obj = v->val_obj;
for (const auto & pair : val_obj) {
unordered[pair.first] = pair.second;
}
maybe_build_unordered();
}
value_object_t(const std::map<value, value> & obj) {
for (const auto & pair : obj) {
@@ -501,8 +547,32 @@ struct value_object_t : public value_t {
}
}
void insert(const std::string & key, const value & val) {
// The common case is re-binding a name that is already present (a loop variable, a
// scope copy): find it by name first so no key value is allocated for the lookup.
if (is_immutable()) {
throw std::runtime_error("Attempting to modify immutable type");
}
for (auto & pair : val_obj) {
const auto * ks = dynamic_cast<const value_string_t *>(pair.first.get());
if (ks && ks->val_str.parts.size() == 1 && ks->val_str.parts[0].val == key) {
pair.second = val;
if (unordered_built_) {
unordered[pair.first] = val;
}
return;
}
}
insert(mk_val<value_string>(key), val);
}
/* Take another object's entries wholesale (a scope inheriting its parent's variables):
* the ordered list copies in one allocation instead of a key allocation and a scan per
* variable. The hash index, if the size calls for one, is rebuilt from the copy. */
void copy_entries_from(const value_object_t & other) {
val_obj = other.val_obj;
unordered.clear();
unordered_built_ = false;
maybe_build_unordered();
}
virtual std::string type() const override { return "Object"; }
virtual bool is_immutable() const override { return false; }
virtual const std::vector<std::pair<value, value>> & as_ordered_object() const override { return val_obj; }
@@ -518,53 +588,125 @@ struct value_object_t : public value_t {
return ss.str();
}
virtual bool as_bool() const override {
return !unordered.empty();
return !val_obj.empty();
}
virtual bool has_key(const value & key) override {
if (!key->is_immutable() || !key->is_hashable()) {
throw std::runtime_error("Object key of unhashable type: " + key->type());
}
return unordered.find(key) != unordered.end();
if (unordered_built_) {
return unordered.find(key) != unordered.end();
}
return find_key_linear(key) != nullptr;
}
virtual void insert(const value & key, const value & val) override {
bool replaced = false;
if (is_immutable()) {
throw std::runtime_error("Attempting to modify immutable type");
}
if (has_key(key)) {
// if key exists, replace value in ordered list instead of appending
for (auto & pair : val_obj) {
if (*(pair.first) == *key) {
pair.second = val;
replaced = true;
break;
if (!key->is_immutable() || !key->is_hashable()) {
throw std::runtime_error("Object key of unhashable type: " + key->type());
}
if (unordered_built_) {
auto it = unordered.find(key);
if (it != unordered.end()) {
// if key exists, replace value in ordered list instead of appending
it->second = val;
for (auto & pair : val_obj) {
if (*(pair.first) == *key) {
pair.second = val;
break;
}
}
return;
}
}
unordered[key] = val;
if (!replaced) {
unordered.emplace(key, val);
val_obj.push_back({key, val});
return;
}
if (value * existing = find_key_linear(key)) {
*existing = val;
return;
}
val_obj.push_back({key, val});
maybe_build_unordered();
}
/* Insert a key the caller knows is absent (a fresh object's fields): no lookup first. */
void insert_new(const value & key, const value & val) {
if (is_immutable()) {
throw std::runtime_error("Attempting to modify immutable type");
}
if (unordered_built_) {
unordered.emplace(key, val);
}
val_obj.push_back({key, val});
maybe_build_unordered();
}
void insert_new(const std::string & key, const value & val) {
insert_new(mk_val<value_string>(key), val);
}
virtual value & at(const value & key, value & default_val) override {
if (!has_key(key)) {
return default_val;
if (!key->is_immutable() || !key->is_hashable()) {
throw std::runtime_error("Object key of unhashable type: " + key->type());
}
return unordered.at(key);
if (unordered_built_) {
auto it = unordered.find(key);
return it == unordered.end() ? default_val : it->second;
}
if (value * v = find_key_linear(key)) {
return *v;
}
return default_val;
}
virtual value & at(const value & key) override {
if (!has_key(key)) {
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
if (!key->is_immutable() || !key->is_hashable()) {
throw std::runtime_error("Object key of unhashable type: " + key->type());
}
return unordered.at(key);
if (unordered_built_) {
auto it = unordered.find(key);
if (it == unordered.end()) {
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
}
return it->second;
}
if (value * v = find_key_linear(key)) {
return *v;
}
throw std::runtime_error("Key '" + key->as_string().str() + "' not found in value of type " + type());
}
/* A string key by value, without allocating a key value and hashing it: objects here are
* message/argument records of a few keys, so the ordered scan is the cheaper lookup. */
value * find_string_key(const std::string & key) {
for (auto & pair : val_obj) {
const auto * ks = dynamic_cast<const value_string_t *>(pair.first.get());
if (!ks) {
continue;
}
size_t off = 0;
bool eq = true;
for (const auto & part : ks->val_str.parts) {
if (key.compare(off, part.val.size(), part.val) != 0) {
eq = false;
break;
}
off += part.val.size();
}
if (eq && off == key.size()) {
return &pair.second;
}
}
return nullptr;
}
virtual value & at(const std::string & key, value & default_val) override {
value key_val = mk_val<value_string>(key);
return at(key_val, default_val);
if (value * v = find_string_key(key)) {
return *v;
}
return default_val;
}
virtual value & at(const std::string & key) override {
value key_val = mk_val<value_string>(key);
return at(key_val);
if (value * v = find_string_key(key)) {
return *v;
}
throw std::runtime_error("Key '" + key + "' not found in value of type " + type());
}
virtual const func_builtins & get_builtins() const override;
virtual bool is_hashable() const override {
+151 -71
View File
@@ -2,12 +2,12 @@
#include "log.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <string>
#include <regex>
using json = nlohmann::ordered_json;
using json = rad::Json;
enum common_json_stack_element_type {
COMMON_JSON_STACK_ELEMENT_OBJECT,
@@ -36,84 +36,164 @@ bool common_json_parse(
const std::string & healing_marker,
common_json & out)
{
// // https://json.nlohmann.me/features/parsing/sax_interface/
struct json_error_locator : public nlohmann::json_sax<json> {
std::size_t position;
bool found_error;
std::string last_token;
std::string exception_message;
// What the healing below needs from a failed parse: where it stopped and which
// containers (and object key) were still open there. This was a SAX walk
// before the DOM swap; a small scanner over the (usually truncated) input produces the
// same stack and cut point. It only ever runs on text json::parse has already refused,
// and every healing candidate is re-parsed before it is believed, so the scanner tracks
// structure, not validity in the small (number and literal spellings are consumed, not
// checked).
struct json_error_locator {
std::size_t position = 0;
bool found_error = false;
std::vector<common_json_stack_element> stack;
json_error_locator() : position(0), found_error(false) {}
bool parse_error(std::size_t position, const std::string & last_token, const json::exception & ex) override { // NOLINT
this->position = position - 1;
this->found_error = true;
this->last_token = last_token;
this->exception_message = ex.what();
return false;
}
void close_value() {
if (!stack.empty() && (stack.back().type == COMMON_JSON_STACK_ELEMENT_KEY)) {
stack.pop_back();
}
}
bool null() override { // NOLINT
close_value();
return true;
}
bool boolean(bool) override { // NOLINT
close_value();
return true;
}
bool number_integer(number_integer_t) override { // NOLINT
close_value();
return true;
}
bool number_unsigned(number_unsigned_t) override { // NOLINT
close_value();
return true;
}
bool number_float(number_float_t, const string_t &) override { // NOLINT
close_value();
return true;
}
bool string(string_t &) override { // NOLINT
close_value();
return true;
}
bool binary(binary_t &) override { // NOLINT
close_value();
return true;
}
bool start_object(std::size_t) override { // NOLINT
stack.push_back({COMMON_JSON_STACK_ELEMENT_OBJECT, ""});
return true;
}
bool end_object() override {
GGML_ASSERT(!stack.empty() && stack.back().type == COMMON_JSON_STACK_ELEMENT_OBJECT);
stack.pop_back();
close_value();
return true;
}
bool key(string_t & key) override { // NOLINT
stack.push_back({COMMON_JSON_STACK_ELEMENT_KEY, key});
return true;
}
bool start_array(std::size_t) override { // NOLINT
stack.push_back({COMMON_JSON_STACK_ELEMENT_ARRAY, ""});
return true;
}
bool end_array() override {
GGML_ASSERT(!stack.empty() && stack.back().type == COMMON_JSON_STACK_ELEMENT_ARRAY);
stack.pop_back();
close_value();
return true;
}
};
json_error_locator err_loc;
auto start = it;
json::sax_parse(it, end, &err_loc);
{
const std::string text(it, end);
const char * s = text.data();
const size_t n = text.size();
size_t i = 0;
struct scan_stop {};
auto fail = [&](size_t at) {
err_loc.found_error = true;
err_loc.position = at;
throw scan_stop{};
};
std::function<void()> skip_ws = [&]() {
while (i < n && (s[i] == ' ' || s[i] == '\n' || s[i] == '\r' || s[i] == '\t')) {
++i;
}
};
std::function<bool()> scan_string = [&]() {
++i; // opening quote
while (true) {
if (i >= n) fail(n);
const char c = s[i];
if (c == '"') {
++i;
return true;
}
if (c == '\\') {
++i;
if (i >= n) fail(n);
if (s[i] == 'u') {
for (int k = 0; k < 4; ++k) {
++i;
if (i >= n || !std::isxdigit((unsigned char) s[i])) fail(i >= n ? n : i);
}
}
++i;
continue;
}
if ((unsigned char) c < 0x20) fail(i);
++i;
}
};
std::function<void(int)> scan_value = [&](int depth) {
if (depth > 512) fail(i);
skip_ws();
if (i >= n) fail(n);
const char c = s[i];
if (c == '{') {
++i;
err_loc.stack.push_back({COMMON_JSON_STACK_ELEMENT_OBJECT, ""});
skip_ws();
if (i < n && s[i] == '}') {
++i;
err_loc.stack.pop_back();
err_loc.close_value();
return;
}
while (true) {
skip_ws();
if (i >= n) fail(n);
if (s[i] != '"') fail(i);
scan_string();
err_loc.stack.push_back({COMMON_JSON_STACK_ELEMENT_KEY, ""});
skip_ws();
if (i >= n) fail(n);
if (s[i] != ':') fail(i);
++i;
scan_value(depth + 1);
skip_ws();
if (i >= n) fail(n);
if (s[i] == ',') {
++i;
continue;
}
if (s[i] == '}') {
++i;
err_loc.stack.pop_back();
err_loc.close_value();
return;
}
fail(i);
}
}
if (c == '[') {
++i;
err_loc.stack.push_back({COMMON_JSON_STACK_ELEMENT_ARRAY, ""});
skip_ws();
if (i < n && s[i] == ']') {
++i;
err_loc.stack.pop_back();
err_loc.close_value();
return;
}
while (true) {
scan_value(depth + 1);
skip_ws();
if (i >= n) fail(n);
if (s[i] == ',') {
++i;
continue;
}
if (s[i] == ']') {
++i;
err_loc.stack.pop_back();
err_loc.close_value();
return;
}
fail(i);
}
}
if (c == '"') {
scan_string();
err_loc.close_value();
return;
}
if (c == '-' || (c >= '0' && c <= '9')) {
while (i < n && (std::isdigit((unsigned char) s[i]) || s[i] == '-' || s[i] == '+' ||
s[i] == '.' || s[i] == 'e' || s[i] == 'E')) {
++i;
}
err_loc.close_value();
return;
}
if (std::isalpha((unsigned char) c)) {
while (i < n && std::isalpha((unsigned char) s[i])) {
++i;
}
err_loc.close_value();
return;
}
fail(i);
};
try {
scan_value(0);
skip_ws();
if (i < n) fail(i);
} catch (const scan_stop &) {
}
}
if (err_loc.found_error) {
it = start;
@@ -318,7 +398,7 @@ bool common_json_parse(
}
return false;
}
out.json = json::parse(it, end);
out.json = json::parse(std::string(it, end));
it = end;
return true;
}
+2 -2
View File
@@ -1,7 +1,7 @@
#pragma once
// TODO: use json_fwd.hpp when possible
#include <nlohmann/json.hpp>
#include "util/json.h"
// Healing marker (empty if the JSON was fully parsed / wasn't healed).
struct common_healing_marker {
@@ -14,7 +14,7 @@ struct common_healing_marker {
// Represents a parsed JSON object, with its optional healing marker (a JSON dump fragment that can be used to find the position of healing in the JSON dump string)
struct common_json {
nlohmann::ordered_json json;
rad::Json json;
common_healing_marker healing_marker;
};
+8 -7
View File
@@ -1,10 +1,11 @@
#include "json-schema-to-grammar.h"
#include "common.h"
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <algorithm>
#include <cctype>
#include <limits>
#include <map>
#include <regex>
#include <sstream>
@@ -13,7 +14,7 @@
#include <unordered_set>
#include <vector>
using json = nlohmann::ordered_json;
using json = rad::Json;
static std::string build_repetition(const std::string & item_rule, int min_items, int max_items, const std::string & separator_rule = "") {
auto has_max = max_items != std::numeric_limits<int>::max();
@@ -1437,11 +1438,11 @@ common_schema_info::~common_schema_info() = default;
common_schema_info::common_schema_info(common_schema_info &&) noexcept = default;
common_schema_info & common_schema_info::operator=(common_schema_info &&) noexcept = default;
void common_schema_info::resolve_refs(nlohmann::ordered_json & schema) {
void common_schema_info::resolve_refs(rad::Json & schema) {
impl_->resolve_refs(schema, "");
}
bool common_schema_info::unsatisfiable(const nlohmann::ordered_json & schema) const {
bool common_schema_info::unsatisfiable(const rad::Json & schema) const {
return common_schema_converter::is_unsatisfiable(schema);
}
@@ -1449,7 +1450,7 @@ bool common_schema_info::unsatisfiable(const nlohmann::ordered_json & schema) co
// Some models emit raw string values rather than JSON-encoded strings for string parameters.
// If any branch of the schema (via oneOf, anyOf, $ref, etc.) permits a string, this returns
// true, allowing callers to handle the value as a raw string for simplicity.
bool common_schema_info::resolves_to_string(const nlohmann::ordered_json & schema) {
bool common_schema_info::resolves_to_string(const rad::Json & schema) {
std::unordered_set<std::string> visited_refs;
std::function<bool(const json &)> check = [&](const json & s) -> bool {
@@ -1578,10 +1579,10 @@ std::string build_grammar(const std::function<void(const common_grammar_builder
/* .add_rule = */ [&](const std::string & name, const std::string & rule) {
return converter._add_rule(name, rule);
},
/* .add_schema = */ [&](const std::string & name, const nlohmann::ordered_json & schema) {
/* .add_schema = */ [&](const std::string & name, const rad::Json & schema) {
return converter.visit(schema, name == "root" ? "" : name);
},
/* .resolve_refs = */ [&](nlohmann::ordered_json & schema) {
/* .resolve_refs = */ [&](rad::Json & schema) {
converter.resolve_refs(schema, "");
}
};
+7 -7
View File
@@ -1,12 +1,12 @@
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "util/json.h"
#include <functional>
#include <memory>
#include <string>
std::string json_schema_to_grammar(const nlohmann::ordered_json & schema,
std::string json_schema_to_grammar(const rad::Json & schema,
bool force_gbnf = false);
class common_schema_converter;
@@ -24,17 +24,17 @@ class common_schema_info {
common_schema_info(common_schema_info &&) noexcept;
common_schema_info & operator=(common_schema_info &&) noexcept;
void resolve_refs(nlohmann::ordered_json & schema);
bool resolves_to_string(const nlohmann::ordered_json & schema);
void resolve_refs(rad::Json & schema);
bool resolves_to_string(const rad::Json & schema);
// RADIANCE: whether no value satisfies the schema -- `false`, or a `not` of a schema every
// value satisfies (`{}`, or types naming all six JSON types).
bool unsatisfiable(const nlohmann::ordered_json & schema) const;
bool unsatisfiable(const rad::Json & schema) const;
};
struct common_grammar_builder {
std::function<std::string(const std::string &, const std::string &)> add_rule;
std::function<std::string(const std::string &, const nlohmann::ordered_json &)> add_schema;
std::function<void(nlohmann::ordered_json &)> resolve_refs;
std::function<std::string(const std::string &, const rad::Json &)> add_schema;
std::function<void(rad::Json &)> resolve_refs;
};
struct common_grammar_options {
+12 -12
View File
@@ -9,7 +9,7 @@
#include <initializer_list>
#include <map>
#include <memory>
#include <nlohmann/json.hpp>
#include "util/json.h"
#include <regex>
#include <stdexcept>
#include <unordered_set>
@@ -1223,8 +1223,8 @@ common_peg_parser common_peg_parser_builder::chars(const std::string & classes,
return wrap(arena_.add_parser(common_peg_chars_parser{classes, ranges, negated, min, max}));
}
common_peg_parser common_peg_parser_builder::schema(const common_peg_parser & p, const std::string & name, const nlohmann::ordered_json & schema, bool raw) {
return wrap(arena_.add_parser(common_peg_schema_parser{p.id(), name, std::make_shared<nlohmann::ordered_json>(schema), raw}));
common_peg_parser common_peg_parser_builder::schema(const common_peg_parser & p, const std::string & name, const rad::Json & schema, bool raw) {
return wrap(arena_.add_parser(common_peg_schema_parser{p.id(), name, std::make_shared<rad::Json>(schema), raw}));
}
common_peg_parser common_peg_parser_builder::rule(const std::string & name, const common_peg_parser & p, bool trigger) {
@@ -1826,8 +1826,8 @@ void common_peg_arena::build_grammar(const common_grammar_builder & builder, boo
}
}
static nlohmann::json serialize_parser_variant(const common_peg_parser_variant & variant) {
using json = nlohmann::json;
static rad::Json serialize_parser_variant(const common_peg_parser_variant & variant) {
using json = rad::Json;
return std::visit([](const auto & p) -> json {
using T = std::decay_t<decltype(p)>;
@@ -1907,19 +1907,19 @@ static nlohmann::json serialize_parser_variant(const common_peg_parser_variant &
}, variant);
}
nlohmann::json common_peg_arena::to_json() const {
auto parsers = nlohmann::json::array();
rad::Json common_peg_arena::to_json() const {
auto parsers = rad::Json::array();
for (const auto & parser : parsers_) {
parsers.push_back(serialize_parser_variant(parser));
}
return nlohmann::json{
return rad::Json{
{"parsers", parsers},
{"rules", rules_},
{"root", root_}
};
}
static common_peg_parser_variant deserialize_parser_variant(const nlohmann::json & j) {
static common_peg_parser_variant deserialize_parser_variant(const rad::Json & j) {
if (!j.contains("type") || !j["type"].is_string()) {
throw std::runtime_error("Parser variant JSON missing or invalid 'type' field");
}
@@ -2026,7 +2026,7 @@ static common_peg_parser_variant deserialize_parser_variant(const nlohmann::json
parser.child = j["child"].get<common_peg_parser_id>();
parser.name = j["name"];
if (!j["schema"].is_null()) {
parser.schema = std::make_shared<nlohmann::ordered_json>(j["schema"]);
parser.schema = std::make_shared<rad::Json>(j["schema"]);
}
parser.raw = j["raw"].get<bool>();
return parser;
@@ -2078,7 +2078,7 @@ static common_peg_parser_variant deserialize_parser_variant(const nlohmann::json
throw std::runtime_error("Unknown parser type: " + type);
}
common_peg_arena common_peg_arena::from_json(const nlohmann::json & j) {
common_peg_arena common_peg_arena::from_json(const rad::Json & j) {
if (!j.contains("parsers") || !j["parsers"].is_array()) {
throw std::runtime_error("JSON missing or invalid 'parsers' array");
}
@@ -2118,7 +2118,7 @@ std::string common_peg_arena::save() const {
}
void common_peg_arena::load(const std::string & data) {
*this = from_json(nlohmann::json::parse(data));
*this = from_json(rad::Json::parse(data));
}
common_peg_arena build_peg_parser(const std::function<common_peg_parser(common_peg_parser_builder & builder)> & fn) {
+5 -5
View File
@@ -1,6 +1,6 @@
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "util/json.h"
#include <memory>
#include <unordered_map>
@@ -245,7 +245,7 @@ struct common_peg_until_parser {
struct common_peg_schema_parser {
common_peg_parser_id child;
std::string name;
std::shared_ptr<nlohmann::ordered_json> schema;
std::shared_ptr<rad::Json> schema;
// Indicates if the GBNF should accept a raw string that matches the schema.
bool raw;
@@ -326,8 +326,8 @@ class common_peg_arena {
std::string dump(common_peg_parser_id id) const;
nlohmann::json to_json() const;
static common_peg_arena from_json(const nlohmann::json & j);
rad::Json to_json() const;
static common_peg_arena from_json(const rad::Json & j);
std::string save() const;
void load(const std::string & data);
@@ -484,7 +484,7 @@ class common_peg_parser_builder {
// Wraps a parser with JSON schema metadata for grammar generation.
// Used internally to convert JSON schemas to GBNF grammar rules.
common_peg_parser schema(const common_peg_parser & p, const std::string & name, const nlohmann::ordered_json & schema, bool raw = false);
common_peg_parser schema(const common_peg_parser & p, const std::string & name, const rad::Json & schema, bool raw = false);
// Creates a named rule, stores it in the grammar, and returns a ref.
// If trigger=true, marks this rule as an entry point for lazy grammar generation.